Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PLAT-24830: Support captions clipping when serving WebVTT #12962

Open
wants to merge 5 commits into
base: Ursa-21.3.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions alpha/apps/kaltura/lib/kContextDataHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ class kContextDataHelper
private $streamerType = null;

private $mediaProtocol = null;

/**
* @var int
*/
private $clipFrom;

/**
* @var int
*/
private $clipTo;

/**
*
Expand Down Expand Up @@ -152,6 +162,38 @@ public function setMediaProtocol($protocol) {
$this->mediaProtocol = $protocol;
}

/**
* @return int
*/
public function getClipFrom()
{
return $this->clipFrom;
}

/**
* @param $clipFrom
*/
public function setClipFrom($clipFrom)
{
$this->clipFrom = $clipFrom;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets add logic that user cannot ask for clipFrom that that is longer than clip to and the opposite

}

/**
* @return int
*/
public function getClipTo()
{
return $this->clipTo;
}

/**
* @param $clipTo
*/
public function setClipTo($clipTo)
{
$this->clipTo = $clipTo;
}

public function buildContextDataResult($scope, $flavorTags, $streamerType, $mediaProtocol, $shouldHandleRuleCodes = false)
{
$this->streamerType = $streamerType;
Expand Down
2 changes: 2 additions & 0 deletions api_v3/lib/KalturaErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,8 @@ class KalturaErrors extends APIErrors

const FEATURE_RECYCLE_BIN_DISABLED = "FEATURE_RECYCLE_BIN_DISABLED;;Feature recycle bin is disabled for partner";

const CLIPPING_PARAMS_INVALID = "CLIPPING_PARAMS_INVALID;;Clipping parameters are invalid";

/*
* FileAsset Service
*/
Expand Down
8 changes: 8 additions & 0 deletions api_v3/lib/types/entry/KalturaPlaybackContextOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,13 @@
*/
class KalturaPlaybackContextOptions extends KalturaEntryContextDataParams
{
/**
* @var int
*/
public $clipFrom;

/**
* @var int
*/
public $clipTo;
}
8 changes: 8 additions & 0 deletions api_v3/services/BaseEntryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,14 @@ function getPlaybackContextAction($entryId, KalturaPlaybackContextOptions $conte
$contextDataHelper->setMediaProtocol($contextDataParams->mediaProtocol);
$contextDataHelper->setStreamerType($contextDataParams->streamerType);

if (isset($contextDataParams->clipFrom) && isset($contextDataParams->clipTo)
&& $contextDataParams->clipFrom >= $contextDataParams->clipTo)
{
throw new KalturaAPIException(KalturaErrors::CLIPPING_PARAMS_INVALID);
}
$contextDataHelper->setClipFrom($contextDataParams->clipFrom);
$contextDataHelper->setClipTo($contextDataParams->clipTo);

$playbackContextDataHelper = new kPlaybackContextDataHelper();
$playbackContextDataHelper->setIsScheduledNow($isScheduledNow);
$playbackContextDataHelper->constructPlaybackContextResult($contextDataHelper, $dbEntry);
Expand Down
17 changes: 12 additions & 5 deletions plugins/content/caption/base/CaptionPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -665,16 +665,23 @@ public function contributeToPlaybackContextDataResult(entry $entry, kPlaybackCon
continue;
}

$url = null;
$webVttUrl = null;

try
{

$url = $assetDb->getDownloadUrl(true, false, null, null, false);
if ($url)
{
$webVttUrl = myPartnerUtils::getCdnHost($assetDb->getPartnerId()) . self::SERVE_WEBVTT_URL_PREFIX . '/captionAssetId/' . $assetDb->getId() . '/segmentIndex/-1/version/' . $assetDb->getVersion() . '/captions.vtt';
$clipFrom = $contextDataHelper->getClipFrom();
$clipTo = $contextDataHelper->getClipTo();
$webVttUrl = myPartnerUtils::getCdnHost($assetDb->getPartnerId()) . self::SERVE_WEBVTT_URL_PREFIX . '/captionAssetId/' . $assetDb->getId() . '/segmentIndex/-1/version/' . $assetDb->getVersion();
if ($clipFrom)
{
$webVttUrl .= "/clipFrom/$clipFrom";
}
if ($clipTo)
{
$webVttUrl .= "/clipTo/$clipTo";
}
$webVttUrl .= '/captions.vtt';
$languageCode = languageCodeManager::getLanguageCode($assetDb->getLanguage(),$useThreeCodeLang);
$playbackCaptions [] = new kCaptionPlaybackPluginData($assetDb->getLabel(), $assetDb->getContainerFormat(), $assetDb->getLanguage(), $assetDb->getDefault(), $webVttUrl, $url, $languageCode);
}
Expand Down
144 changes: 101 additions & 43 deletions plugins/content/caption/base/lib/kWebVTTGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,25 @@ public static function formatWebVTTTimeStamp($timeStamp)
* @param int $entryDuration
* @return string
*/
public static function buildWebVTTM3U8File($segmentDuration, $entryDuration)
public static function buildWebVTTM3U8File($segmentDuration, $entryDuration, $clipFrom, $clipTo)
{
$result = "#EXTM3U\r\n";
$result .= "#EXT-X-TARGETDURATION:{$segmentDuration}\r\n";
$result .= "#EXT-X-VERSION:3\r\n";
$result .= "#EXT-X-MEDIA-SEQUENCE:1\r\n";
$result .= "#EXT-X-PLAYLIST-TYPE:VOD\r\n";
$segmentCount = ceil($entryDuration / $segmentDuration);
$lastSegmentDuration = $entryDuration - ($segmentCount - 1) * $segmentDuration;
$result = self::getManifestHeaderForWebVTT($segmentDuration);

$entryDurationMs = $entryDuration * 1000;
$linkParamsToConcat = '';
if ($clipTo && $entryDurationMs > $clipTo)
{
$entryDurationMs = $clipTo;
$linkParamsToConcat .= "clipTo/$clipTo/";
}
if ($clipFrom)
{
$entryDurationMs -= $clipFrom;
$linkParamsToConcat .= "clipFrom/$clipFrom/";
}

$segmentCount = ceil(($entryDurationMs / 1000) / $segmentDuration);
$lastSegmentDuration = ceil($entryDurationMs / 1000) - ($segmentCount - 1) * $segmentDuration;
for ($curIndex = 1; $curIndex <= $segmentCount; $curIndex++)
{
if ($curIndex == $segmentCount)
Expand All @@ -49,40 +59,48 @@ public static function buildWebVTTM3U8File($segmentDuration, $entryDuration)
{
$result .= "#EXTINF:{$segmentDuration}.0,\r\n";
}

$result .= $linkParamsToConcat;
$result .= "segmentIndex/{$curIndex}.vtt\r\n";
}
$result .= "#EXT-X-ENDLIST\r\n";
return $result;
}

protected static function getManifestHeaderForWebVTT($segmentDuration)
{
$result = "#EXTM3U\r\n";
$result .= "#EXT-X-TARGETDURATION:{$segmentDuration}\r\n";
$result .= "#EXT-X-VERSION:3\r\n";
$result .= "#EXT-X-MEDIA-SEQUENCE:1\r\n";
$result .= "#EXT-X-PLAYLIST-TYPE:VOD\r\n";
return $result;
}

/**
* @param array $parsedCaption
* @param int $segmentIndex
* @param int $segmentDuration
* @param int $localTimestamp
* @return string
*/
public static function buildWebVTTSegment(array $parsedCaption, $segmentIndex, $segmentDuration, $localTimestamp)
public static function buildWebVTTSegment(array $parsedCaption, $segmentIndex, $segmentDuration, $localTimestamp, $clipFrom, $clipTo)
{
$segmentStartTime = ($segmentIndex - 1) * $segmentDuration * 1000;
$segmentEndTime = $segmentIndex * $segmentDuration * 1000;
$result = self::getSegmentHeaderForWebVTT($localTimestamp);

$result = "WEBVTT\n";
if ($localTimestamp != 10000)
{
$result .= "X-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:" . self::formatWebVTTTimeStamp($localTimestamp) . "\n";
}
$result .= "\n";
[$segmentStartTime, $segmentEndTime] = self::calculateSegmentTime($segmentIndex, $segmentDuration, $clipFrom, $clipTo);

foreach ($parsedCaption as $curCaption)
{
if ($segmentIndex != -1 && ($curCaption["startTime"] < $segmentStartTime || $curCaption["startTime"] >= $segmentEndTime) &&
($curCaption["endTime"] < $segmentStartTime || $curCaption["endTime"] >= $segmentEndTime)
)
if (self::validateCaptionTimeFrame($curCaption, $segmentStartTime, $segmentEndTime))
{
continue;
}

if ($curCaption["startTime"]>=$curCaption["endTime"])
if ($curCaption['startTime'] >= $curCaption['endTime'])
{
continue;
}

// calculate line-level styling
$styling = array();
Expand All @@ -91,18 +109,18 @@ public static function buildWebVTTSegment(array $parsedCaption, $segmentIndex, $
{
$style = $firstChunk['style'];

$aligmentMapping = array('left' => 'start', 'right' => 'end', 'center' => 'middle', 'full' => 'middle');
$alignmentMapping = array('left' => 'start', 'right' => 'end', 'center' => 'middle', 'full' => 'middle');
if (isset($style['textAlign']))
{
if (isset($aligmentMapping[$style['textAlign']]))
$styling['align'] = $aligmentMapping[$style['textAlign']];
if (isset($alignmentMapping[$style['textAlign']]))
$styling['align'] = $alignmentMapping[$style['textAlign']];
else
$styling['align'] = $style['align'];
}

$aligmentMapping = array('before' => '0%', 'center' => '50%', 'after' => '100%');
if (isset($style['displayAlign']) && isset($aligmentMapping[$style['displayAlign']]))
$styling['line'] = $aligmentMapping[$style['displayAlign']];
$alignmentMapping = array('before' => '0%', 'center' => '50%', 'after' => '100%');
if (isset($style['displayAlign']) && isset($alignmentMapping[$style['displayAlign']]))
$styling['line'] = $alignmentMapping[$style['displayAlign']];

if (isset($style['origin']))
{
Expand Down Expand Up @@ -159,26 +177,20 @@ public static function buildWebVTTSegment(array $parsedCaption, $segmentIndex, $
* @param int $localTimestamp
* @return string
*/
public static function getSegmentFromWebVTT($captionsContentManager, $webVTTcontent, $segmentIndex, $segmentDuration, $localTimestamp)
public static function getSegmentFromWebVTT($captionsContentManager, $webVTTcontent, $segmentIndex, $segmentDuration, $localTimestamp, $clipFrom, $clipTo)
{
$parsedCaption = $captionsContentManager->parseWebVTT($webVTTcontent);
$headerInfo = $captionsContentManager->headerInfo;

$segmentStartTime = ($segmentIndex - 1) * $segmentDuration * 1000;
$segmentEndTime = $segmentIndex * $segmentDuration * 1000;

$result = implode('', $headerInfo);
if ($localTimestamp != 10000)
{
$result .= "X-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:" . self::formatWebVTTTimeStamp($localTimestamp) . "\n";
}
$result .= "\n";
$result = self::getSegmentHeaderForWebVTT($localTimestamp, $captionsContentManager->headerInfo);

[$segmentStartTime, $segmentEndTime] = self::calculateSegmentTime($segmentIndex, $segmentDuration, $clipFrom, $clipTo);

$parsedCaption = $captionsContentManager->parseWebVTT($webVTTcontent);
foreach ($parsedCaption as $curCaption)
{
if ($segmentIndex != -1 && ($curCaption["startTime"] < $segmentStartTime || $curCaption["startTime"] >= $segmentEndTime) &&
($curCaption["endTime"] < $segmentStartTime || $curCaption["endTime"] >= $segmentEndTime))
continue;
if (self::validateCaptionTimeFrame($curCaption, $segmentStartTime, $segmentEndTime))
{
continue;
}

// calculate the line content
$content = '';
foreach ($curCaption['content'] as $curChunk)
Expand All @@ -194,10 +206,56 @@ public static function getSegmentFromWebVTT($captionsContentManager, $webVTTcont
self::formatWebVTTTimeStamp($curCaption["endTime"]) ."\n";
$result .= trim($content) . "\n\n";
}

$result .="\n\n\n";

return $result;
}

protected static function getSegmentHeaderForWebVTT($localTimestamp, $headerInfo = null)
{
$result = isset($headerInfo) ? implode('', $headerInfo) : "WEBVTT\n";
if ($localTimestamp != 10000)
{
$result .= "X-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:" . self::formatWebVTTTimeStamp($localTimestamp) . "\n";
}
$result .= "\n";
return $result;
}

protected static function calculateSegmentTime($segmentIndex, $segmentDuration, $clipFrom, $clipTo)
{
$segmentStartTime = $clipFrom ?: 0;

if ($segmentIndex == -1)
{
if (!$clipFrom && !$clipTo)
{
return array(-1, -1);
}
}
else
{
$segmentStartTime += ($segmentIndex - 1) * $segmentDuration * 1000;
}

$segmentEndTime = $segmentStartTime + $segmentDuration * 1000;

if ($clipTo && $clipTo < $segmentEndTime)
{
$segmentEndTime = $clipTo;
}

return array($segmentStartTime, $segmentEndTime);
}

protected static function validateCaptionTimeFrame($curCaption, $segmentStartTime, $segmentEndTime)
{
return $segmentStartTime > -1 && $segmentEndTime > -1
&& ($curCaption['startTime'] < $segmentStartTime || $curCaption['startTime'] >= $segmentEndTime)
&& ($curCaption['endTime'] < $segmentStartTime || $curCaption['endTime'] >= $segmentEndTime);
}

/**
* @param string $textLine
* @return string
Expand Down
12 changes: 7 additions & 5 deletions plugins/content/caption/base/services/CaptionAssetService.php
Original file line number Diff line number Diff line change
Expand Up @@ -649,12 +649,14 @@ public function serveAsJsonAction($captionAssetId)
* @param int $segmentDuration
* @param int $segmentIndex
* @param int $localTimestamp
* @return file
* @param int $clipFrom
* @param int $clipTo
* @return files
* @ksOptional
*
* @throws KalturaCaptionErrors::CAPTION_ASSET_ID_NOT_FOUND
*/
public function serveWebVTTAction($captionAssetId, $segmentDuration = 30, $segmentIndex = null, $localTimestamp = 10000)
public function serveWebVTTAction($captionAssetId, $segmentDuration = 30, $segmentIndex = null, $localTimestamp = 10000, $clipFrom = null, $clipTo = null)
{
$captionAsset = $this->validateForDownload($captionAssetId);

Expand All @@ -666,7 +668,7 @@ public function serveWebVTTAction($captionAssetId, $segmentDuration = 30, $segme
throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_ENTRY_ID_NOT_FOUND, $captionAsset->getEntryId());
entryPeer::setUseCriteriaFilter(true);

return new kRendererString(kWebVTTGenerator::buildWebVTTM3U8File($segmentDuration, (int)$entry->getDuration()), 'application/x-mpegurl');
return new kRendererString(kWebVTTGenerator::buildWebVTTM3U8File($segmentDuration, (int)$entry->getDuration(), $clipFrom, $clipTo), 'application/x-mpegurl');
}
$syncKey = $captionAsset->getSyncKey(asset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
$content = kFileSyncUtils::file_get_contents($syncKey, true, false, self::MAX_SERVE_WEBVTT_FILE_SIZE);
Expand All @@ -687,13 +689,13 @@ public function serveWebVTTAction($captionAssetId, $segmentDuration = 30, $segme
throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_INVALID_FORMAT, $captionAssetId);

if ($captionAsset->getContainerFormat() == CaptionType::WEBVTT)
return new kRendererString(kWebVTTGenerator::getSegmentFromWebVTT($captionsContentManager, $content, $segmentIndex, $segmentDuration, $localTimestamp), 'text/vtt');
return new kRendererString(kWebVTTGenerator::getSegmentFromWebVTT($captionsContentManager, $content, $segmentIndex, $segmentDuration, $localTimestamp, $clipFrom, $clipTo), 'text/vtt');
else
{
$parsedCaption = $captionsContentManager->parse($content);
if (!$parsedCaption)
throw new KalturaAPIException(KalturaCaptionErrors::CAPTION_ASSET_PARSING_FAILED, $captionAssetId);
return new kRendererString(kWebVTTGenerator::buildWebVTTSegment($parsedCaption, $segmentIndex, $segmentDuration, $localTimestamp), 'text/vtt');
return new kRendererString(kWebVTTGenerator::buildWebVTTSegment($parsedCaption, $segmentIndex, $segmentDuration, $localTimestamp, $clipFrom, $clipTo), 'text/vtt');
}
}

Expand Down