UNPKG

2.66 kBJavaScriptView Raw
1/**
2 * @file ad-cue-tags.js
3 */
4import window from 'global/window';
5
6/**
7 * Searches for an ad cue that overlaps with the given mediaTime
8 *
9 * @param {Object} track
10 * the track to find the cue for
11 *
12 * @param {number} mediaTime
13 * the time to find the cue at
14 *
15 * @return {Object|null}
16 * the found cue or null
17 */
18export const findAdCue = function(track, mediaTime) {
19 const cues = track.cues;
20
21 for (let i = 0; i < cues.length; i++) {
22 const cue = cues[i];
23
24 if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
25 return cue;
26 }
27 }
28 return null;
29};
30
31export const updateAdCues = function(media, track, offset = 0) {
32 if (!media.segments) {
33 return;
34 }
35
36 let mediaTime = offset;
37 let cue;
38
39 for (let i = 0; i < media.segments.length; i++) {
40 const segment = media.segments[i];
41
42 if (!cue) {
43 // Since the cues will span for at least the segment duration, adding a fudge
44 // factor of half segment duration will prevent duplicate cues from being
45 // created when timing info is not exact (e.g. cue start time initialized
46 // at 10.006677, but next call mediaTime is 10.003332 )
47 cue = findAdCue(track, mediaTime + (segment.duration / 2));
48 }
49
50 if (cue) {
51 if ('cueIn' in segment) {
52 // Found a CUE-IN so end the cue
53 cue.endTime = mediaTime;
54 cue.adEndTime = mediaTime;
55 mediaTime += segment.duration;
56 cue = null;
57 continue;
58 }
59
60 if (mediaTime < cue.endTime) {
61 // Already processed this mediaTime for this cue
62 mediaTime += segment.duration;
63 continue;
64 }
65
66 // otherwise extend cue until a CUE-IN is found
67 cue.endTime += segment.duration;
68
69 } else {
70 if ('cueOut' in segment) {
71 cue = new window.VTTCue(
72 mediaTime,
73 mediaTime + segment.duration,
74 segment.cueOut
75 );
76 cue.adStartTime = mediaTime;
77 // Assumes tag format to be
78 // #EXT-X-CUE-OUT:30
79 cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
80 track.addCue(cue);
81 }
82
83 if ('cueOutCont' in segment) {
84 // Entered into the middle of an ad cue
85 // Assumes tag formate to be
86 // #EXT-X-CUE-OUT-CONT:10/30
87 const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
88
89 cue = new window.VTTCue(
90 mediaTime,
91 mediaTime + segment.duration,
92 ''
93 );
94 cue.adStartTime = mediaTime - adOffset;
95 cue.adEndTime = cue.adStartTime + adTotal;
96 track.addCue(cue);
97 }
98 }
99 mediaTime += segment.duration;
100 }
101};