Skip to content

Instantly share code, notes, and snippets.

@ildarusmanov
Last active October 23, 2019 10:30
Show Gist options
  • Save ildarusmanov/3554f1f25fd59c74957eb17fe1237152 to your computer and use it in GitHub Desktop.
Save ildarusmanov/3554f1f25fd59c74957eb17fe1237152 to your computer and use it in GitHub Desktop.
<?php
/*
composer.json
{
"require": {
"chrisyue/php-m3u8": "^1.2"
}
}
*/
require __DIR__ . '/vendor/autoload.php';
$ts = isset($_REQUEST['ts']) ? intval($_REQUEST['ts']) : 0;
$offset = time() - $ts;
if ($ts == 0) {
die();
}
define('PLAYLIST_PATH', __DIR__ . '/index.m3u8');
define('MAX_SIZE', 10000);
header("Content-type: application/x-mpegURL");
$content = file_get_contents(PLAYLIST_PATH);
$parser = new \Chrisyue\PhpM3u8\Parser();
$data = $parser->parse($content);
$pl = $data->getPlaylist();
$resultSegments = [];
$resultSize = 5;
$timeLeft = 0.0;
$i = 0;
while ($pl->valid()) {
if ($i > MAX_SIZE) {
break;
}
$timeLeft += $pl->current()->getDuration();
if ($timeLeft >= $offset) {
$resultSegments[] = $pl->current();
}
if (count($resultSegments) >= $resultSize) {
break;
}
$i++;
$pl->next();
}
echo '#EXTM3U' . PHP_EOL;
echo '#EXT-X-PLAYLIST-TYPE:LIVE' . PHP_EOL;
echo '#EXT-X-VERSION:3' . PHP_EOL;
echo '#EXT-X-TARGETDURATION:' . $data->getTargetDuration() . PHP_EOL;
echo '#EXT-X-MEDIA-SEQUENCE:' . ($i - count($resultSegments)) . PHP_EOL;
foreach ($resultSegments as $segment) {
echo '#EXTINF:' . $segment->getDuration() . ',' . PHP_EOL;
echo $segment->getUri() . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment