UNPKG

15.1 kBJavaScriptView Raw
1/**
2 * @file playlist.js
3 *
4 * Playlist related utilities.
5 */
6import {createTimeRange} from 'video.js';
7import window from 'global/window';
8
9let Playlist = {
10 /**
11 * The number of segments that are unsafe to start playback at in
12 * a live stream. Changing this value can cause playback stalls.
13 * See HTTP Live Streaming, "Playing the Media Playlist File"
14 * https://tools.ietf.org/html/draft-pantos-http-live-streaming-18#section-6.3.3
15 */
16 UNSAFE_LIVE_SEGMENTS: 3
17};
18
19/**
20 * walk backward until we find a duration we can use
21 * or return a failure
22 *
23 * @param {Playlist} playlist the playlist to walk through
24 * @param {Number} endSequence the mediaSequence to stop walking on
25 */
26
27const backwardDuration = function(playlist, endSequence) {
28 let result = 0;
29 let i = endSequence - playlist.mediaSequence;
30 // if a start time is available for segment immediately following
31 // the interval, use it
32 let segment = playlist.segments[i];
33
34 // Walk backward until we find the latest segment with timeline
35 // information that is earlier than endSequence
36 if (segment) {
37 if (typeof segment.start !== 'undefined') {
38 return { result: segment.start, precise: true };
39 }
40 if (typeof segment.end !== 'undefined') {
41 return {
42 result: segment.end - segment.duration,
43 precise: true
44 };
45 }
46 }
47 while (i--) {
48 segment = playlist.segments[i];
49 if (typeof segment.end !== 'undefined') {
50 return { result: result + segment.end, precise: true };
51 }
52
53 result += segment.duration;
54
55 if (typeof segment.start !== 'undefined') {
56 return { result: result + segment.start, precise: true };
57 }
58 }
59 return { result, precise: false };
60};
61
62/**
63 * walk forward until we find a duration we can use
64 * or return a failure
65 *
66 * @param {Playlist} playlist the playlist to walk through
67 * @param {Number} endSequence the mediaSequence to stop walking on
68 */
69const forwardDuration = function(playlist, endSequence) {
70 let result = 0;
71 let segment;
72 let i = endSequence - playlist.mediaSequence;
73 // Walk forward until we find the earliest segment with timeline
74 // information
75
76 for (; i < playlist.segments.length; i++) {
77 segment = playlist.segments[i];
78 if (typeof segment.start !== 'undefined') {
79 return {
80 result: segment.start - result,
81 precise: true
82 };
83 }
84
85 result += segment.duration;
86
87 if (typeof segment.end !== 'undefined') {
88 return {
89 result: segment.end - result,
90 precise: true
91 };
92 }
93
94 }
95 // indicate we didn't find a useful duration estimate
96 return { result: -1, precise: false };
97};
98
99/**
100 * Calculate the media duration from the segments associated with a
101 * playlist. The duration of a subinterval of the available segments
102 * may be calculated by specifying an end index.
103 *
104 * @param {Object} playlist a media playlist object
105 * @param {Number=} endSequence an exclusive upper boundary
106 * for the playlist. Defaults to playlist length.
107 * @param {Number} expired the amount of time that has dropped
108 * off the front of the playlist in a live scenario
109 * @return {Number} the duration between the first available segment
110 * and end index.
111 */
112const intervalDuration = function(playlist, endSequence, expired) {
113 let backward;
114 let forward;
115
116 if (typeof endSequence === 'undefined') {
117 endSequence = playlist.mediaSequence + playlist.segments.length;
118 }
119
120 if (endSequence < playlist.mediaSequence) {
121 return 0;
122 }
123
124 // do a backward walk to estimate the duration
125 backward = backwardDuration(playlist, endSequence);
126 if (backward.precise) {
127 // if we were able to base our duration estimate on timing
128 // information provided directly from the Media Source, return
129 // it
130 return backward.result;
131 }
132
133 // walk forward to see if a precise duration estimate can be made
134 // that way
135 forward = forwardDuration(playlist, endSequence);
136 if (forward.precise) {
137 // we found a segment that has been buffered and so it's
138 // position is known precisely
139 return forward.result;
140 }
141
142 // return the less-precise, playlist-based duration estimate
143 return backward.result + expired;
144};
145
146/**
147 * Calculates the duration of a playlist. If a start and end index
148 * are specified, the duration will be for the subset of the media
149 * timeline between those two indices. The total duration for live
150 * playlists is always Infinity.
151 *
152 * @param {Object} playlist a media playlist object
153 * @param {Number=} endSequence an exclusive upper
154 * boundary for the playlist. Defaults to the playlist media
155 * sequence number plus its length.
156 * @param {Number=} expired the amount of time that has
157 * dropped off the front of the playlist in a live scenario
158 * @return {Number} the duration between the start index and end
159 * index.
160 */
161export const duration = function(playlist, endSequence, expired) {
162 if (!playlist) {
163 return 0;
164 }
165
166 if (typeof expired !== 'number') {
167 expired = 0;
168 }
169
170 // if a slice of the total duration is not requested, use
171 // playlist-level duration indicators when they're present
172 if (typeof endSequence === 'undefined') {
173 // if present, use the duration specified in the playlist
174 if (playlist.totalDuration) {
175 return playlist.totalDuration;
176 }
177
178 // duration should be Infinity for live playlists
179 if (!playlist.endList) {
180 return window.Infinity;
181 }
182 }
183
184 // calculate the total duration based on the segment durations
185 return intervalDuration(playlist,
186 endSequence,
187 expired);
188};
189
190/**
191 * Calculate the time between two indexes in the current playlist
192 * neight the start- nor the end-index need to be within the current
193 * playlist in which case, the targetDuration of the playlist is used
194 * to approximate the durations of the segments
195 *
196 * @param {Object} playlist a media playlist object
197 * @param {Number} startIndex
198 * @param {Number} endIndex
199 * @return {Number} the number of seconds between startIndex and endIndex
200 */
201export const sumDurations = function(playlist, startIndex, endIndex) {
202 let durations = 0;
203
204 if (startIndex > endIndex) {
205 [startIndex, endIndex] = [endIndex, startIndex];
206 }
207
208 if (startIndex < 0) {
209 for (let i = startIndex; i < Math.min(0, endIndex); i++) {
210 durations += playlist.targetDuration;
211 }
212 startIndex = 0;
213 }
214
215 for (let i = startIndex; i < endIndex; i++) {
216 durations += playlist.segments[i].duration;
217 }
218
219 return durations;
220};
221
222/**
223 * Calculates the playlist end time
224 *
225 * @param {Object} playlist a media playlist object
226 * @param {Number=} expired the amount of time that has
227 * dropped off the front of the playlist in a live scenario
228 * @param {Boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
229 * playlist end calculation should consider the safe live end
230 * (truncate the playlist end by three segments). This is normally
231 * used for calculating the end of the playlist's seekable range.
232 * @returns {Number} the end time of playlist
233 * @function playlistEnd
234 */
235export const playlistEnd = function(playlist, expired, useSafeLiveEnd) {
236 if (!playlist || !playlist.segments) {
237 return null;
238 }
239 if (playlist.endList) {
240 return duration(playlist);
241 }
242
243 if (expired === null) {
244 return null;
245 }
246
247 expired = expired || 0;
248
249 let endSequence = useSafeLiveEnd ?
250 Math.max(0, playlist.segments.length - Playlist.UNSAFE_LIVE_SEGMENTS) :
251 Math.max(0, playlist.segments.length);
252
253 return intervalDuration(playlist,
254 playlist.mediaSequence + endSequence,
255 expired);
256};
257
258/**
259 * Calculates the interval of time that is currently seekable in a
260 * playlist. The returned time ranges are relative to the earliest
261 * moment in the specified playlist that is still available. A full
262 * seekable implementation for live streams would need to offset
263 * these values by the duration of content that has expired from the
264 * stream.
265 *
266 * @param {Object} playlist a media playlist object
267 * dropped off the front of the playlist in a live scenario
268 * @param {Number=} expired the amount of time that has
269 * dropped off the front of the playlist in a live scenario
270 * @return {TimeRanges} the periods of time that are valid targets
271 * for seeking
272 */
273export const seekable = function(playlist, expired) {
274 let useSafeLiveEnd = true;
275 let seekableStart = expired || 0;
276 let seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd);
277
278 if (seekableEnd === null) {
279 return createTimeRange();
280 }
281 return createTimeRange(seekableStart, seekableEnd);
282};
283
284const isWholeNumber = function(num) {
285 return (num - Math.floor(num)) === 0;
286};
287
288const roundSignificantDigit = function(increment, num) {
289 // If we have a whole number, just add 1 to it
290 if (isWholeNumber(num)) {
291 return num + (increment * 0.1);
292 }
293
294 let numDecimalDigits = num.toString().split('.')[1].length;
295
296 for (let i = 1; i <= numDecimalDigits; i++) {
297 let scale = Math.pow(10, i);
298 let temp = num * scale;
299
300 if (isWholeNumber(temp) ||
301 i === numDecimalDigits) {
302 return (temp + increment) / scale;
303 }
304 }
305};
306
307const ceilLeastSignificantDigit = roundSignificantDigit.bind(null, 1);
308const floorLeastSignificantDigit = roundSignificantDigit.bind(null, -1);
309
310/**
311 * Determine the index and estimated starting time of the segment that
312 * contains a specified playback position in a media playlist.
313 *
314 * @param {Object} playlist the media playlist to query
315 * @param {Number} currentTime The number of seconds since the earliest
316 * possible position to determine the containing segment for
317 * @param {Number} startIndex
318 * @param {Number} startTime
319 * @return {Object}
320 */
321export const getMediaInfoForTime = function(playlist,
322 currentTime,
323 startIndex,
324 startTime) {
325 let i;
326 let segment;
327 let numSegments = playlist.segments.length;
328
329 let time = currentTime - startTime;
330
331 if (time < 0) {
332 // Walk backward from startIndex in the playlist, adding durations
333 // until we find a segment that contains `time` and return it
334 if (startIndex > 0) {
335 for (i = startIndex - 1; i >= 0; i--) {
336 segment = playlist.segments[i];
337 time += floorLeastSignificantDigit(segment.duration);
338 if (time > 0) {
339 return {
340 mediaIndex: i,
341 startTime: startTime - sumDurations(playlist, startIndex, i)
342 };
343 }
344 }
345 }
346 // We were unable to find a good segment within the playlist
347 // so select the first segment
348 return {
349 mediaIndex: 0,
350 startTime: currentTime
351 };
352 }
353
354 // When startIndex is negative, we first walk forward to first segment
355 // adding target durations. If we "run out of time" before getting to
356 // the first segment, return the first segment
357 if (startIndex < 0) {
358 for (i = startIndex; i < 0; i++) {
359 time -= playlist.targetDuration;
360 if (time < 0) {
361 return {
362 mediaIndex: 0,
363 startTime: currentTime
364 };
365 }
366 }
367 startIndex = 0;
368 }
369
370 // Walk forward from startIndex in the playlist, subtracting durations
371 // until we find a segment that contains `time` and return it
372 for (i = startIndex; i < numSegments; i++) {
373 segment = playlist.segments[i];
374 time -= ceilLeastSignificantDigit(segment.duration);
375 if (time < 0) {
376 return {
377 mediaIndex: i,
378 startTime: startTime + sumDurations(playlist, startIndex, i)
379 };
380 }
381 }
382
383 // We are out of possible candidates so load the last one...
384 return {
385 mediaIndex: numSegments - 1,
386 startTime: currentTime
387 };
388};
389
390/**
391 * Check whether the playlist is blacklisted or not.
392 *
393 * @param {Object} playlist the media playlist object
394 * @return {boolean} whether the playlist is blacklisted or not
395 * @function isBlacklisted
396 */
397export const isBlacklisted = function(playlist) {
398 return playlist.excludeUntil && playlist.excludeUntil > Date.now();
399};
400
401/**
402 * Check whether the playlist is enabled or not.
403 *
404 * @param {Object} playlist the media playlist object
405 * @return {boolean} whether the playlist is enabled or not
406 * @function isEnabled
407 */
408export const isEnabled = function(playlist) {
409 const blacklisted = isBlacklisted(playlist);
410
411 return (!playlist.disabled && !blacklisted);
412};
413
414/**
415 * Returns whether the current playlist is an AES encrypted HLS stream
416 *
417 * @return {Boolean} true if it's an AES encrypted HLS stream
418 */
419export const isAes = function(media) {
420 for (let i = 0; i < media.segments.length; i++) {
421 if (media.segments[i].key) {
422 return true;
423 }
424 }
425 return false;
426};
427
428/**
429 * Returns whether the current playlist contains fMP4
430 *
431 * @return {Boolean} true if the playlist contains fMP4
432 */
433export const isFmp4 = function(media) {
434 for (let i = 0; i < media.segments.length; i++) {
435 if (media.segments[i].map) {
436 return true;
437 }
438 }
439 return false;
440};
441
442/**
443 * Checks if the playlist has a value for the specified attribute
444 *
445 * @param {String} attr
446 * Attribute to check for
447 * @param {Object} playlist
448 * The media playlist object
449 * @return {Boolean}
450 * Whether the playlist contains a value for the attribute or not
451 * @function hasAttribute
452 */
453export const hasAttribute = function(attr, playlist) {
454 return playlist.attributes && playlist.attributes[attr];
455};
456
457/**
458 * Estimates the time required to complete a segment download from the specified playlist
459 *
460 * @param {Number} segmentDuration
461 * Duration of requested segment
462 * @param {Number} bandwidth
463 * Current measured bandwidth of the player
464 * @param {Object} playlist
465 * The media playlist object
466 * @param {Number=} bytesReceived
467 * Number of bytes already received for the request. Defaults to 0
468 * @return {Number|NaN}
469 * The estimated time to request the segment. NaN if bandwidth information for
470 * the given playlist is unavailable
471 * @function estimateSegmentRequestTime
472 */
473export const estimateSegmentRequestTime = function(segmentDuration,
474 bandwidth,
475 playlist,
476 bytesReceived = 0) {
477 if (!hasAttribute('BANDWIDTH', playlist)) {
478 return NaN;
479 }
480
481 const size = segmentDuration * playlist.attributes.BANDWIDTH;
482
483 return (size - (bytesReceived * 8)) / bandwidth;
484};
485
486Playlist.duration = duration;
487Playlist.seekable = seekable;
488Playlist.getMediaInfoForTime = getMediaInfoForTime;
489Playlist.isEnabled = isEnabled;
490Playlist.isBlacklisted = isBlacklisted;
491Playlist.playlistEnd = playlistEnd;
492Playlist.isAes = isAes;
493Playlist.isFmp4 = isFmp4;
494Playlist.hasAttribute = hasAttribute;
495Playlist.estimateSegmentRequestTime = estimateSegmentRequestTime;
496
497// exports
498export default Playlist;