view release on metacpan or search on metacpan
lib/MHFS/Plugin/GetVideo.pm view on Meta::CPAN
}, 'ext' => 'm3u8', 'desired_audio' => 'aac',
'player_html' => $settings->{'DOCUMENTROOT'} . '/static/hls_player.html'},
'jsmpeg' => {'lock' => 0, 'create_cmd' => sub {
my ($video) = @_;
return ['ffmpeg', '-i', $video->{"src_file"}{"filepath"}, '-f', 'mpegts', '-codec:v', 'mpeg1video', '-codec:a', 'mp2', '-b', '0', $video->{"out_filepath"}];
}, 'ext' => 'ts', 'player_html' => $settings->{'DOCUMENTROOT'} . '/static/jsmpeg_player.html', 'minsize' => '1048576'},
'mp4' => {'lock' => 1, 'create_cmd' => sub {
my ($video) = @_;
return ['ffmpeg', '-i', $video->{"src_file"}{"filepath"}, '-c:v', 'copy', '-c:a', 'aac', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', $video->{"out_filepath"}];
}, 'ext' => 'mp4', 'player_html' => $settings->{'DOCUMENTROOT'} . '/static/mp4_player.html', 'minsize' => '1048576'},
'noconv' => {'lock' => 0, 'ext' => '', 'player_html' => $settings->{'DOCUMENTROOT'} . '/static/noconv_player.html', },
'mkvinfo' => {'lock' => 0, 'ext' => ''},
'fmp4' => {'lock' => 0, 'ext' => ''},
};
$self->{'routes'} = [
[
lib/MHFS/Plugin/GetVideo.pm view on Meta::CPAN
$request->SendAsJSON($obj);
}
sub get_video_fmp4 {
my ($request, $fileabspath) = @_;
my @command = ('ffmpeg', '-loglevel', 'fatal');
if($request->{'qs'}{'fmp4_time'}) {
my $formattedtime = hls_audio_formattime($request->{'qs'}{'fmp4_time'});
push @command, ('-ss', $formattedtime);
}
push @command, ('-i', $fileabspath, '-c:v', 'copy', '-c:a', 'aac', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', '-');
my $evp = $request->{'client'}{'server'}{'evp'};
my $sent;
print "$_ " foreach @command;
$request->{'outheaders'}{'Accept-Ranges'} = 'none';
# avoid bookkeeping, have ffmpeg output straight to the socket
$request->{'outheaders'}{'Connection'} = 'close';
$request->{'outheaders'}{'Content-Type'} = 'video/mp4';
my $sock = $request->{'client'}{'sock'};
print $sock "HTTP/1.0 200 OK\r\n";
share/public_html/static/hls.js view on Meta::CPAN
// fired when a level switch is requested - data: { level : id of new level }
LEVEL_SWITCHING: 'hlsLevelSwitching',
// fired when a level switch is effective - data: { level : id of new level }
LEVEL_SWITCHED: 'hlsLevelSwitched',
// fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
LEVEL_LOADING: 'hlsLevelLoading',
// fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
LEVEL_LOADED: 'hlsLevelLoaded',
// fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
LEVEL_UPDATED: 'hlsLevelUpdated',
// fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
// fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
// fired when an audio track switching is requested - data: { id : audio track id }
AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
// fired when an audio track switch actually occurs - data: { id : audio track id }
AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
// fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
// fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
// fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
// fired when an subtitle track switch occurs - data: { id : subtitle track id }
SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
// fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
// fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
// fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
// fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
INIT_PTS_FOUND: 'hlsInitPtsFound',
// fired when a fragment loading starts - data: { frag : fragment object }
FRAG_LOADING: 'hlsFragLoading',
// fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
// Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
// fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
FRAG_LOADED: 'hlsFragLoaded',
// fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
FRAG_DECRYPTED: 'hlsFragDecrypted',
// fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
// fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
// fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
// fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
FRAG_PARSING_DATA: 'hlsFragParsingData',
// fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
FRAG_PARSED: 'hlsFragParsed',
// fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
FRAG_BUFFERED: 'hlsFragBuffered',
// fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
FRAG_CHANGED: 'hlsFragChanged',
// Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
FPS_DROP: 'hlsFpsDrop',
// triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
// Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
ERROR: 'hlsError',
// fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
DESTROYING: 'hlsDestroying',
// fired when a decrypt key loading starts - data: { frag : fragment object }
KEY_LOADING: 'hlsKeyLoading',
// fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
KEY_LOADED: 'hlsKeyLoaded',
// fired upon stream controller state transitions - data: { previousState, nextState }
STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
};
/* harmony default export */ __webpack_exports__["a"] = (HlsEvents);
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
share/public_html/static/hls.js view on Meta::CPAN
// Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
LEVEL_LOAD_ERROR: 'levelLoadError',
// Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
// Identifier for a level switch error - data: { level : faulty level Id, event : error description}
LEVEL_SWITCH_ERROR: 'levelSwitchError',
// Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
// Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
// Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
FRAG_LOAD_ERROR: 'fragLoadError',
// Identifier for fragment load timeout error - data: { frag : fragment object}
FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
// Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
FRAG_DECRYPT_ERROR: 'fragDecryptError',
// Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
// will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
FRAG_PARSING_ERROR: 'fragParsingError',
// Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
REMUX_ALLOC_ERROR: 'remuxAllocError',
// Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
KEY_LOAD_ERROR: 'keyLoadError',
// Identifier for decrypt key load timeout error - data: { frag : fragment object}
KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
// Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
// Identifier for a buffer append error - data: append error description
BUFFER_APPEND_ERROR: 'bufferAppendError',
// Identifier for a buffer appending error event - data: appending error description
BUFFER_APPENDING_ERROR: 'bufferAppendingError',
// Identifier for a buffer stalled error event
BUFFER_STALLED_ERROR: 'bufferStalledError',
// Identifier for a buffer full event
share/public_html/static/hls.js view on Meta::CPAN
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
share/public_html/static/hls.js view on Meta::CPAN
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || ''
};
},
normalizePath: function(path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
share/public_html/static/hls.js view on Meta::CPAN
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
return path.split('').reverse().join('');
},
buildURLFromParts: function(parts) {
return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
}
};
/* jshint ignore:start */
if(true)
module.exports = URLToolkit;
else if(typeof define === 'function' && define.amd)
define([], function() { return URLToolkit; });
else if(typeof exports === 'object')
exports["URLToolkit"] = URLToolkit;
share/public_html/static/hls.js view on Meta::CPAN
}
}
}
}
});
return result;
};
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param timescale {object} a hash of track ids to timescale values.
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
var trafs = void 0,
baseTimes = void 0,
result = void 0;
// we need info from two childrend of each track fragment box
trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
// determine the start times for each track
baseTimes = [].concat.apply([], trafs.map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
var id = void 0,
scale = void 0,
baseTime = void 0;
// get the track id from the tfhd
id = MP4Demuxer.readUint32(tfhd, 4);
share/public_html/static/hls.js view on Meta::CPAN
// convert base time to seconds
return baseTime / scale;
});
}));
// return the minimum
result = Math.min.apply(null, baseTimes);
return isFinite(result) ? result : 0;
};
MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
// get the track id from the tfhd
var id = MP4Demuxer.readUint32(tfhd, 4);
// assume a 90kHz clock if no timescale was specified
var timescale = initData[id].timescale || 90e3;
// get the base media decode time from the tfdt
MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
share/public_html/static/hls.js view on Meta::CPAN
return true;
}
};
TSDemuxer._syncOffset = function _syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
};
/**
share/public_html/static/hls.js view on Meta::CPAN
}
} else {
this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
}
}
// try to parse last PES packets
if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
if (audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData && audioData.size) {
logger["b" /* logger */].log('last AAC PES packet truncated,might overlap between fragments');
}
// either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
if (this.sampleAes == null) {
this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
} else {
this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
share/public_html/static/hls.js view on Meta::CPAN
}
// move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
}
return result;
};
TSDemuxer.prototype._parsePES = function _parsePES(stream) {
var i = 0,
frag = void 0,
pesFlags = void 0,
pesPrefix = void 0,
pesLen = void 0,
pesHdrLen = void 0,
pesData = void 0,
pesPts = void 0,
pesDts = void 0,
payloadStartOffset = void 0,
data = stream.data;
// safety check
share/public_html/static/hls.js view on Meta::CPAN
// we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
}
// retrieve PTS/DTS from first fragment
frag = data[0];
pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5];
// if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
pesFlags = frag[7];
if (pesFlags & 0xC0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
(frag[10] & 0xFF) * 4194304 + // 1 << 22
(frag[11] & 0xFE) * 16384 + // 1 << 14
(frag[12] & 0xFF) * 128 + // 1 << 7
(frag[13] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesPts > 4294967295) {
// decrement 2^33
pesPts -= 8589934592;
}
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
(frag[15] & 0xFF) * 4194304 + // 1 << 22
(frag[16] & 0xFE) * 16384 + // 1 << 14
(frag[17] & 0xFF) * 128 + // 1 << 7
(frag[18] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesDts > 4294967295) {
// decrement 2^33
pesDts -= 8589934592;
}
if (pesPts - pesDts > 60 * 90000) {
logger["b" /* logger */].warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8];
// 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
payloadStartOffset = pesHdrLen + 9;
stream.size -= payloadStartOffset;
// reassemble PES packet
pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
} else {
return null;
}
};
TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
// only push AVC sample if starting with a keyframe is not mandatory OR
// if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
avcSample.id = nbSamples;
samples.push(avcSample);
} else {
// dropped samples, track it
avcTrack.dropped++;
}
}
if (avcSample.debug.length) {
logger["b" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
share/public_html/static/hls.js view on Meta::CPAN
if (!this.ISGenerated) {
this.generateIS(audioTrack, videoTrack, timeOffset);
}
if (this.ISGenerated) {
var nbAudioSamples = audioTrack.samples.length;
var nbVideoSamples = videoTrack.samples.length;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset;
if (nbAudioSamples && nbVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts) / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoDeltaDts);
videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
}
// Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
// calculated in remuxAudio.
// logger.log('nb AAC samples:' + audioTrack.samples.length);
share/public_html/static/hls.js view on Meta::CPAN
// let unitsString = '';
// for (let j = 0; j < units.length ; j++) {
// unitsString += units[j].type + ',';
// if (units[j].data.length < 500) {
// unitsString += Hex.hexDump(units[j].data);
// }
// }
// logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);
// }
// if parsed fragment is contiguous with last one, let's use last DTS value as reference
var nextAvcDts = this.nextAvcDts;
var isSafari = this.isSafari;
if (nbSamples === 0) {
return;
}
// Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
if (isSafari) {
// also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 200 ms PTS gaps (timeScale/5)
contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5);
}
if (!contiguous) {
// if not contiguous, let's use target timeOffset
nextAvcDts = timeOffset * timeScale;
}
share/public_html/static/hls.js view on Meta::CPAN
for (var i = 0; i < inputSamples.length; i++) {
inputSamples[i].dts += PTSDTSshift;
}
}
// compute first DTS and last DTS, normalize them against reference value
var sample = inputSamples[0];
firstDTS = Math.max(sample.dts, 0);
firstPTS = Math.max(sample.pts, 0);
// check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = Math.round((firstDTS - nextAvcDts) / 90);
// if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
if (delta) {
if (delta > 1) {
logger["b" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it');
} else if (delta < -1) {
logger["b" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected');
}
// remove hole/gap : set DTS to next expected DTS
firstDTS = nextAvcDts;
inputSamples[0].dts = firstDTS;
// offset PTS as well, ensure that PTS is smaller or equal than new DTS
firstPTS = Math.max(firstPTS - delta, nextAvcDts);
inputSamples[0].pts = firstPTS;
logger["b" /* logger */].log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
}
share/public_html/static/hls.js view on Meta::CPAN
mp4Sample = void 0,
fillFrame = void 0,
mdat = void 0,
moof = void 0,
firstPTS = void 0,
lastPTS = void 0,
inputSamples = track.samples,
outputSamples = [],
nextAudioPts = this.nextAudioPts;
// for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);
// compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);
});
// filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
});
// in case all samples have negative PTS, and have been filtered out, return now
if (inputSamples.length === 0) {
return;
}
if (!contiguous) {
if (!accurateTimeOffset) {
// if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].pts;
} else {
// if timeOffset is accurate, let's use it as predicted next audio PTS
nextAudioPts = timeOffset * inputTimeScale;
}
}
// If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
share/public_html/static/hls.js view on Meta::CPAN
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
// logger.log(`Audio/PTS:${Math.round(pts/90)}`);
// if not first sample
if (lastPTS !== undefined) {
mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
numMissingFrames = 0;
// if fragment are contiguous, detect hole/overlapping between fragments
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
if (contiguous && track.isAAC) {
// log delta
if (_delta) {
if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
logger["b" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it');
if (numMissingFrames > 0) {
fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
fillFrame = unit.subarray();
share/public_html/static/hls.js view on Meta::CPAN
return PassThroughRemuxer;
}();
/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
// CONCATENATED MODULE: ./src/demux/demuxer-inline.js
function demuxer_inline__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
*
* inline demuxer: probe fragments and instantiate
* appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
*
*/
share/public_html/static/hls.js view on Meta::CPAN
}
return this._uri;
}
}]);
return LevelKey;
}();
/* harmony default export */ var level_key = (level_key_LevelKey);
// CONCATENATED MODULE: ./src/loader/fragment.js
var fragment__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("valu...
function fragment__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fragment_Fragment = function () {
function Fragment() {
var _elementaryStreams;
fragment__classCallCheck(this, Fragment);
this._url = null;
this._byteRange = null;
this._decryptdata = null;
this.tagList = [];
// Holds the types of data this fragment supports
this._elementaryStreams = (_elementaryStreams = {}, _elementaryStreams[Fragment.ElementaryStreamTypes.AUDIO] = false, _elementaryStreams[Fragment.ElementaryStreamTypes.VIDEO] = false, _elementaryStreams);
}
/**
* `type` property for this._elementaryStreams
*
* @enum
*/
share/public_html/static/hls.js view on Meta::CPAN
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
};
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {*} - an object to be applied as a fragment's decryptdata
*/
Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
decryptdata = new level_key();
decryptdata.method = levelkey.method;
decryptdata.baseuri = levelkey.baseuri;
decryptdata.reluri = levelkey.reluri;
decryptdata.iv = this.createInitializationVector(segmentNumber);
}
return decryptdata;
};
fragment__createClass(Fragment, [{
key: 'url',
get: function get() {
if (!this._url && this.relurl) {
this._url = url_toolkit_default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
}
return this._url;
},
set: function set(value) {
this._url = value;
share/public_html/static/hls.js view on Meta::CPAN
}
}, {
key: 'byteRangeEndOffset',
get: function get() {
return this.byteRange[1];
}
}, {
key: 'decryptdata',
get: function get() {
if (!this._decryptdata) {
this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
}
return this._decryptdata;
}
}, {
key: 'encrypted',
get: function get() {
return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
}
}], [{
share/public_html/static/hls.js view on Meta::CPAN
return {
AUDIO: 'audio',
VIDEO: 'video'
};
}
}]);
return Fragment;
}();
/* harmony default export */ var loader_fragment = (fragment_Fragment);
// CONCATENATED MODULE: ./src/utils/attr-list.js
function attr_list__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = function () {
function AttrList(attrs) {
share/public_html/static/hls.js view on Meta::CPAN
media.id = id++;
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var currentSN = 0,
totalduration = 0,
level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },
levelkey = new level_key(),
cc = 0,
prevFrag = null,
frag = new loader_fragment(),
result = void 0,
i = void 0;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration);
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (!isNaN(frag.duration)) {
var sn = currentSN++;
frag.type = type;
frag.start = totalduration;
frag.levelkey = levelkey;
frag.sn = sn;
frag.level = id;
frag.cc = cc;
frag.urlId = levelUrlId;
frag.baseurl = baseurl;
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
if (level.programDateTime) {
if (prevFrag) {
if (frag.rawProgramDateTime) {
// PDT discontinuity found
frag.pdt = Date.parse(frag.rawProgramDateTime);
} else {
// Contiguous fragment
frag.pdt = prevFrag.pdt + prevFrag.duration * 1000;
}
} else {
// First fragment
frag.pdt = Date.parse(level.programDateTime);
}
frag.endPdt = frag.pdt + frag.duration * 1000;
}
level.fragments.push(frag);
prevFrag = frag;
totalduration += frag.duration;
frag = new loader_fragment();
}
} else if (result[4]) {
// X-BYTERANGE
frag.rawByteRange = (' ' + result[4]).slice(1);
if (prevFrag) {
var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
if (lastByteRangeEndOffset) {
frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
}
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (level.programDateTime === undefined) {
level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration);
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
for (i = 1; i < result.length; i++) {
if (result[i] !== undefined) {
break;
}
}
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = (' ' + result[i + 2]).slice(1);
switch (result[i]) {
case '#':
frag.tagList.push(value2 ? [value1, value2] : [value1]);
break;
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
frag.tagList.push(['DIS']);
break;
case 'DISCONTINUITY-SEQ':
cc = parseInt(value1);
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = value1;
var keyAttrs = new attr_list(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
share/public_html/static/hls.js view on Meta::CPAN
var startAttrs = new attr_list(startParams);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
// TIME-OFFSET can be 0
if (!isNaN(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
case 'MAP':
var mapAttrs = new attr_list(value1);
frag.relurl = mapAttrs.URI;
frag.rawByteRange = mapAttrs.BYTERANGE;
frag.baseurl = baseurl;
frag.level = id;
frag.type = type;
frag.sn = 'initSegment';
level.initSegment = frag;
frag = new loader_fragment();
break;
default:
logger["b" /* logger */].warn('line parsed but not handled: ' + result);
break;
}
}
}
frag = prevFrag;
// logger.log('found ' + level.fragments.length + ' fragments');
if (frag && !frag.relurl) {
level.fragments.pop();
totalduration -= frag.duration;
}
level.totalduration = totalduration;
level.averagetargetduration = totalduration / level.fragments.length;
level.endSN = currentSN - 1;
level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
level.endCC = cc;
if (!level.initSegment && level.fragments.length) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return MP4_REGEX_SUFFIX.test(frag.relurl);
})) {
logger["b" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new loader_fragment();
frag.relurl = level.fragments[0].relurl;
frag.baseurl = baseurl;
frag.level = id;
frag.type = type;
frag.sn = 'initSegment';
level.initSegment = frag;
level.needSidxRanges = true;
}
}
return level;
};
return M3U8Parser;
}();
share/public_html/static/hls.js view on Meta::CPAN
// extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this._handlePlaylistLoaded(response, stats, context, networkDetails);
};
PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) {
var sidxInfo = mp4demuxer["a" /* default */].parseSegmentIndex(new Uint8Array(response.data));
sidxInfo.references.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
var frag = context.levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
}
});
context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
};
PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(events["a" /* default */].ERROR, {
type: errors["b" /* ErrorTypes */].NETWORK_ERROR,
details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR,
share/public_html/static/hls.js view on Meta::CPAN
key: 'LevelType',
get: function get() {
return LevelType;
}
}]);
return PlaylistLoader;
}(event_handler);
/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
// CONCATENATED MODULE: ./src/loader/fragment-loader.js
function fragment_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function fragment_loader__possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : s...
function fragment_loader__inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Obje...
/*
* Fragment Loader
*/
var fragment_loader_FragmentLoader = function (_EventHandler) {
fragment_loader__inherits(FragmentLoader, _EventHandler);
function FragmentLoader(hls) {
fragment_loader__classCallCheck(this, FragmentLoader);
var _this = fragment_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING));
_this.loaders = {};
return _this;
}
FragmentLoader.prototype.destroy = function destroy() {
var loaders = this.loaders;
for (var loaderName in loaders) {
var loader = loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
_EventHandler.prototype.destroy.call(this);
};
FragmentLoader.prototype.onFragLoading = function onFragLoading(data) {
var frag = data.frag,
type = frag.type,
loaders = this.loaders,
config = this.hls.config,
FragmentILoader = config.fLoader,
DefaultILoader = config.loader;
// reset fragment state
frag.loaded = 0;
var loader = loaders[type];
if (loader) {
logger["b" /* logger */].warn('abort previous fragment loader for type: ' + type);
loader.abort();
}
loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = void 0,
loaderConfig = void 0,
loaderCallbacks = void 0;
loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
var start = frag.byteRangeStartOffset,
end = frag.byteRangeEndOffset;
if (!isNaN(start) && !isNaN(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout
};
loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this),
onProgress: this.loadprogress.bind(this)
};
loader.load(loaderContext, loaderConfig, loaderCallbacks);
};
FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var payload = response.data,
frag = context.frag;
// detach fragment loader on load success
frag.loader = undefined;
this.loaders[frag.type] = undefined;
this.hls.trigger(events["a" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
};
FragmentLoader.prototype.loaderror = function loaderror(response, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var loader = context.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails })...
};
FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var loader = context.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
};
// data will be used for progressive parsing
FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) {
var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
// jshint ignore:line
var frag = context.frag;
frag.loaded = stats.loaded;
this.hls.trigger(events["a" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
};
return FragmentLoader;
}(event_handler);
/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
// CONCATENATED MODULE: ./src/loader/key-loader.js
function key_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function key_loader__possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; ...
function key_loader__inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.cr...
/*
* Decrypt key Loader
*/
share/public_html/static/hls.js view on Meta::CPAN
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
event_handler.prototype.destroy.call(this);
};
KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) {
var frag = data.frag,
type = frag.type,
loader = this.loaders[type],
decryptdata = frag.decryptdata,
uri = decryptdata.uri;
// if uri is different from previous one or if decrypt key not retrieved yet
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
logger["b" /* logger */].warn('abort previous key loader for type:' + type);
loader.abort();
}
frag.loader = this.loaders[type] = new config.loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = void 0,
loaderConfig = void 0,
loaderCallbacks = void 0;
loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// we already loaded this key, return it
decryptdata.key = this.decryptkey;
this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
}
};
KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
// detach fragment loader on load success
frag.loader = undefined;
this.loaders[frag.type] = undefined;
this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
};
KeyLoader.prototype.loaderror = function loaderror(response, context) {
var frag = context.frag,
loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
};
KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag,
loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
};
return KeyLoader;
}(event_handler);
/* harmony default export */ var key_loader = (key_loader_KeyLoader);
// CONCATENATED MODULE: ./src/controller/fragment-tracker.js
function fragment_tracker__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function fragment_tracker__possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : ...
function fragment_tracker__inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Obj...
var FragmentState = {
NOT_LOADED: 'NOT_LOADED',
APPENDING: 'APPENDING',
PARTIAL: 'PARTIAL',
OK: 'OK'
};
var fragment_tracker_FragmentTracker = function (_EventHandler) {
fragment_tracker__inherits(FragmentTracker, _EventHandler);
function FragmentTracker(hls) {
fragment_tracker__classCallCheck(this, FragmentTracker);
var _this = fragment_tracker__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].FRAG_LOADED));
_this.bufferPadding = 0.2;
_this.fragments = Object.create(null);
_this.timeRanges = Object.create(null);
_this.config = hls.config;
return _this;
}
FragmentTracker.prototype.destroy = function destroy() {
this.fragments = null;
this.timeRanges = null;
this.config = null;
event_handler.prototype.destroy.call(this);
_EventHandler.prototype.destroy.call(this);
};
/**
* Return a Fragment that match the position and levelType.
* If not found any Fragment, return null
* @param {number} position
* @param {LevelType} levelType
* @returns {Fragment|null}
*/
FragmentTracker.prototype.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var bufferedFrags = Object.keys(fragments).filter(function (key) {
var fragmentEntity = fragments[key];
if (fragmentEntity.body.type !== levelType) {
return false;
}
if (!fragmentEntity.buffered) {
return false;
}
var frag = fragmentEntity.body;
return frag.startPTS <= position && position <= frag.endPTS;
});
if (bufferedFrags.length === 0) {
return null;
} else {
// https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
var bufferedFragKey = bufferedFrags.pop();
return fragments[bufferedFragKey].body;
}
};
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
* @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
* @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
*/
FragmentTracker.prototype.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {
var _this2 = this;
var fragmentTimes = void 0,
time = void 0;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this2.fragments[key];
if (fragmentEntity.buffered === true) {
var esData = fragmentEntity.range[elementaryStream];
if (esData) {
fragmentTimes = esData.time;
for (var i = 0; i < fragmentTimes.length; i++) {
time = fragmentTimes[i];
if (_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
// Unregister partial fragment as it needs to load again to be reused
_this2.removeFragment(fragmentEntity.body);
break;
}
}
}
}
});
};
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
* @param {Object} fragment Check the fragment against all sourceBuffers loaded
*/
FragmentTracker.prototype.detectPartialFragments = function detectPartialFragments(fragment) {
var _this3 = this;
var fragKey = this.getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
fragmentEntity.buffered = true;
Object.keys(this.timeRanges).forEach(function (elementaryStream) {
if (fragment.hasElementaryStream(elementaryStream) === true) {
var timeRange = _this3.timeRanges[elementaryStream];
// Check for malformed fragments
// Gaps need to be calculated for each elementaryStream
fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
}
});
}
};
FragmentTracker.prototype.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {
var fragmentTimes = [];
var startTime = void 0,
endTime = void 0;
var fragmentPartial = false;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
fragmentTimes.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
// Check for intersection with buffer
// Get playable sections of the fragment
fragmentTimes.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
fragmentPartial = true;
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return {
time: fragmentTimes,
partial: fragmentPartial
};
};
FragmentTracker.prototype.getFragmentKey = function getFragmentKey(fragment) {
return fragment.type + '_' + fragment.level + '_' + fragment.urlId + '_' + fragment.sn;
};
/**
* Gets the partial fragment for a certain time
* @param {Number} time
* @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
*/
FragmentTracker.prototype.getPartialFragment = function getPartialFragment(time) {
var _this4 = this;
var timePadding = void 0,
startTime = void 0,
endTime = void 0;
var bestFragment = null;
var bestOverlap = 0;
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this4.fragments[key];
if (_this4.isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
};
/**
* @param {Object} fragment The fragment to check
* @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
*/
FragmentTracker.prototype.getState = function getState(fragment) {
var fragKey = this.getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
var state = FragmentState.NOT_LOADED;
if (fragmentEntity !== undefined) {
if (!fragmentEntity.buffered) {
state = FragmentState.APPENDING;
} else if (this.isPartial(fragmentEntity) === true) {
state = FragmentState.PARTIAL;
} else {
state = FragmentState.OK;
}
}
return state;
};
FragmentTracker.prototype.isPartial = function isPartial(fragmentEntity) {
return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
};
FragmentTracker.prototype.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime = void 0,
endTime = void 0;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
share/public_html/static/hls.js view on Meta::CPAN
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
};
/**
* Fires when a fragment loading is completed
*/
FragmentTracker.prototype.onFragLoaded = function onFragLoaded(e) {
var fragment = e.frag;
// don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
if (!isNaN(fragment.sn) && !fragment.bitrateTest) {
var fragKey = this.getFragmentKey(fragment);
var fragmentEntity = {
body: fragment,
range: Object.create(null),
buffered: false
};
this.fragments[fragKey] = fragmentEntity;
}
};
/**
* Fires when the buffer is updated
*/
FragmentTracker.prototype.onBufferAppended = function onBufferAppended(e) {
var _this5 = this;
// Store the latest timeRanges loaded in the buffer
this.timeRanges = e.timeRanges;
Object.keys(this.timeRanges).forEach(function (elementaryStream) {
var timeRange = _this5.timeRanges[elementaryStream];
_this5.detectEvictedFragments(elementaryStream, timeRange);
});
};
/**
* Fires after a fragment has been loaded into the source buffer
*/
FragmentTracker.prototype.onFragBuffered = function onFragBuffered(e) {
this.detectPartialFragments(e.frag);
};
/**
* Return true if fragment tracker has the fragment.
* @param {Object} fragment
* @returns {boolean}
*/
FragmentTracker.prototype.hasFragment = function hasFragment(fragment) {
var fragKey = this.getFragmentKey(fragment);
return this.fragments[fragKey] !== undefined;
};
/**
* Remove a fragment from fragment tracker until it is loaded again
* @param {Object} fragment The fragment to remove
*/
FragmentTracker.prototype.removeFragment = function removeFragment(fragment) {
var fragKey = this.getFragmentKey(fragment);
delete this.fragments[fragKey];
};
/**
* Remove all fragments from fragment tracker.
*/
FragmentTracker.prototype.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
};
return FragmentTracker;
}(event_handler);
// CONCATENATED MODULE: ./src/utils/binary-search.js
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
share/public_html/static/hls.js view on Meta::CPAN
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
var forwardMessage = function (ev, data) {
data = data || {};
data.frag = this.frag;
data.id = this.id;
hls.trigger(ev, data);
}.bind(this);
// forward events to main thread
observer.on(events["a" /* default */].FRAG_DECRYPTED, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_DATA, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSED, forwardMessage);
observer.on(events["a" /* default */].ERROR, forwardMessage);
share/public_html/static/hls.js view on Meta::CPAN
this.demuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
this.observer = null;
}
};
Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
var w = this.w;
var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
var contiguous = !trackSwitch && nextSN;
if (discontinuity) {
logger["b" /* logger */].log(this.id + ':discontinuity detected');
}
if (trackSwitch) {
logger["b" /* logger */].log(this.id + ':switch detected');
}
this.frag = frag;
if (w) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous...
} else {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
}
}
};
Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) {
share/public_html/static/hls.js view on Meta::CPAN
// special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
case events["a" /* default */].FRAG_PARSING_DATA:
data.data.data1 = new Uint8Array(data.data1);
if (data.data2) {
data.data.data2 = new Uint8Array(data.data2);
}
/* falls through */
default:
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
};
return Demuxer;
}();
/* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
share/public_html/static/hls.js view on Meta::CPAN
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx],
fragTo = fragments[toIdx],
fragToPTS = fragTo.startPTS;
// if we know startPTS[toIdx]
if (!isNaN(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
if (toIdx > fromIdx) {
fragFrom.duration = fragToPTS - fragFrom.start;
if (fragFrom.duration < 0) {
logger["b" /* logger */].warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
}
} else {
fragTo.duration = fragFrom.start - fragToPTS;
if (fragTo.duration < 0) {
logger["b" /* logger */].warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
}
}
} else {
// we dont know startPTS[toIdx]
if (toIdx > fromIdx) {
fragTo.start = fragFrom.start + fragFrom.duration;
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
// update frag PTS/DTS
var maxStartPTS = startPTS;
if (!isNaN(frag.startPTS)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(frag.startPTS - startPTS);
if (isNaN(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, frag.startPTS);
startPTS = Math.min(startPTS, frag.startPTS);
endPTS = Math.max(endPTS, frag.endPTS);
startDTS = Math.min(startDTS, frag.startDTS);
endDTS = Math.max(endDTS, frag.endDTS);
}
var drift = startPTS - frag.start;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.endPTS = endPTS;
frag.startDTS = startDTS;
frag.endDTS = endDTS;
frag.duration = endPTS - startPTS;
var sn = frag.sn;
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var fragIdx = void 0,
fragments = void 0,
i = void 0;
fragIdx = sn - details.startSN;
fragments = details.fragments;
// update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag;
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updatePTS(fragments, i, i - 1);
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updatePTS(fragments, i, i + 1);
}
details.PTSKnown = true;
// logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
return drift;
}
function mergeDetails(oldDetails, newDetails) {
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
delta = newDetails.startSN - oldDetails.startSN,
oldfragments = oldDetails.fragments,
newfragments = newDetails.fragments,
ccOffset = 0,
PTSFrag = void 0;
// potentially retrieve cached initsegment
if (newDetails.initSegment && oldDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
}
// check if old/new playlists have fragments in common
if (end < start) {
newDetails.PTSKnown = false;
return;
}
// loop through overlapping SN and update startPTS , cc, and duration if any found
for (var i = start; i <= end; i++) {
var oldFrag = oldfragments[delta + i],
newFrag = newfragments[i];
if (newFrag && oldFrag) {
ccOffset = oldFrag.cc - newFrag.cc;
if (!isNaN(oldFrag.startPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.duration = oldFrag.duration;
newFrag.backtracked = oldFrag.backtracked;
newFrag.dropped = oldFrag.dropped;
PTSFrag = newFrag;
}
}
}
if (ccOffset) {
logger["b" /* logger */].log('discontinuity sliding from playlist, take drift into account');
for (i = 0; i < newfragments.length; i++) {
newfragments[i].cc += ccOffset;
}
}
// if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldfragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
if (delta >= 0 && delta < oldfragments.length) {
// adjust start by sliding offset
var sliding = oldfragments[delta].start;
for (i = 0; i < newfragments.length; i++) {
newfragments[i].start += sliding;
}
}
}
// if we are here, it means we have fragments overlapping between
// old and new level. reliable PTS info is thus relying on old level
newDetails.PTSKnown = oldDetails.PTSKnown;
}
// CONCATENATED MODULE: ./src/utils/time-ranges.js
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
share/public_html/static/hls.js view on Meta::CPAN
return log;
}
};
/* harmony default export */ var time_ranges = (TimeRanges);
// CONCATENATED MODULE: ./src/utils/discontinuities.js
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0; i < fragments.length; i += 1) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function findFragWithCC(fragments, CC) {
return binary_search.search(fragments, function (candidate) {
if (candidate.cc < CC) {
return 1;
} else if (candidate.cc > CC) {
return -1;
} else {
return 0;
}
});
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
var shouldAlign = false;
if (lastLevel && lastLevel.details && details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
shouldAlign = true;
}
}
return shouldAlign;
}
// Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
logger["b" /* logger */].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
logger["b" /* logger */].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustPts(sliding, details) {
details.fragments.forEach(function (frag) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
});
details.PTSKnown = true;
}
// If a change in CC is detected, the PTS can no longer be relied upon
// Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS
// as a reference
function alignDiscontinuities(lastFrag, lastLevel, details) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag) {
logger["b" /* logger */].log('Adjusting PTS using last level due to CC increase within current level');
adjustPts(referenceFrag.start, details);
}
}
// try to align using programDateTime attribute (if available)
if (details.PTSKnown === false && lastLevel && lastLevel.details && lastLevel.details.fragments && lastLevel.details.fragments.length) {
// if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastLevel.details.programDateTime;
var newPDT = details.programDateTime;
// date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start;
if (!isNaN(sliding)) {
logger["b" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
adjustPts(sliding, details);
}
}
}
// CONCATENATED MODULE: ./src/task-loop.js
function task_loop__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function task_loop__possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
share/public_html/static/hls.js view on Meta::CPAN
* @abstract
*/
TaskLoop.prototype.doTick = function doTick() {};
return TaskLoop;
}(event_handler);
/* harmony default export */ var task_loop = (TaskLoop);
// CONCATENATED MODULE: ./src/controller/fragment-finders.js
/**
* Calculates the PDT of the next load position.
* bufferEnd in this function is usually the position of the playhead.
* @param {number} [start = 0] - The PTS of the first fragment within the level
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {*} levelDetails - An object containing the parsed and computed properties of the currently playing level
* @returns {number} nextPdt - The computed PDT
*/
function calculateNextPDT() {
var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var bufferEnd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var levelDetails = arguments[2];
var pdt = 0;
if (levelDetails.programDateTime) {
var parsedDateInt = Date.parse(levelDetails.programDateTime);
if (!isNaN(parsedDateInt)) {
pdt = bufferEnd * 1000 + parsedDateInt - 1000 * start;
}
}
return pdt;
}
/**
* Finds the first fragment whose endPDT value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments) {
var PDTValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (!Array.isArray(fragments) || !fragments.length || PDTValue === null) {
return null;
}
// if less than start
var firstSegment = fragments[0];
if (PDTValue < firstSegment.pdt) {
return null;
}
var lastSegment = fragments[fragments.length - 1];
if (PDTValue >= lastSegment.endPdt) {
return null;
}
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (PDTValue < frag.endPdt) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} [end = 0] - The computed end time of the stream
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentBySN(fragPrevious, fragments) {
var bufferEnd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var maxFragLookUpTolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
var foundFrag = void 0;
var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;
if (bufferEnd < end) {
if (bufferEnd > end - maxFragLookUpTolerance) {
maxFragLookUpTolerance = 0;
}
// Prefer the next fragment if it's within tolerance
if (fragNext && !fragment_finders_fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
foundFrag = fragNext;
} else {
foundFrag = binary_search.search(fragments, fragment_finders_fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
}
}
return foundFrag;
}
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragment_finders_fragmentWithinToleranceTest() {
var bufferEnd = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var maxFragLookUpTolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var candidate = arguments[2];
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ã] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
share/public_html/static/hls.js view on Meta::CPAN
PARSING: 'PARSING',
PARSED: 'PARSED',
BUFFER_FLUSHING: 'BUFFER_FLUSHING',
ENDED: 'ENDED',
ERROR: 'ERROR'
};
var stream_controller_StreamController = function (_TaskLoop) {
stream_controller__inherits(StreamController, _TaskLoop);
function StreamController(hls, fragmentTracker) {
stream_controller__classCallCheck(this, StreamController);
var _this = stream_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MA...
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.audioCodecSwap = false;
_this._state = State.STOPPED;
_this.stallReported = false;
return _this;
}
StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
StreamController.prototype.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(100);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
}
// set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
}
// if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
logger["b" /* logger */].log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = State.IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this.forceStartLoad = true;
this.state = State.STOPPED;
}
};
StreamController.prototype.stopLoad = function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragmentTracker.removeFragment(frag);
this.fragCurrent = null;
}
this.fragPrevious = null;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.clearInterval();
this.state = State.STOPPED;
this.forceStartLoad = false;
};
StreamController.prototype.doTick = function doTick() {
switch (this.state) {
case State.BUFFER_FLUSHING:
// in buffer flushing state, reset fragLoadError counter
this.fragLoadError = 0;
break;
case State.IDLE:
this._doTickIdle();
break;
case State.WAITING_LEVEL:
var level = this.levels[this.level];
// check if playlist is already loaded
if (level && level.details) {
this.state = State.IDLE;
}
share/public_html/static/hls.js view on Meta::CPAN
case State.FRAG_LOADING:
case State.PARSING:
case State.PARSED:
case State.ENDED:
break;
default:
break;
}
// check buffer
this._checkBuffer();
// check/update current fragment
this._checkFragmentChanged();
};
// Ironically the "idle" state is the on we do the most logic in it seems ....
// NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
// played segment, or on pause/play/seek instead of naively checking every 100ms?
StreamController.prototype._doTickIdle = function _doTickIdle() {
var hls = this.hls,
config = hls.config,
media = this.media;
// if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch disable
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
}
// if we have not yet loaded any fragment, start loading from start position
var pos = void 0;
if (this.loadedmetadata) {
pos = media.currentTime;
} else {
pos = this.nextLoadPosition;
}
// determine next load level
var level = hls.nextLoadLevel,
levelInfo = this.levels[level];
share/public_html/static/hls.js view on Meta::CPAN
// compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
// determine next candidate fragment to be loaded, based on current position and end of buffer position
// ensure up to `config.maxMaxBufferLength` of buffer upfront
var bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
bufferLen = bufferInfo.len;
// Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
// if buffer length is less than maxBufLen try to load a new fragment ...
logger["b" /* logger */].trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details;
// if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
this.state = State.WAITING_LEVEL;
return;
}
// we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
// dont switch to ENDED if we need to backtrack last fragment
var fragPrevious = this.fragPrevious;
if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !bufferInfo.nextStart) {
// fragPrevious is last fragment. retrieve level duration using last frag start offset + duration
// real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling
var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration);
// if everything (almost) til the end is buffered, let's signal eos
// we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...)
// tolerate up to one frag duration to cope with these cases.
// also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657
if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration)) {
// Finalize the media stream
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(events["a" /* default */].BUFFER_EOS, data);
this.state = State.ENDED;
return;
}
}
// if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
};
StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
var fragPrevious = this.fragPrevious,
level = this.level,
fragments = levelDetails.fragments,
fragLen = fragments.length;
// empty playlist
if (fragLen === 0) {
return;
}
// find fragment index, contiguous with end of buffer position
var start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
bufferEnd = bufferInfo.end,
frag = void 0;
if (levelDetails.initSegment && !levelDetails.initSegment.data) {
frag = levelDetails.initSegment;
} else {
// in case of live playlist we need to ensure that requested position is not located before playlist start
if (levelDetails.live) {
var initialLiveManifestSize = this.config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
logger["b" /* logger */].warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
return;
}
frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
// if it explicitely returns null don't load any fragment and exit function now
if (frag === null) {
return;
}
} else {
// VoD playlist: if bufferEnd before start of playlist, load first fragment
if (bufferEnd < start) {
frag = fragments[0];
}
}
}
if (!frag) {
frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
}
if (frag) {
if (frag.encrypted) {
logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
this._loadKey(frag);
} else {
logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
this._loadFragment(frag);
}
}
};
StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
var config = this.hls.config,
media = this.media;
var frag = void 0;
// check if requested position is within seekable boundaries :
// logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
logger["b" /* logger */].log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
bufferEnd = liveSyncPosition;
if (media && media.readyState && media.duration > liveSyncPosition) {
media.currentTime = liveSyncPosition;
}
this.nextLoadPosition = liveSyncPosition;
}
// if end of buffer greater than live edge, don't load any fragment
// this could happen if live playlist intermittently slides in the past.
// level 1 loaded [182580161,182580167]
// level 1 loaded [182580162,182580169]
// Loading 182580168 of [182580162 ,182580169],level 1 ..
// Loading 182580169 of [182580162 ,182580169],level 1 ..
// level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
// level 1 loaded [182580164,182580171]
//
// don't return null in case media not loaded yet (readystate === 0)
if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
return null;
}
if (this.startFragRequested && !levelDetails.PTSKnown) {
/* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
try to load frag matching with next SN.
even if SN are not synchronized between playlists, loading this frag will help us
compute playlist sliding and find the right one after in case it was not the right consecutive one */
if (fragPrevious) {
if (!levelDetails.programDateTime) {
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN];
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
logger["b" /* logger */].log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
}
}
// next frag SN not available (or not with same continuity counter)
// look for a frag sharing the same CC
if (!frag) {
frag = binary_search.search(fragments, function (frag) {
return fragPrevious.cc - frag.cc;
});
if (frag) {
logger["b" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
}
}
} else {
// Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
frag = findFragmentByPDT(fragments, fragPrevious.endPdt + 1);
}
}
if (!frag) {
/* we have no idea about which fragment should be loaded.
so let's load mid fragment. it will help computing playlist sliding and find the right one
*/
frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
logger["b" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
}
}
return frag;
};
StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
var config = this.hls.config;
var fragBySN = function fragBySN() {
return findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);
};
var frag = void 0;
var foundFrag = void 0;
if (bufferEnd < end) {
if (!levelDetails.programDateTime) {
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
foundFrag = findFragmentBySN(fragPrevious, fragments, bufferEnd, end, config.maxFragLookUpTolerance);
} else {
// Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
foundFrag = findFragmentByPDT(fragments, calculateNextPDT(start, bufferEnd, levelDetails));
if (!foundFrag || fragment_finders_fragmentWithinToleranceTest(bufferEnd, config.maxFragLookUpTolerance, foundFrag)) {
// Fall back to SN order if finding by PDT returns a frag which won't fit within the stream
// fragmentWithToleranceTest returns 0 if the frag is within tolerance; 1 or -1 otherwise
logger["b" /* logger */].warn('Frag found by PDT search did not fit within tolerance; falling back to finding by SN');
foundFrag = fragBySN();
}
}
} else {
// reach end of playlist
foundFrag = fragments[fragLen - 1];
}
if (foundFrag) {
frag = foundFrag;
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var prevFrag = fragments[curSNIdx - 1];
var nextFrag = fragments[curSNIdx + 1];
// logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPrevious && frag.sn === fragPrevious.sn) {
if (sameLevel && !frag.backtracked) {
if (frag.sn < levelDetails.endSN) {
var deltaPTS = fragPrevious.deltaPTS;
// if there is a significant delta between audio and video, larger than max allowed hole,
// and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
// let's try to load previous fragment again to get last keyframe
// then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
frag = prevFrag;
logger["b" /* logger */].warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');
} else {
frag = nextFrag;
logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn);
}
} else {
frag = null;
}
} else if (frag.backtracked) {
// Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
if (nextFrag && nextFrag.backtracked) {
logger["b" /* logger */].warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
frag = nextFrag;
} else {
// If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
// Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
logger["b" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
frag.dropped = 0;
if (prevFrag) {
frag = prevFrag;
frag.backtracked = true;
} else if (curSNIdx) {
// can't backtrack on very first fragment
frag = null;
}
}
}
}
}
return frag;
};
StreamController.prototype._loadKey = function _loadKey(frag) {
this.state = State.KEY_LOADING;
this.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
};
StreamController.prototype._loadFragment = function _loadFragment(frag) {
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag;
this.startFragRequested = true;
// Don't update nextLoadPosition for fragments which are not buffered
if (!isNaN(frag.sn) && !frag.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
// Allow backtracked fragments to load
if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
frag.autoLevel = this.hls.autoLevelEnabled;
frag.bitrateTest = this.bitrateTest;
this.hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
// lazy demuxer init, as this could take some time ... do it during frag loading
if (!this.demuxer) {
this.demuxer = new demux_demuxer(this.hls, 'main');
}
this.state = State.FRAG_LOADING;
} else if (fragState === FragmentState.APPENDING) {
// Lower the buffer size and try again
if (this._reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
}
};
StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, playlist_loader.LevelType.MAIN);
};
StreamController.prototype.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.endPTS + 0.5);
}
return null;
};
StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() {
var fragPlayingCurrent = void 0,
currentTime = void 0,
video = this.media;
if (video && video.readyState && video.seeking === false) {
currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (currentTime > this.lastCurrentTime) {
this.lastCurrentTime = currentTime;
}
if (BufferHelper.isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getBufferedFrag(currentTime);
} else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = fragPlayingCurrent;
if (fragPlaying !== this.fragPlaying) {
this.hls.trigger(events["a" /* default */].FRAG_CHANGED, { frag: fragPlaying });
var fragPlayingLevel = fragPlaying.level;
if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
this.hls.trigger(events["a" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel });
}
this.fragPlaying = fragPlaying;
}
}
}
};
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
share/public_html/static/hls.js view on Meta::CPAN
previouslyPaused = void 0;
if (media) {
previouslyPaused = media.paused;
media.pause();
} else {
// don't restart playback after instant level switch in case media not attached
previouslyPaused = true;
}
this.previouslyPaused = previouslyPaused;
}
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
};
/**
* on immediate level switch end, after new fragment has been buffered:
* - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
* - resume the playback if needed
*/
StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
var media = this.media;
if (media && media.buffered.length) {
this.immediateSwitch = false;
if (BufferHelper.isBuffered(media, media.currentTime)) {
share/public_html/static/hls.js view on Meta::CPAN
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() {
var media = this.media;
// ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media && media.readyState) {
var fetchdelay = void 0,
fragPlayingCurrent = void 0,
nextBufferedFrag = void 0;
fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
}
if (!media.paused) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel,
nextLevel = this.levels[nextLevelId],
fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
}
// logger.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (nextBufferedFrag) {
// we can flush buffer range following this one without stalling playback
nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// start flush position is the start PTS of next buffered frag.
// we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
// in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
}
}
}
};
StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
this.state = State.BUFFER_FLUSHING;
var flushScope = { startOffset: startOffset, endOffset: endOffset };
// if alternate audio tracks are used, only flush video, otherwise flush everything
share/public_html/static/hls.js view on Meta::CPAN
}
};
StreamController.prototype.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media && media.ended) {
logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
}
// reset fragment backtracked flag
var levels = this.levels;
if (levels) {
levels.forEach(function (level) {
if (level.details) {
level.details.fragments.forEach(function (fragment) {
fragment.backtracked = undefined;
});
}
});
}
// remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('seeked', this.onvseeked);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
share/public_html/static/hls.js view on Meta::CPAN
var media = this.media,
currentTime = media ? media.currentTime : undefined,
config = this.config;
if (!isNaN(currentTime)) {
logger["b" /* logger */].log('media seeking to ' + currentTime.toFixed(3));
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var bufferInfo = BufferHelper.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole);
if (this.state === State.FRAG_LOADING) {
var fragCurrent = this.fragCurrent;
// check if we are seeking to a unbuffered area AND if frag loading is in progress
if (bufferInfo.len === 0 && fragCurrent) {
var tolerance = config.maxFragLookUpTolerance,
fragStartOffset = fragCurrent.start - tolerance,
fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
// check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
logger["b" /* logger */].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null;
// switch to IDLE state to load new fragment
this.state = State.IDLE;
} else {
logger["b" /* logger */].log('seeking outside of buffer but within currently loaded fragment range');
}
}
} else if (this.state === State.ENDED) {
// if seeking to unbuffered area, clean up fragPrevious
if (bufferInfo.len === 0) {
this.fragPrevious = 0;
}
// switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
}
if (media) {
this.lastCurrentTime = currentTime;
}
// in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata) {
this.nextLoadPosition = this.startPosition = currentTime;
}
share/public_html/static/hls.js view on Meta::CPAN
StreamController.prototype.onMediaEnded = function onMediaEnded() {
logger["b" /* logger */].log('media ended');
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
StreamController.prototype.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
logger["b" /* logger */].log('trigger BUFFER_RESET');
this.hls.trigger(events["a" /* default */].BUFFER_RESET);
this.fragmentTracker.removeAllFragments();
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
};
StreamController.prototype.onManifestParsed = function onManifestParsed(data) {
var aac = false,
heaac = false,
codec = void 0;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
share/public_html/static/hls.js view on Meta::CPAN
var newLevelId = data.level;
var lastLevel = this.levels[this.levelLastLoaded];
var curLevel = this.levels[newLevelId];
var duration = newDetails.totalduration;
var sliding = 0;
logger["b" /* logger */].log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
if (newDetails.live) {
var curDetails = curLevel.details;
if (curDetails && newDetails.fragments.length > 0) {
// we already have details for that level, merge them
mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
if (newDetails.PTSKnown && !isNaN(sliding)) {
logger["b" /* logger */].log('live playlist sliding:' + sliding.toFixed(3));
} else {
logger["b" /* logger */].log('live playlist - outdated PTS, unknown sliding');
alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
}
} else {
logger["b" /* logger */].log('live playlist - first load, unknown sliding');
newDetails.PTSKnown = false;
alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
}
} else {
newDetails.PTSKnown = false;
}
// override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(events["a" /* default */].LEVEL_UPDATED, { details: newDetails, level: newLevelId });
if (this.startFragRequested === false) {
// compute start position if set to -1. use it straight away if value is defined
if (this.startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = newDetails.startTimeOffset;
if (!isNaN(startTimeOffset)) {
if (startTimeOffset < 0) {
logger["b" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
startTimeOffset = sliding + duration + startTimeOffset;
}
logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
this.startPosition = startTimeOffset;
} else {
// if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
if (newDetails.live) {
this.startPosition = this.computeLivePosition(sliding, newDetails);
logger["b" /* logger */].log('configure startPosition to ' + this.startPosition);
} else {
this.startPosition = 0;
}
}
this.lastCurrentTime = this.startPosition;
}
this.nextLoadPosition = this.startPosition;
}
// only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
}
// trigger handler right now
this.tick();
};
StreamController.prototype.onKeyLoaded = function onKeyLoaded() {
if (this.state === State.KEY_LOADING) {
this.state = State.IDLE;
this.tick();
}
};
StreamController.prototype.onFragLoaded = function onFragLoaded(data) {
var fragCurrent = this.fragCurrent,
fragLoaded = data.frag;
if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
var stats = data.stats;
var currentLevel = this.levels[fragCurrent.level];
var details = currentLevel.details;
logger["b" /* logger */].log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
// reset frag bitrate test in any case after frag loaded event
this.bitrateTest = false;
this.stats = stats;
// if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
// then this means that we should be able to load a fragment at a higher quality level
if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {
// switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
this.state = State.IDLE;
this.startFragRequested = false;
stats.tparsed = stats.tbuffered = window.performance.now();
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
this.tick();
} else if (fragLoaded.sn === 'initSegment') {
this.state = State.IDLE;
stats.tparsed = stats.tbuffered = window.performance.now();
details.initSegment.data = data.payload;
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
this.tick();
} else {
this.state = State.PARSING;
// transmux the MPEG-TS data to ISO-BMFF segments
var duration = details.totalduration,
level = fragCurrent.level,
sn = fragCurrent.sn,
audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap) {
logger["b" /* logger */].log('swapping playlist audio codec');
if (audioCodec === undefined) {
audioCodec = this.lastAudioCodec;
}
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
}
this.pendingBuffering = true;
this.appended = false;
logger["b" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);
var demuxer = this.demuxer;
if (!demuxer) {
demuxer = this.demuxer = new demux_demuxer(this.hls, 'main');
}
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
var media = this.media;
var mediaSeeking = media && media.seeking;
var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);
var initSegmentData = details.initSegment ? details.initSegment.data : [];
demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined);
}
}
this.fragLoadError = 0;
};
StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
var tracks = data.tracks,
trackName = void 0,
track = void 0;
// if audio track is expected to come from audio stream controller, discard any coming from main
if (tracks.audio && this.altAudio) {
delete tracks.audio;
}
// include levelCodec in audio and video tracks
share/public_html/static/hls.js view on Meta::CPAN
}
}
// trigger handler right now
this.tick();
}
};
StreamController.prototype.onFragParsingData = function onFragParsingData(data) {
var _this2 = this;
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
this.state === State.PARSING) {
var level = this.levels[this.level],
frag = fragCurrent;
if (isNaN(data.endPTS)) {
data.endPTS = data.startPTS + fragCurrent.duration;
data.endDTS = data.startDTS + fragCurrent.duration;
}
if (data.hasAudio === true) {
frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.AUDIO);
}
if (data.hasVideo === true) {
frag.addElementaryStream(loader_fragment.ElementaryStreamTypes.VIDEO);
}
logger["b" /* logger */].log('Parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0...
// Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
if (data.type === 'video') {
frag.dropped = data.dropped;
if (frag.dropped) {
if (!frag.backtracked) {
var levelDetails = level.details;
if (levelDetails && frag.sn === levelDetails.startSN) {
logger["b" /* logger */].warn('missing video frame(s) on first frag, appending with gap', frag.sn);
} else {
logger["b" /* logger */].warn('missing video frame(s), backtracking fragment', frag.sn);
// Return back to the IDLE state without appending to buffer
// Causes findFragments to backtrack a segment and find the keyframe
// Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
this.fragmentTracker.removeFragment(frag);
frag.backtracked = true;
this.nextLoadPosition = data.startPTS;
this.state = State.IDLE;
this.fragPrevious = frag;
this.tick();
return;
}
} else {
logger["b" /* logger */].warn('Already backtracked on this fragment, appending with the gap', frag.sn);
}
} else {
// Only reset the backtracked flag if we've loaded the frag without any dropped frames
frag.backtracked = false;
}
}
var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
hls = this.hls;
hls.trigger(events["a" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
// has remuxer dropped video frames located before first keyframe ?
[data.data1, data.data2].forEach(function (buffer) {
// only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
// in that case it is useless to append following segments
if (buffer && buffer.length && _this2.state === State.PARSING) {
_this2.appended = true;
// arm pending Buffering flag before appending a segment
_this2.pendingBuffering = true;
hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
}
});
// trigger handler right now
this.tick();
}
};
StreamController.prototype.onFragParsed = function onFragParsed(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
this.stats.tparsed = window.performance.now();
this.state = State.PARSED;
this._checkAppendedParsed();
}
};
StreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url,
trackId = data.id;
// if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
logger["b" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent;
// we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent.loader) {
logger["b" /* logger */].log('switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null;
// destroy demuxer to force init segment generation (following audio switch)
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
// switch to IDLE state to load new fragment
this.state = State.IDLE;
}
var hls = this.hls;
// switching to main audio, flush all audio and trigger track switched
hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });
this.altAudio = false;
}
};
StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
var trackId = data.id,
altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer;
// if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
logger["b" /* logger */].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
StreamController.prototype.onBufferCreated = function onBufferCreated(data) {
var tracks = data.tracks,
mediaTrack = void 0,
share/public_html/static/hls.js view on Meta::CPAN
mediaTrack = track;
// keep video source buffer reference
if (type === 'video') {
this.videoBuffer = tracks[type].buffer;
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
logger["b" /* logger */].log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
StreamController.prototype.onBufferAppended = function onBufferAppended(data) {
if (data.parent === 'main') {
var state = this.state;
if (state === State.PARSING || state === State.PARSED) {
// check if all buffers have been appended
this.pendingBuffering = data.pending > 0;
this._checkAppendedParsed();
}
}
};
StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {
// trigger handler right now
if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
var frag = this.fragCurrent;
if (frag) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
logger["b" /* logger */].log('main buffered : ' + time_ranges.toString(media.buffered));
this.fragPrevious = frag;
var stats = this.stats;
stats.tbuffered = window.performance.now();
// we should get rid of this.fragLastKbps
this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
this.state = State.IDLE;
}
this.tick();
}
};
StreamController.prototype.onError = function onError(data) {
var frag = data.frag || this.fragCurrent;
// don't handle frag error not related to main fragment
if (frag && frag.type !== 'main') {
return;
}
// 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
var mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
if (!data.fatal) {
// keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
// exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
this.retryDate = window.performance.now() + delay;
// retry loading state
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else {
logger["b" /* logger */].error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
// switch error to fatal
data.fatal = true;
this.state = State.ERROR;
}
}
break;
case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
share/public_html/static/hls.js view on Meta::CPAN
if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
// reduce max buf len if current position is buffered
if (mediaBuffered) {
this._reduceMaxBufferLength(this.config.maxBufferLength);
this.state = State.IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush everything');
this.fragCurrent = null;
// flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
}
break;
default:
break;
}
};
share/public_html/static/hls.js view on Meta::CPAN
this._reportStall(bufferInfo.len);
}
this._tryFixBufferStall(bufferInfo, stalledDuration);
}
}
};
StreamController.prototype.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = State.IDLE;
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tick();
};
StreamController.prototype.onBufferFlushed = function onBufferFlushed() {
/* after successful buffer flushing, filter flushed fragments from bufferedFrags
use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
*/
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
if (media) {
// filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
this.fragmentTracker.detectEvictedFragments(loader_fragment.ElementaryStreamTypes.VIDEO, media.buffered);
}
// move to IDLE once flush complete. this should trigger new fragment loading
this.state = State.IDLE;
// reset reference to frag
this.fragPrevious = null;
};
StreamController.prototype.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
};
StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
};
share/public_html/static/hls.js view on Meta::CPAN
*/
StreamController.prototype._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDuration) {
var config = this.config,
media = this.media;
var currentTime = media.currentTime;
var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end
var partial = this.fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
this._trySkipBufferHole(partial);
}
if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
// Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
share/public_html/static/hls.js view on Meta::CPAN
hls.trigger(events["a" /* default */].ERROR, {
type: errors["b" /* ErrorTypes */].MEDIA_ERROR,
details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
};
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
StreamController.prototype._trySkipBufferHole = function _trySkipBufferHole(partial) {
var hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0;
// Check if currentTime is between unbuffered regions of partial fragments
for (var i = 0; i < media.buffered.length; i++) {
var startTime = media.buffered.start(i);
if (currentTime >= lastEndTime && currentTime < startTime) {
media.currentTime = Math.max(startTime, media.currentTime + 0.1);
logger["b" /* logger */].warn('skipping hole, adjusting currentTime from ' + currentTime + ' to ' + media.currentTime);
this.stalled = null;
hls.trigger(events["a" /* default */].ERROR, {
type: errors["b" /* ErrorTypes */].MEDIA_ERROR,
details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: 'fragment loaded with buffer holes, seeking from ' + currentTime + ' to ' + media.currentTime,
frag: partial
});
return;
}
lastEndTime = media.buffered.end(i);
}
};
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
share/public_html/static/hls.js view on Meta::CPAN
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
StreamController.prototype._seekToStartPos = function _seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
// only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
var startPosition = media.seeking ? currentTime : this.startPosition;
// if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
if (currentTime !== startPosition) {
// if startPosition not buffered, let's seek to buffered.start(0)
logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition + ' from current time ' + currentTime + ' ');
media.currentTime = startPosition;
}
};
stream_controller__createClass(StreamController, [{
share/public_html/static/hls.js view on Meta::CPAN
}
},
get: function get() {
return this._state;
}
}, {
key: 'currentLevel',
get: function get() {
var media = this.media;
if (media) {
var frag = this.getBufferedFrag(media.currentTime);
if (frag) {
return frag.level;
}
}
return -1;
}
}, {
key: 'nextBufferedFrag',
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
} else {
return null;
}
}
}, {
key: 'nextLevel',
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: 'liveSyncPosition',
get: function get() {
return this._liveSyncPosition;
},
set: function set(value) {
share/public_html/static/hls.js view on Meta::CPAN
var levelSet = {};
var levelFromSet = null;
var videoCodecFound = false;
var audioCodecFound = false;
var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
var audioTracks = [];
// regroup redundant levels together
data.levels.forEach(function (level) {
level.loadError = 0;
level.fragmentError = false;
videoCodecFound = videoCodecFound || !!level.videoCodec;
audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO);
// erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
level.audioCodec = undefined;
}
share/public_html/static/hls.js view on Meta::CPAN
LevelController.prototype.onError = function onError(data) {
if (data.fatal) {
if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) {
this.clearTimer();
}
return;
}
var levelError = false,
fragmentError = false;
var levelIndex = void 0;
// try to recover not fatal errors
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
levelIndex = data.frag.level;
fragmentError = true;
break;
case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:
levelIndex = data.context.level;
levelError = true;
break;
case errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, fragmentError);
}
};
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*
* @param {Object} errorEvent
* @param {Number} levelIndex current level index
* @param {Boolean} levelError
* @param {Boolean} fragmentError
*/
// FIXME Find a better abstraction where fragment/level retry management is well decoupled
LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
var _this2 = this;
var config = this.hls.config;
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
var redundantLevels = void 0,
delay = void 0,
nextLevel = void 0;
level.loadError++;
level.fragmentError = fragmentError;
if (levelError) {
if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
// exponential backoff capped to max retry timeout
delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
// Schedule level reload
this.timer = setTimeout(function () {
return _this2.loadLevel();
}, delay);
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
share/public_html/static/hls.js view on Meta::CPAN
logger["b" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error');
this.currentLevelIndex = null;
// stopping live reloading timer if any
this.clearTimer();
// switch error to fatal
errorEvent.fatal = true;
return;
}
}
// Try any redundant streams if available for both errors: level and fragment
// If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
if (levelError || fragmentError) {
redundantLevels = level.url.length;
if (redundantLevels > 1 && level.loadError < redundantLevels) {
level.urlId = (level.urlId + 1) % redundantLevels;
level.details = undefined;
logger["b" /* logger */].warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant URL-id ' + level.urlId);
// console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', level.attrs.AUDIO);
} else {
// Search for available level
if (this.manualLevelIndex === -1) {
// When lowest level has been reached, let's start hunt from the top
nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
logger["b" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);
this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
} else if (fragmentError) {
// Allow fragment retry as long as configuration allows.
// reset this._level so that another call to set level() will trigger again a frag load
logger["b" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment');
this.currentLevelIndex = null;
}
}
}
};
// reset errors on the successful load of a fragment
LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === 'main') {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = false;
level.loadError = 0;
this.levelRetryCount = 0;
}
}
};
LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) {
var _this3 = this;
var levelId = data.level;
// only process level loaded events matching with expected level
if (levelId !== this.currentLevelIndex) {
return;
}
var curLevel = this._levels[levelId];
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (!curLevel.fragmentError) {
curLevel.loadError = 0;
this.levelRetryCount = 0;
}
var newDetails = data.details;
// if current playlist is a live playlist, arm a timer to reload it
if (newDetails.live) {
var targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);
var reloadInterval = targetdurationMs,
curDetails = curLevel.details;
if (curDetails && newDetails.endSN === curDetails.endSN) {
share/public_html/static/hls.js view on Meta::CPAN
// same as what we do for captions
sendAddTrackEvent(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) {
var fragment = data.frag;
var samples = data.samples;
// create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
this.id3Track.mode = 'hidden';
}
// Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = id3["a" /* default */].getID3Frames(samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
// Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
if (startTime === endTime) {
endTime += 0.0001;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j];
// Safari doesn't put the timestamp frame in the TextTrack
if (!id3["a" /* default */].isTimeStampFrame(frame)) {
share/public_html/static/hls.js view on Meta::CPAN
var abr_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ...
function abr_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function abr_controller__possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : se...
function abr_controller__inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Objec...
/*
* simple ABR Controller
* - compute next level based on last fragment bw heuristics
* - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
*/
var abr_controller__window = window,
share/public_html/static/hls.js view on Meta::CPAN
_this.onCheck = _this._abandonRulesCheck.bind(_this);
return _this;
}
AbrController.prototype.destroy = function destroy() {
this.clearTimer();
event_handler.prototype.destroy.call(this);
};
AbrController.prototype.onFragLoading = function onFragLoading(data) {
var frag = data.frag;
if (frag.type === 'main') {
if (!this.timer) {
this.fragCurrent = frag;
this.timer = setInterval(this.onCheck, 100);
}
// lazy init of BwEstimator, rationale is that we use different params for Live/VoD
// so we need to wait for stream manifest / playlist type to instantiate it.
if (!this._bwEstimator) {
var hls = this.hls;
var config = hls.config;
var level = frag.level;
var isLive = hls.levels[level].details.live;
var ewmaFast = void 0,
ewmaSlow = void 0;
if (isLive) {
ewmaFast = config.abrEwmaFastLive;
ewmaSlow = config.abrEwmaSlowLive;
} else {
ewmaFast = config.abrEwmaFastVoD;
ewmaSlow = config.abrEwmaSlowVoD;
}
this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
}
}
};
AbrController.prototype._abandonRulesCheck = function _abandonRulesCheck() {
/*
monitor fragment retrieval time...
we compute expected time of arrival of the complete fragment.
we compare it to expected time of buffer starvation
*/
var hls = this.hls;
var video = hls.media;
var frag = this.fragCurrent;
if (!frag) {
return;
}
var loader = frag.loader;
var minAutoLevel = hls.minAutoLevel;
// if loader has been destroyed or loading has been aborted, stop timer and return
if (!loader || loader.stats && loader.stats.aborted) {
logger["b" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer();
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
}
var stats = loader.stats;
/* only monitor frag retrieval time if
(video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
var requestDelay = abr_controller_performance.now() - stats.trequest,
playbackRate = Math.abs(video.playbackRate);
// monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
if (requestDelay > 500 * frag.duration / playbackRate) {
var levels = hls.levels,
loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
// byte/s; at least 1 byte/s to avoid division by zero
// compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
level = levels[frag.level],
levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
pos = video.currentTime,
fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
// consider emergency switch down only if we have less than 2 frag buffered AND
// time to finish loading current fragment is bigger than buffer starvation delay
// ie if we risk buffer starvation if bw does not increase quickly
if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
var fragLevelNextLoadedDelay = void 0,
nextLoadLevel = void 0;
// lets iterate through lower level and try to find the biggest one that could avoid rebuffering
// we start from current level - 1 and we step down , until we find a matching level
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
// we found a lower level that be rebuffering free with current estimated bw !
break;
}
}
// only emergency switch down if it takes less time to load new fragment at lowest level instead
// of finishing loading current one ...
if (fragLevelNextLoadedDelay < fragLoadedDelay) {
logger["b" /* logger */].warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']<fragLoadedDelay[' + (frag.level - 1) + '];bufferStarvationDelay:' + fragLevelNextLoad...
// force next load level in auto mode
hls.nextLoadLevel = nextLoadLevel;
// update bw estimate for this fragment before cancelling load (this will help reducing the bw)
this._bwEstimator.sample(requestDelay, stats.loaded);
// abort fragment loading
loader.abort();
// stop abandon rules timer
this.clearTimer();
hls.trigger(events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
}
}
}
}
};
AbrController.prototype.onFragLoaded = function onFragLoaded(data) {
var frag = data.frag;
if (frag.type === 'main' && !isNaN(frag.sn)) {
// stop monitoring bw once frag loaded
this.clearTimer();
// store level id after successful fragment load
this.lastLoadedFragLevel = frag.level;
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
// compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
level.loaded = { bytes: loadedBytes, duration: loadedDuration };
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
// if fragment has been loaded to perform a bitrate test,
if (data.frag.bitrateTest) {
var stats = data.stats;
stats.tparsed = stats.tbuffered = stats.tload;
this.onFragBuffered(data);
}
}
};
AbrController.prototype.onFragBuffered = function onFragBuffered(data) {
var stats = data.stats;
var frag = data.frag;
// only update stats on first frag buffering
// if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
// and leading to wrong bw estimation
// on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
if (stats.aborted !== true && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
// use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
// in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
// as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
logger["b" /* logger */].log('latency/loading/parsing/append/kbps:' + Math.round(stats.tfirst - stats.trequest) + '/' + Math.round(stats.tload - stats.tfirst) + '/' + Math.round(stats.tparsed - stats.tload) + '/' + Math.round(stats.tbuffered - ...
this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
stats.bwEstimate = this._bwEstimator.getEstimate();
// if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
if (frag.bitrateTest) {
this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
}
};
AbrController.prototype.onError = function onError(data) {
// stop timer in case of frag loading error
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
share/public_html/static/hls.js view on Meta::CPAN
this.timer = null;
};
// return next auto level
AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i],
levelDetails = levelInfo.details,
avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
live = levelDetails ? levelDetails.live : false,
adjustedbw = void 0;
// follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
fetchDuration = bitrate * avgDuration / adjustedbw;
logger["b" /* logger */].trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
// if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && (
// fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
}
// not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
share/public_html/static/hls.js view on Meta::CPAN
}, {
key: '_nextABRAutoLevel',
get: function get() {
var hls = this.hls,
maxAutoLevel = hls.maxAutoLevel,
levels = hls.levels,
config = hls.config,
minAutoLevel = hls.minAutoLevel;
var video = hls.media,
currentLevel = this.lastLoadedFragLevel,
currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
pos = video ? video.currentTime : 0,
// playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0,
avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
// bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;
share/public_html/static/hls.js view on Meta::CPAN
if (bestLevel >= 0) {
return bestLevel;
} else {
logger["b" /* logger */].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
// not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
bwFactor = config.abrBandWidthFactor,
bwUpFactor = config.abrBandWidthUpFactor;
if (bufferStarvationDelay === 0) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
logger["b" /* logger */].trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
// don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
return Math.max(bestLevel, 0);
}
}
}]);
share/public_html/static/hls.js view on Meta::CPAN
this.checkEos();
}
this.appending = false;
var parent = this.parent;
// count nb of pending segments waiting for appending on this sourcebuffer
var pending = this.segments.reduce(function (counter, segment) {
return segment.parent === parent ? counter + 1 : counter;
}, 0);
// this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
var timeRanges = {};
var sourceBuffer = this.sourceBuffer;
for (var streamType in sourceBuffer) {
timeRanges[streamType] = sourceBuffer[streamType].buffered;
}
this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });
// don't append in flushing mode
if (!this._needsFlush) {
this.doAppending();
share/public_html/static/hls.js view on Meta::CPAN
var sbobj = sb[type];
if (!sbobj.ended) {
return;
}
if (sbobj.updating) {
this._needsEos = true;
return;
}
}
logger["b" /* logger */].log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
// Notify the media element that it now has all of the media data
try {
mediaSource.endOfStream();
} catch (e) {
logger["b" /* logger */].warn('exception while calling mediaSource.endOfStream()');
}
this._needsEos = false;
};
BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) {
this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
// attempt flush immediately
this.flushBufferCounter = 0;
this.doFlush();
};
BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) {
var details = _ref.details;
if (details.fragments.length > 0) {
this._levelDuration = details.totalduration + details.fragments[0].start;
this._live = details.live;
this.updateMediaElementDuration();
}
};
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
share/public_html/static/hls.js view on Meta::CPAN
PARSED: 'PARSED',
BUFFER_FLUSHING: 'BUFFER_FLUSHING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS'
};
var audio_stream_controller_AudioStreamController = function (_TaskLoop) {
audio_stream_controller__inherits(AudioStreamController, _TaskLoop);
function AudioStreamController(hls, fragmentTracker) {
audio_stream_controller__classCallCheck(this, AudioStreamController);
var _this = audio_stream_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].AUDIO_TRACKS_UPDATED, events["a" /* defa...
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.audioCodecSwap = false;
_this._state = audio_stream_controller_State.STOPPED;
_this.initPTS = [];
_this.waitingFragment = null;
_this.videoTrackCC = null;
return _this;
}
AudioStreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
AudioStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = audio_stream_controller_State.STOPPED;
this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
// Signal that video PTS was found
AudioStreamController.prototype.onInitPtsFound = function onInitPtsFound(data) {
var demuxerId = data.id,
cc = data.frag.cc,
initPTS = data.initPTS;
if (demuxerId === 'main') {
// Always update the new INIT PTS
// Can change due level switch
this.initPTS[cc] = initPTS;
this.videoTrackCC = cc;
logger["b" /* logger */].log('InitPTS for cc: ' + cc + ' found from video track: ' + initPTS);
// If we are waiting we need to demux/remux the waiting frag
// With the new initPTS
if (this.state === audio_stream_controller_State.WAITING_INIT_PTS) {
this.tick();
}
}
};
AudioStreamController.prototype.startLoad = function startLoad(startPosition) {
if (this.tracks) {
var lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
this.setInterval(100);
this.fragLoadError = 0;
if (lastCurrentTime > 0 && startPosition === -1) {
logger["b" /* logger */].log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
this.state = audio_stream_controller_State.IDLE;
} else {
this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
this.state = audio_stream_controller_State.STARTING;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
this.tick();
} else {
this.startPosition = startPosition;
this.state = audio_stream_controller_State.STOPPED;
}
};
AudioStreamController.prototype.stopLoad = function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragmentTracker.removeFragment(frag);
this.fragCurrent = null;
}
this.fragPrevious = null;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.state = audio_stream_controller_State.STOPPED;
};
AudioStreamController.prototype.doTick = function doTick() {
var pos = void 0,
track = void 0,
share/public_html/static/hls.js view on Meta::CPAN
this.loadedmetadata = false;
break;
case audio_stream_controller_State.IDLE:
var tracks = this.tracks;
// audio tracks not received => exit loop
if (!tracks) {
break;
}
// if video not attached AND
// start fragment already requested OR start frag prefetch disable
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
break;
}
// determine next candidate fragment to be loaded, based on current position and
// end of buffer position
// if we have not yet loaded any fragment, start loading from start position
if (this.loadedmetadata) {
pos = this.media.currentTime;
} else {
pos = this.nextLoadPosition;
if (pos === undefined) {
break;
}
}
var media = this.mediaBuffer ? this.mediaBuffer : this.media,
videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,
bufferInfo = BufferHelper.bufferInfo(media, pos, config.maxBufferHole),
mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole),
bufferLen = bufferInfo.len,
bufferEnd = bufferInfo.end,
fragPrevious = this.fragPrevious,
// ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
// whichever is smaller.
// once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength),
maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len),
audioSwitch = this.audioSwitch,
trackId = this.trackId;
// if buffer length is less than maxBufLen try to load a new fragment
if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
trackDetails = tracks[trackId].details;
// if track info not retrieved yet, switch state and wait for track retrieval
if (typeof trackDetails === 'undefined') {
this.state = audio_stream_controller_State.WAITING_TRACK;
break;
}
// check if we need to finalize media stream
// we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) {
// if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos
// we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching
// between different renditions. using half frag duration should help cope with these cases.
if (!this.media.seeking || this.media.duration - bufferEnd < fragPrevious.duration / 2) {
// Finalize the media stream
this.hls.trigger(events["a" /* default */].BUFFER_EOS, { type: 'audio' });
this.state = audio_stream_controller_State.ENDED;
break;
}
}
// find fragment index, contiguous with end of buffer position
var fragments = trackDetails.fragments,
fragLen = fragments.length,
start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
frag = void 0;
// When switching audio track, reload audio as close as possible to currentTime
if (audioSwitch) {
if (trackDetails.live && !trackDetails.PTSKnown) {
logger["b" /* logger */].log('switching audiotrack, live stream, unknown PTS,load first fragment');
bufferEnd = 0;
} else {
bufferEnd = pos;
// if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
if (trackDetails.PTSKnown && pos < start) {
// if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
if (bufferInfo.end > start || bufferInfo.nextStart) {
logger["b" /* logger */].log('alt audio track ahead of main track, seek to start of alt audio track');
this.media.currentTime = start + 0.05;
} else {
return;
}
}
}
}
if (trackDetails.initSegment && !trackDetails.initSegment.data) {
frag = trackDetails.initSegment;
} // eslint-disable-line brace-style
// if bufferEnd before start of playlist, load first fragment
else if (bufferEnd <= start) {
frag = fragments[0];
if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
// Ensure we find a fragment which matches the continuity of the video track
frag = findFragWithCC(fragments, this.videoTrackCC);
}
if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
// we just loaded this first fragment, and we are still lagging behind the start of the live playlist
// let's force seek to start
var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
logger["b" /* logger */].log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
this.media.currentTime = nextBuffered + 0.05;
return;
}
} else {
var foundFrag = void 0;
var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ã] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
};
if (bufferEnd < end) {
if (bufferEnd > end - maxFragLookUpTolerance) {
maxFragLookUpTolerance = 0;
}
// Prefer the next fragment if it's within tolerance
if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
foundFrag = fragNext;
} else {
foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest);
}
} else {
// reach end of playlist
foundFrag = fragments[fragLen - 1];
}
if (foundFrag) {
frag = foundFrag;
start = foundFrag.start;
// logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
if (frag.sn < trackDetails.endSN) {
frag = fragments[frag.sn + 1 - trackDetails.startSN];
logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn);
} else {
frag = null;
}
}
}
}
if (frag) {
// logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
if (frag.encrypted) {
logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
this.state = audio_stream_controller_State.KEY_LOADING;
hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
} else {
logger["b" /* logger */].log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
// only load if fragment is not loaded or if in audio switch
// we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {
this.fragCurrent = frag;
this.startFragRequested = true;
if (!isNaN(frag.sn)) {
this.nextLoadPosition = frag.start + frag.duration;
}
hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
this.state = audio_stream_controller_State.FRAG_LOADING;
}
}
}
}
break;
case audio_stream_controller_State.WAITING_TRACK:
track = this.tracks[this.trackId];
// check if playlist is already loaded
if (track && track.details) {
share/public_html/static/hls.js view on Meta::CPAN
logger["b" /* logger */].log('audioStreamController: retryDate reached, switch back to IDLE state');
this.state = audio_stream_controller_State.IDLE;
}
break;
case audio_stream_controller_State.WAITING_INIT_PTS:
var videoTrackCC = this.videoTrackCC;
if (this.initPTS[videoTrackCC] === undefined) {
break;
}
// Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
var waitingFrag = this.waitingFragment;
if (waitingFrag) {
var waitingFragCC = waitingFrag.frag.cc;
if (videoTrackCC !== waitingFragCC) {
track = this.tracks[this.trackId];
if (track.details && track.details.live) {
logger["b" /* logger */].warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')');
this.waitingFragment = null;
this.state = audio_stream_controller_State.IDLE;
}
} else {
this.state = audio_stream_controller_State.FRAG_LOADING;
this.onFragLoaded(this.waitingFragment);
this.waitingFragment = null;
}
} else {
this.state = audio_stream_controller_State.IDLE;
share/public_html/static/hls.js view on Meta::CPAN
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
}
this.media = this.mediaBuffer = this.videoBuffer = null;
this.loadedmetadata = false;
this.stopLoad();
};
AudioStreamController.prototype.onMediaSeeking = function onMediaSeeking() {
if (this.state === audio_stream_controller_State.ENDED) {
// switch to IDLE state to check for potential new fragment
this.state = audio_stream_controller_State.IDLE;
}
if (this.media) {
this.lastCurrentTime = this.media.currentTime;
}
// tick to speed up processing
this.tick();
};
share/public_html/static/hls.js view on Meta::CPAN
AudioStreamController.prototype.onAudioTracksUpdated = function onAudioTracksUpdated(data) {
logger["b" /* logger */].log('audio tracks updated');
this.tracks = data.audioTracks;
};
AudioStreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url;
this.trackId = data.id;
this.fragCurrent = null;
this.state = audio_stream_controller_State.PAUSED;
this.waitingFragment = null;
// destroy useless demuxer when switching audio to main
if (!altAudio) {
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
} else {
// switching to audio track, start timer if not already started
share/public_html/static/hls.js view on Meta::CPAN
var newDetails = data.details,
trackId = data.id,
track = this.tracks[trackId],
duration = newDetails.totalduration,
sliding = 0;
logger["b" /* logger */].log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
if (newDetails.live) {
var curDetails = track.details;
if (curDetails && newDetails.fragments.length > 0) {
// we already have details for that level, merge them
mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
// TODO
// this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
if (newDetails.PTSKnown) {
logger["b" /* logger */].log('live audio playlist sliding:' + sliding.toFixed(3));
} else {
logger["b" /* logger */].log('live audio playlist - outdated PTS, unknown sliding');
}
} else {
newDetails.PTSKnown = false;
logger["b" /* logger */].log('live audio playlist - first load, unknown sliding');
share/public_html/static/hls.js view on Meta::CPAN
var startTimeOffset = newDetails.startTimeOffset;
if (!isNaN(startTimeOffset)) {
logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
this.startPosition = startTimeOffset;
} else {
this.startPosition = 0;
}
}
this.nextLoadPosition = this.startPosition;
}
// only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
if (this.state === audio_stream_controller_State.WAITING_TRACK) {
this.state = audio_stream_controller_State.IDLE;
}
// trigger handler right now
this.tick();
};
AudioStreamController.prototype.onKeyLoaded = function onKeyLoaded() {
if (this.state === audio_stream_controller_State.KEY_LOADING) {
this.state = audio_stream_controller_State.IDLE;
this.tick();
}
};
AudioStreamController.prototype.onFragLoaded = function onFragLoaded(data) {
var fragCurrent = this.fragCurrent,
fragLoaded = data.frag;
if (this.state === audio_stream_controller_State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
var track = this.tracks[this.trackId],
details = track.details,
duration = details.totalduration,
trackId = fragCurrent.level,
sn = fragCurrent.sn,
cc = fragCurrent.cc,
audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
stats = this.stats = data.stats;
if (sn === 'initSegment') {
this.state = audio_stream_controller_State.IDLE;
stats.tparsed = stats.tbuffered = audio_stream_controller_performance.now();
details.initSegment.data = data.payload;
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
this.tick();
} else {
this.state = audio_stream_controller_State.PARSING;
// transmux the MPEG-TS data to ISO-BMFF segments
this.appended = false;
if (!this.demuxer) {
this.demuxer = new demux_demuxer(this.hls, 'audio');
}
// Check if we have video initPTS
// If not we need to wait for it
var initPTS = this.initPTS[cc];
var initSegmentData = details.initSegment ? details.initSegment.data : [];
if (details.initSegment || initPTS !== undefined) {
this.pendingBuffering = true;
logger["b" /* logger */].log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = false; // details.PTSKnown || !details.live;
this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
} else {
logger["b" /* logger */].log('unknown video PTS for continuity counter ' + cc + ', waiting for video PTS before demuxing audio frag ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
this.waitingFragment = data;
this.state = audio_stream_controller_State.WAITING_INIT_PTS;
}
}
}
this.fragLoadError = 0;
};
AudioStreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
var tracks = data.tracks,
track = void 0;
// delete any video track found on audio demuxer
if (tracks.video) {
delete tracks.video;
}
// include levelCodec in audio and video tracks
track = tracks.audio;
share/public_html/static/hls.js view on Meta::CPAN
}
// trigger handler right now
this.tick();
}
}
};
AudioStreamController.prototype.onFragParsingData = function onFragParsingData(data) {
var _this2 = this;
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
var trackId = this.trackId,
track = this.tracks[trackId],
hls = this.hls;
if (isNaN(data.endPTS)) {
data.endPTS = data.startPTS + fragCurrent.duration;
data.endDTS = data.startDTS + fragCurrent.duration;
}
fragCurrent.addElementaryStream(loader_fragment.ElementaryStreamTypes.AUDIO);
logger["b" /* logger */].log('parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb);
updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
var audioSwitch = this.audioSwitch,
media = this.media,
appendOnBufferFlush = false;
// Only flush audio from old audio tracks when PTS is known on new audio track
if (audioSwitch && media) {
if (media.readyState) {
var currentTime = media.currentTime;
logger["b" /* logger */].log('switching audio track : currentTime:' + currentTime);
if (currentTime >= data.startPTS) {
share/public_html/static/hls.js view on Meta::CPAN
this.pendingData = [];
this.appended = true;
}
}
// trigger handler right now
this.tick();
}
};
AudioStreamController.prototype.onFragParsed = function onFragParsed(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
this.stats.tparsed = audio_stream_controller_performance.now();
this.state = audio_stream_controller_State.PARSED;
this._checkAppendedParsed();
}
};
AudioStreamController.prototype.onBufferReset = function onBufferReset() {
// reset reference to sourcebuffers
this.mediaBuffer = this.videoBuffer = null;
this.loadedmetadata = false;
share/public_html/static/hls.js view on Meta::CPAN
// check if all buffers have been appended
this.pendingBuffering = data.pending > 0;
this._checkAppendedParsed();
}
}
};
AudioStreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {
// trigger handler right now
if (this.state === audio_stream_controller_State.PARSED && (!this.appended || !this.pendingBuffering)) {
var frag = this.fragCurrent,
stats = this.stats,
hls = this.hls;
if (frag) {
this.fragPrevious = frag;
stats.tbuffered = audio_stream_controller_performance.now();
hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
logger["b" /* logger */].log('audio buffered : ' + time_ranges.toString(media.buffered));
if (this.audioSwitch && this.appended) {
this.audioSwitch = false;
hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: this.trackId });
}
this.state = audio_stream_controller_State.IDLE;
}
this.tick();
}
};
AudioStreamController.prototype.onError = function onError(data) {
var frag = data.frag;
// don't handle frag error not related to audio fragment
if (frag && frag.type !== 'audio') {
return;
}
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
var _frag = data.frag;
// don't handle frag error not related to audio fragment
if (_frag && _frag.type !== 'audio') {
break;
}
if (!data.fatal) {
var loadError = this.fragLoadError;
if (loadError) {
loadError++;
} else {
loadError = 1;
}
var config = this.config;
if (loadError <= config.fragLoadingMaxRetry) {
this.fragLoadError = loadError;
// exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
logger["b" /* logger */].warn('AudioStreamController: frag loading failed, retry in ' + delay + ' ms');
this.retryDate = audio_stream_controller_performance.now() + delay;
// retry loading state
this.state = audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY;
} else {
logger["b" /* logger */].error('AudioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
// switch error to fatal
data.fatal = true;
this.state = audio_stream_controller_State.ERROR;
}
}
break;
case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR:
case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT:
case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== audio_stream_controller_State.ERROR) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? audio_stream_controller_State.ERROR : audio_stream_controller_State.IDLE;
logger["b" /* logger */].warn('AudioStreamController: ' + data.details + ' while loading frag, now switching to ' + this.state + ' state ...');
}
break;
case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'audio' && (this.state === audio_stream_controller_State.PARSING || this.state === audio_stream_controller_State.PARSED)) {
var media = this.mediaBuffer,
currentTime = this.media.currentTime,
mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5);
// reduce max buf len if current position is buffered
if (mediaBuffered) {
share/public_html/static/hls.js view on Meta::CPAN
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
_config.maxMaxBufferLength /= 2;
logger["b" /* logger */].warn('AudioStreamController: reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
}
this.state = audio_stream_controller_State.IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole audio buffer to recover
logger["b" /* logger */].warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
this.fragCurrent = null;
// flush everything
this.state = audio_stream_controller_State.BUFFER_FLUSHING;
this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
}
}
break;
default:
break;
}
};
share/public_html/static/hls.js view on Meta::CPAN
var pendingData = this.pendingData;
if (pendingData && pendingData.length) {
logger["b" /* logger */].log('AudioStreamController: appending pending audio data after buffer flushed');
pendingData.forEach(function (appendObj) {
_this3.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj);
});
this.appended = true;
this.pendingData = [];
this.state = audio_stream_controller_State.PARSED;
} else {
// move to IDLE once flush complete. this should trigger new fragment loading
this.state = audio_stream_controller_State.IDLE;
// reset reference to frag
this.fragPrevious = null;
this.tick();
}
};
audio_stream_controller__createClass(AudioStreamController, [{
key: 'state',
set: function set(nextState) {
if (this.state !== nextState) {
var previousState = this.state;
this._state = nextState;
share/public_html/static/hls.js view on Meta::CPAN
// Triggered when an initial PTS is found; used for synchronisation of WebVTT.
TimelineController.prototype.onInitPtsFound = function onInitPtsFound(data) {
var _this2 = this;
if (typeof this.initPTS === 'undefined') {
this.initPTS = data.initPTS;
}
// Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded.
// Parse any unparsed fragments upon receiving the initial PTS.
if (this.unparsedVttFrags.length) {
this.unparsedVttFrags.forEach(function (frag) {
_this2.onFragLoaded(frag);
});
this.unparsedVttFrags = [];
}
};
TimelineController.prototype.getExistingTrack = function getExistingTrack(trackName) {
var media = this.media;
if (media) {
for (var i = 0; i < media.textTracks.length; i++) {
share/public_html/static/hls.js view on Meta::CPAN
TimelineController.prototype.onMediaDetaching = function onMediaDetaching() {
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
clearCurrentCues(captionsTracks[trackName]);
delete captionsTracks[trackName];
});
};
TimelineController.prototype.onManifestLoading = function onManifestLoading() {
this.lastSn = -1; // Detect discontiguity in fragment parsing
this.prevCC = -1;
this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests
this._cleanTracks();
};
TimelineController.prototype._cleanTracks = function _cleanTracks() {
// clear outdated subtitles
var media = this.media;
if (media) {
var textTracks = media.textTracks;
share/public_html/static/hls.js view on Meta::CPAN
_this3.textTracks.push(textTrack);
});
}
};
TimelineController.prototype.onLevelSwitching = function onLevelSwitching() {
this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
};
TimelineController.prototype.onFragLoaded = function onFragLoaded(data) {
var frag = data.frag,
payload = data.payload;
if (frag.type === 'main') {
var sn = frag.sn;
// if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
if (sn !== this.lastSn + 1) {
var cea608Parser = this.cea608Parser;
if (cea608Parser) {
cea608Parser.reset();
}
}
this.lastSn = sn;
} // eslint-disable-line brace-style
// If fragment is subtitle type, parse as WebVTT.
else if (frag.type === 'subtitle') {
if (payload.byteLength) {
// We need an initial synchronisation PTS. Store fragments as long as none has arrived.
if (typeof this.initPTS === 'undefined') {
this.unparsedVttFrags.push(data);
return;
}
var decryptData = frag.decryptdata;
// If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
this._parseVTTs(frag, payload);
}
} else {
// In case there is no payload, finish unsuccessfully.
this.hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
}
}
};
TimelineController.prototype._parseVTTs = function _parseVTTs(frag, payload) {
var vttCCs = this.vttCCs;
if (!vttCCs[frag.cc]) {
vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
this.prevCC = frag.cc;
}
var textTracks = this.textTracks,
hls = this.hls;
// Parse the WebVTT file contents.
webvtt_parser.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {
var currentTrack = textTracks[frag.trackId];
// WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
// before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
// and trying to access getCueById method of cues will throw an exception
if (currentTrack.mode === 'disabled') {
hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
return;
}
// Add cues and trigger event with success true.
cues.forEach(function (cue) {
// Sometimes there are cue overlaps on segmented vtts so the same
// cue can appear more than once in different vtt files.
// This avoid showing duplicated cues with same timecode and text.
if (!currentTrack.cues.getCueById(cue.id)) {
try {
currentTrack.addCue(cue);
} catch (err) {
var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
textTrackCue.id = cue.id;
currentTrack.addCue(textTrackCue);
}
}
});
hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
}, function (e) {
// Something went wrong while parsing. Trigger event with success false.
logger["b" /* logger */].log('Failed to parse VTT cue: ' + e);
hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
});
};
TimelineController.prototype.onFragDecrypted = function onFragDecrypted(data) {
var decryptedData = data.payload,
frag = data.frag;
if (frag.type === 'subtitle') {
if (typeof this.initPTS === 'undefined') {
this.unparsedVttFrags.push(data);
return;
}
this._parseVTTs(frag, decryptedData);
}
};
TimelineController.prototype.onFragParsingUserdata = function onFragParsingUserdata(data) {
// push all of the CEA-708 messages into the interpreter
// immediately. It will create the proper timestamps based on our PTS value
if (this.enabled && this.config.enableCEA708Captions) {
for (var i = 0; i < data.samples.length; i++) {
var ccdatas = this.extractCea608Data(data.samples[i].bytes);
this.cea608Parser.addData(data.samples[i].pts, ccdatas);
share/public_html/static/hls.js view on Meta::CPAN
SubtitleStreamController.prototype.clearVttFragQueues = function clearVttFragQueues() {
var _this2 = this;
this.vttFragQueues = {};
this.tracks.forEach(function (track) {
_this2.vttFragQueues[track.id] = [];
});
};
// If no frag is being processed and queue isn't empty, initiate processing of next frag in line.
SubtitleStreamController.prototype.nextFrag = function nextFrag() {
if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {
var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();
this.fragCurrent = frag;
this.hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
this.state = subtitle_stream_controller_State.FRAG_LOADING;
}
};
// When fragment has finished processing, add sn to list of completed if successful.
SubtitleStreamController.prototype.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) {
if (data.success) {
this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);
}
this.currentlyProcessing = null;
this.state = subtitle_stream_controller_State.IDLE;
this.nextFrag();
};
SubtitleStreamController.prototype.onMediaAttached = function onMediaAttached() {
this.state = subtitle_stream_controller_State.IDLE;
};
// If something goes wrong, procede to next frag, if we were processing one.
SubtitleStreamController.prototype.onError = function onError(data) {
var frag = data.frag;
// don't handle frag error not related to subtitle fragment
if (frag && frag.type !== 'subtitle') {
return;
}
if (this.currentlyProcessing) {
this.currentlyProcessing = null;
this.nextFrag();
}
};
SubtitleStreamController.prototype.doTick = function doTick() {
var _this3 = this;
switch (this.state) {
case subtitle_stream_controller_State.IDLE:
var tracks = this.tracks;
var trackId = this.currentTrackId;
var processedFragSNs = this.vttFragSNsProcessed[trackId],
fragQueue = this.vttFragQueues[trackId],
currentFragSN = this.currentlyProcessing ? this.currentlyProcessing.sn : -1;
var alreadyProcessed = function alreadyProcessed(frag) {
return processedFragSNs.indexOf(frag.sn) > -1;
};
var alreadyInQueue = function alreadyInQueue(frag) {
return fragQueue.some(function (fragInQueue) {
return fragInQueue.sn === frag.sn;
});
};
// exit if tracks don't exist
if (!tracks) {
break;
}
var trackDetails;
if (trackId < tracks.length) {
trackDetails = tracks[trackId].details;
}
if (typeof trackDetails === 'undefined') {
break;
}
// Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue.
trackDetails.fragments.forEach(function (frag) {
if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {
// Load key if subtitles are encrypted
if (frag.encrypted) {
logger["b" /* logger */].log('Loading key for ' + frag.sn);
_this3.state = subtitle_stream_controller_State.KEY_LOADING;
_this3.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
} else {
// Frags don't know their subtitle track ID, so let's just add that...
frag.trackId = trackId;
fragQueue.push(frag);
_this3.nextFrag();
}
}
});
}
};
// Got all new subtitle tracks.
share/public_html/static/hls.js view on Meta::CPAN
});
};
SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) {
this.currentTrackId = data.id;
if (!this.tracks || this.currentTrackId === -1) {
return;
}
// Check if track was already loaded and if so make sure we finish
// downloading its frags, if not all have been downloaded yet
var currentTrack = this.tracks[this.currentTrackId];
if (currentTrack && currentTrack.details) {
this.tick();
}
};
// Got a new set of subtitle fragments.
SubtitleStreamController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded() {
this.tick();
};
SubtitleStreamController.prototype.onKeyLoaded = function onKeyLoaded() {
if (this.state === subtitle_stream_controller_State.KEY_LOADING) {
this.state = subtitle_stream_controller_State.IDLE;
this.tick();
}
};
SubtitleStreamController.prototype.onFragLoaded = function onFragLoaded(data) {
var fragCurrent = this.fragCurrent,
decryptData = data.frag.decryptdata;
var fragLoaded = data.frag,
hls = this.hls;
if (this.state === subtitle_stream_controller_State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
// check to see if the payload needs to be decrypted
if (data.payload.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.method === 'AES-128') {
var startTime = void 0;
try {
startTime = subtitle_stream_controller_performance.now();
} catch (error) {
startTime = Date.now();
}
// decrypt the subtitles
this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
var endTime = void 0;
try {
endTime = subtitle_stream_controller_performance.now();
} catch (error) {
endTime = Date.now();
}
hls.trigger(events["a" /* default */].FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
});
}
}
};
return SubtitleStreamController;
}(task_loop);
/* harmony default export */ var subtitle_stream_controller = (subtitle_stream_controller_SubtitleStreamController);
// CONCATENATED MODULE: ./src/controller/eme-controller.js
share/public_html/static/hls.js view on Meta::CPAN
enableSoftwareAES: true, // used by decrypter
manifestLoadingTimeOut: 10000, // used by playlist-loader
manifestLoadingMaxRetry: 1, // used by playlist-loader
manifestLoadingRetryDelay: 1000, // used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
startLevel: undefined, // used by level-controller
levelLoadingTimeOut: 10000, // used by playlist-loader
levelLoadingMaxRetry: 4, // used by playlist-loader
levelLoadingRetryDelay: 1000, // used by playlist-loader
levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
fragLoadingTimeOut: 20000, // used by fragment-loader
fragLoadingMaxRetry: 6, // used by fragment-loader
fragLoadingRetryDelay: 1000, // used by fragment-loader
fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
startFragPrefetch: false, // used by stream-controller
fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
appendErrorMaxRetry: 3, // used by buffer-controller
loader: xhr_loader,
// loader: FetchLoader,
fLoader: undefined, // used by fragment-loader
pLoader: undefined, // used by playlist-loader
xhrSetup: undefined, // used by xhr-loader
licenseXhrSetup: undefined, // used by eme-controller
// fetchSetup: undefined,
abrController: abr_controller,
bufferController: buffer_controller,
capLevelController: cap_level_controller,
fpsController: fps_controller,
stretchShortVideoTrack: false, // used by mp4-remuxer
maxAudioFramesDrift: 1, // used by mp4-remuxer
share/public_html/static/hls.js view on Meta::CPAN
/**
* @member {AbrController} abrController
*/
var abrController = this.abrController = new config.abrController(this);
var bufferController = new config.bufferController(this);
var capLevelController = new config.capLevelController(this);
var fpsController = new config.fpsController(this);
var playListLoader = new playlist_loader(this);
var fragmentLoader = new fragment_loader(this);
var keyLoader = new key_loader(this);
var id3TrackController = new id3_track_controller(this);
// network controllers
/**
* @member {LevelController} levelController
*/
var levelController = this.levelController = new level_controller(this);
// FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new fragment_tracker_FragmentTracker(this);
/**
* @member {StreamController} streamController
*/
var streamController = this.streamController = new stream_controller(this, fragmentTracker);
var networkControllers = [levelController, streamController];
// optional audio stream controller
/**
* @var {ICoreComponent | Controller}
*/
var Controller = config.audioStreamController;
if (Controller) {
networkControllers.push(new Controller(this, fragmentTracker));
}
/**
* @member {INetworkController[]} networkControllers
*/
this.networkControllers = networkControllers;
/**
* @var {ICoreComponent[]}
*/
var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
// optional audio track and subtitle controller
Controller = config.audioTrackController;
if (Controller) {
var audioTrackController = new Controller(this);
/**
* @member {AudioTrackController} audioTrackController
*/
this.audioTrackController = audioTrackController;
share/public_html/static/hls.js view on Meta::CPAN
}, {
key: 'nextLevel',
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set nextLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
share/public_html/static/hls.js view on Meta::CPAN
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set firstLevel:' + newLevel);
this.levelController.firstLevel = newLevel;
}
/**
* Return start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number}
*/
}, {
key: 'startLevel',
get: function get() {
return this.levelController.startLevel;
}
/**
* set start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set startLevel:' + newLevel);
var hls = this;
// if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
share/public_html/static/hls.js view on Meta::CPAN
get: function get() {
var hls = this;
// ensure next auto level is between min and max auto level
return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
}
/**
* this setter is used to force next auto level.
* this is useful to force a switch down in auto mode:
* in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
* forced value is valid for one fragment. upon succesful frag loading at forced level,
* this value will be resetted to -1 by ABR controller.
* @type {number}
*/
,
set: function set(nextLevel) {
var hls = this;
hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
}
/**
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
} dsound;
#endif
#ifdef MA_SUPPORT_WINMM
struct
{
/*HWAVEOUT*/ ma_handle hDevicePlayback;
/*HWAVEIN*/ ma_handle hDeviceCapture;
/*HANDLE*/ ma_handle hEventPlayback;
/*HANDLE*/ ma_handle hEventCapture;
ma_uint32 fragmentSizeInFrames;
ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
ma_uint32 headerFramesConsumedCapture; /* ^^^ */
/*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
/*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
ma_uint8* pIntermediaryBufferPlayback;
ma_uint8* pIntermediaryBufferCapture;
ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
} winmm;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
Remarks
-------
This API needs to wait on the worker thread to stop the backend device properly before returning. It also waits on a mutex for thread-safety. In addition, some
backends need to wait for the device to finish playback/recording of the current fragment which can take some time (usually proportionate to the buffer size
that was specified at initialization time).
Backends are required to either pause the stream in-place or drain the buffer if pausing is not possible. The reason for this is that stopping the device and
the resuming it with ma_device_start() (which you might do when your program loses focus) may result in a situation where those samples are never output to the
speakers or received from the microphone which can in turn result in de-syncs.
Do not call this in any callback.
This will be called implicitly by `ma_device_uninit()`.
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (pConfig->capture.pDeviceID != NULL) {
winMMDeviceIDCapture = (UINT)pConfig->capture.pDeviceID->winmm;
}
/* The capture device needs to be initialized first. */
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
WAVEINCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventCapture = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventCapture == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalPeriods = pConfig->periods;
pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, pDevice->capture.internalSampleRate);
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
WAVEOUTCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventPlayback = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventPlayback == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
typedef struct ma_pa_operation ma_pa_operation;
typedef struct ma_pa_stream ma_pa_stream;
typedef struct ma_pa_spawn_api ma_pa_spawn_api;
typedef struct
{
ma_uint32 maxlength;
ma_uint32 tlength;
ma_uint32 prebuf;
ma_uint32 minreq;
ma_uint32 fragsize;
} ma_pa_buffer_attr;
typedef struct
{
ma_uint8 channels;
ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
} ma_pa_channel_map;
typedef struct
{
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
}
static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
{
ma_pa_buffer_attr attr;
attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
attr.tlength = attr.maxlength / periods;
attr.prebuf = (ma_uint32)-1;
attr.minreq = (ma_uint32)-1;
attr.fragsize = attr.maxlength / periods;
return attr;
}
static ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap)
{
static int g_StreamCounter = 0;
char actualStreamName[256];
if (pStreamName != NULL) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
ss = sourceInfo.sample_spec;
cmap = sourceInfo.channel_map;
pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, ss.rate);
pDevice->capture.internalPeriods = pConfig->periods;
attr = ma_device__pa_buffer_attr_new(pDevice->capture.internalPeriodSizeInFrames, pConfig->periods, &ss);
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalPeriodSizeInFram...
#endif
pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
if (pDevice->pulse.pStreamCapture == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
goto on_error3;
}
streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
if (devCapture != NULL) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
pDevice->capture.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
}
/* Buffer. */
pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (pActualAttr != NULL) {
attr = *pActualAttr;
}
pDevice->capture.internalPeriods = attr.maxlength / attr.fragsize;
pDevice->capture.internalPeriodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels) / pDevice->capture.internalPeriods;
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalPeriodSiz...
#endif
/* Name. */
devCapture = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (devCapture != NULL) {
ma_pa_operation* pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devCapture, ma_device_source_name_callback, pDevice);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
ss = sinkInfo.sample_spec;
cmap = sinkInfo.channel_map;
pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, ss.rate);
pDevice->playback.internalPeriods = pConfig->periods;
attr = ma_device__pa_buffer_attr_new(pDevice->playback.internalPeriodSizeInFrames, pConfig->periods, &ss);
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalPeriodSizeInFr...
#endif
pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
if (pDevice->pulse.pStreamPlayback == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
goto on_error3;
}
streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
if (devPlayback != NULL) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
/* Buffer. */
pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (pActualAttr != NULL) {
attr = *pActualAttr;
}
pDevice->playback.internalPeriods = attr.maxlength / attr.tlength;
pDevice->playback.internalPeriodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels) / pDevice->playback.internalPeriods;
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalPeriodS...
#endif
/* Name. */
devPlayback = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (devPlayback != NULL) {
ma_pa_operation* pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devPlayback, ma_device_sink_name_callback, pDevice);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
*/
if (pDevice->pulse.mappedBufferFramesRemainingCapture > 0) {
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityCapture - pDevice->pulse.mappedBufferFramesRemainingCapture;
ma_uint32 framesToCopy = ma_min(pDevice->pulse.mappedBufferFramesRemainingCapture, (frameCount - totalFramesRead));
void* pDst = (ma_uint8*)pPCMFrames + (totalFramesRead * bpf);
/*
This little bit of logic here is specifically for PulseAudio and it's hole management. The buffer pointer will be set to NULL
when the current fragment is a hole. For a hole we just output silence.
*/
if (pDevice->pulse.pMappedBufferCapture != NULL) {
const void* pSrc = (const ma_uint8*)pDevice->pulse.pMappedBufferCapture + (mappedBufferFramesConsumed * bpf);
MA_COPY_MEMORY(pDst, pSrc, framesToCopy * bpf);
} else {
MA_ZERO_MEMORY(pDst, framesToCopy * bpf);
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Filling hole with silence.\n");
#endif
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
*/
if (pDevice->pulse.mappedBufferFramesCapacityCapture > 0 && pDevice->pulse.mappedBufferFramesRemainingCapture == 0) {
int error;
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Call pa_stream_drop()\n");
#endif
error = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (error != 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to drop fragment.", ma_result_from_pulse(error));
}
pDevice->pulse.pMappedBufferCapture = NULL;
pDevice->pulse.mappedBufferFramesRemainingCapture = 0;
pDevice->pulse.mappedBufferFramesCapacityCapture = 0;
}
MA_ASSERT(totalFramesRead <= frameCount);
if (totalFramesRead == frameCount) {
break;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* Sample Rate. */
ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.", MA_FORMAT_NOT_SUPPORTED);
}
/*
Buffer.
The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
it should be done before or after format/channels/rate.
OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
value.
*/
{
ma_uint32 periodSizeInFrames;
ma_uint32 periodSizeInBytes;
ma_uint32 ossFragmentSizePower;
periodSizeInFrames = pConfig->periodSizeInFrames;
if (periodSizeInFrames == 0) {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, (ma_uint32)ossSampleRate);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ossFragmentSizePower = 4;
periodSizeInBytes >>= 4;
while (periodSizeInBytes >>= 1) {
ossFragmentSizePower += 1;
}
ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.", MA_FORMAT_NOT_SUPPORTED);
}
}
/* Internal settings. */
if (deviceType == ma_device_type_capture) {
pDevice->oss.fdCapture = fd;
pDevice->capture.internalFormat = ma_format_from_oss(ossFormat);
pDevice->capture.internalChannels = ossChannels;
pDevice->capture.internalSampleRate = ossSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sound4, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
/*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
} dsound;
#endif
#ifdef MA_SUPPORT_WINMM
struct
{
/*HWAVEOUT*/ ma_handle hDevicePlayback;
/*HWAVEIN*/ ma_handle hDeviceCapture;
/*HANDLE*/ ma_handle hEventPlayback;
/*HANDLE*/ ma_handle hEventCapture;
ma_uint32 fragmentSizeInFrames;
ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
ma_uint32 headerFramesConsumedCapture; /* ^^^ */
/*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
/*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
ma_uint8* pIntermediaryBufferPlayback;
ma_uint8* pIntermediaryBufferCapture;
ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
} winmm;
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
Remarks
-------
This API needs to wait on the worker thread to stop the backend device properly before returning. It also waits on a mutex for thread-safety. In addition, some
backends need to wait for the device to finish playback/recording of the current fragment which can take some time (usually proportionate to the buffer size
that was specified at initialization time).
Backends are required to either pause the stream in-place or drain the buffer if pausing is not possible. The reason for this is that stopping the device and
the resuming it with ma_device_start() (which you might do when your program loses focus) may result in a situation where those samples are never output to the
speakers or received from the microphone which can in turn result in de-syncs.
Do not call this in any callback.
This will be called implicitly by `ma_device_uninit()`.
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
if (pDescriptorCapture->pDeviceID != NULL) {
winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm;
}
/* The capture device needs to be initialized first. */
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
WAVEINCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventCapture = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventCapture == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
pDescriptorCapture->periodCount = pDescriptorCapture->periodCount;
pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
WAVEOUTCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventPlayback = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventPlayback == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
typedef struct ma_pa_operation ma_pa_operation;
typedef struct ma_pa_stream ma_pa_stream;
typedef struct ma_pa_spawn_api ma_pa_spawn_api;
typedef struct
{
ma_uint32 maxlength;
ma_uint32 tlength;
ma_uint32 prebuf;
ma_uint32 minreq;
ma_uint32 fragsize;
} ma_pa_buffer_attr;
typedef struct
{
ma_uint8 channels;
ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
} ma_pa_channel_map;
typedef struct
{
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
return MA_SUCCESS;
}
static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
{
ma_pa_buffer_attr attr;
attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
attr.tlength = attr.maxlength / periods;
attr.prebuf = (ma_uint32)-1;
attr.minreq = (ma_uint32)-1;
attr.fragsize = attr.maxlength / periods;
return attr;
}
static ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap)
{
static int g_StreamCounter = 0;
char actualStreamName[256];
if (pStreamName != NULL) {
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
}
if (ss.channels == 0) {
ss.channels = MA_DEFAULT_CHANNELS;
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
}
/* We now have enough information to calculate our actual period size in frames. */
pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorCapture, ss.rate, pConfig->performanceProfile);
attr = ma_device__pa_buffer_attr_new(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodCount, &ss);
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsi...
pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
if (pDevice->pulse.pStreamCapture == NULL) {
ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.\n");
result = MA_ERROR;
goto on_error0;
}
/* The callback needs to be set before connecting the stream. */
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
}
}
/* Buffer. */
pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (pActualAttr != NULL) {
attr = *pActualAttr;
}
if (attr.fragsize > 0) {
pDescriptorCapture->periodCount = ma_max(attr.maxlength / attr.fragsize, 1);
} else {
pDescriptorCapture->periodCount = 1;
}
pDescriptorCapture->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / pDescriptorCapture->periodCount;
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr...
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
result = ma_context_get_sink_info__pulse(pDevice->pContext, devPlayback, &sinkInfo);
if (result != MA_SUCCESS) {
ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.\n");
goto on_error2;
}
ss = sinkInfo.sample_spec;
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
if (ss.channels == 0) {
ss.channels = MA_DEFAULT_CHANNELS;
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
}
/* We now have enough information to calculate the actual buffer size in frames. */
pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorPlayback, ss.rate, pConfig->performanceProfile);
attr = ma_device__pa_buffer_attr_new(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodCount, &ss);
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; periodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.frags...
pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
if (pDevice->pulse.pStreamPlayback == NULL) {
ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.\n");
result = MA_ERROR;
goto on_error2;
}
/*
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
attr = *pActualAttr;
}
if (attr.tlength > 0) {
pDescriptorPlayback->periodCount = ma_max(attr.maxlength / attr.tlength, 1);
} else {
pDescriptorPlayback->periodCount = 1;
}
pDescriptorPlayback->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) / pDescriptorPlayback->periodCount;
ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.min...
}
/*
We need a ring buffer for handling duplex mode. We can use the main duplex ring buffer in the main
part of the ma_device struct. We cannot, however, depend on ma_device_init() initializing this for
us later on because that will only do it if it's a fully asynchronous backend - i.e. the
onDeviceDataLoop callback is NULL, which is not the case for PulseAudio.
*/
if (pConfig->deviceType == ma_device_type_duplex) {
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
if (ossResult == -1) {
close(fd);
ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.");
return ma_result_from_errno(errno);
}
/*
Buffer.
The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
it should be done before or after format/channels/rate.
OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
value.
*/
{
ma_uint32 periodSizeInFrames;
ma_uint32 periodSizeInBytes;
ma_uint32 ossFragmentSizePower;
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, (ma_uint32)ossSampleRate, pConfig->performanceProfile);
periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels));
share/public_html/static/music_worklet_inprogress/decoder/deps/miniaudio/miniaudio.h view on Meta::CPAN
ossFragmentSizePower = 4;
periodSizeInBytes >>= 4;
while (periodSizeInBytes >>= 1) {
ossFragmentSizePower += 1;
}
ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
if (ossResult == -1) {
close(fd);
ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.");
return ma_result_from_errno(errno);
}
}
/* Internal settings. */
if (deviceType == ma_device_type_capture) {
pDevice->oss.fdCapture = fd;
} else {
pDevice->oss.fdPlayback = fd;
}