/
streaming_engine_unit.js
3527 lines (2995 loc) · 123 KB
/
streaming_engine_unit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.media.InitSegmentReference');
goog.require('shaka.media.SegmentReference');
goog.require('shaka.media.StreamingEngine');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.net.NetworkingEngine.PendingRequest');
goog.require('shaka.test.FakeNetworkingEngine');
goog.require('shaka.test.FakeMediaSourceEngine');
goog.require('shaka.test.ManifestGenerator');
goog.require('shaka.test.StreamingEngineUtil');
goog.require('shaka.test.Util');
goog.require('shaka.util.AbortableOperation');
goog.require('shaka.util.Error');
goog.require('shaka.util.Iterables');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.PlayerConfiguration');
goog.require('shaka.util.PublicPromise');
goog.require('shaka.util.Uint8ArrayUtils');
goog.requireType('shaka.media.PresentationTimeline');
goog.requireType('shaka.test.FakeNetworkingEngine');
goog.requireType('shaka.test.FakePresentationTimeline');
describe('StreamingEngine', () => {
const Util = shaka.test.Util;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const Uint8ArrayUtils = shaka.util.Uint8ArrayUtils;
// Dummy byte ranges and sizes for initialization and media segments.
// Create empty object first and initialize the fields through
// [] to allow field names to be expressions.
/**
* @type {!Object.<shaka.util.ManifestParserUtils.ContentType,
* !Array.<number>>}
*/
const initSegmentRanges = {};
initSegmentRanges[ContentType.AUDIO] = [100, 1000];
initSegmentRanges[ContentType.VIDEO] = [200, 2000];
/** @type {!Object.<shaka.util.ManifestParserUtils.ContentType, number>} */
const segmentSizes = {};
segmentSizes[ContentType.AUDIO] = 1000;
segmentSizes[ContentType.VIDEO] = 10000;
segmentSizes[ContentType.TEXT] = 500;
/** @type {!Object.<string, shaka.test.FakeMediaSourceEngine.SegmentData>} */
let segmentData;
/** @type {number} */
let presentationTimeInSeconds;
/** @type {boolean} */
let playing;
/** @type {!shaka.test.FakeMediaSourceEngine} */
let mediaSourceEngine;
/** @type {{audio: number, video: number, text: number}} */
let netEngineDelays;
/** @type {!shaka.test.FakeNetworkingEngine} */
let netEngine;
/** @type {{start: number, end: number}} */
let segmentAvailability;
/** @type {!shaka.test.FakePresentationTimeline} */
let timeline;
/** @type {?shaka.extern.Stream} */
let audioStream;
/** @type {?shaka.extern.Stream} */
let videoStream;
/** @type {shaka.extern.Variant} */
let variant;
/** @type {shaka.extern.Stream} */
let textStream;
/** @type {shaka.extern.Variant} */
let alternateVariant;
/** @type {shaka.extern.Stream} */
let alternateVideoStream;
/** @type {shaka.extern.Manifest} */
let manifest;
/** @type {!jasmine.Spy} */
let onError;
/** @type {!jasmine.Spy} */
let onEvent;
/** @type {!jasmine.Spy} */
let onManifestUpdate;
/** @type {!jasmine.Spy} */
let onSegmentAppended;
/** @type {!jasmine.Spy} */
let getBandwidthEstimate;
/** @type {!shaka.media.StreamingEngine} */
let streamingEngine;
/**
* Runs the fake event loop.
* @param {function()=} callback An optional callback that is executed
* each time the clock ticks.
*/
async function runTest(callback) {
async function onTick(currentTime) {
if (callback) {
await callback();
}
if (playing) {
presentationTimeInSeconds++;
}
}
// No test should require more than 60 seconds of simulated time.
await Util.fakeEventLoop(60, onTick);
}
beforeAll(() => {
jasmine.clock().install();
jasmine.clock().mockDate();
});
/** @param {boolean=} trickMode
* @param {number=} mediaOffset The offset from 0 for the segment start times
*/
function setupVod(trickMode, mediaOffset) {
// For VOD, we fake a presentation that has 2 Periods of equal duration
// (20 seconds), where each Period has 1 Variant and 1 text stream.
//
// There are 4 initialization segments: 1 audio and 1 video for the
// first Period, and 1 audio and 1 video for the second Period.
//
// There are 12 media segments: 2 audio, 2 video, and 2 text for the
// first Period, and 2 audio, 2 video, and 2 text for the second Period.
// All media segments are (by default) 10 seconds long.
const offset = mediaOffset || 0;
// timestampOffset is -ve since it is added to bring the timeline to 0.
// -0 and 0 are not same so explicitly set to 0.
const timestampOffset = offset === 0 ? 0 : -offset;
// Create SegmentData map for FakeMediaSourceEngine.
const initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] -
initSegmentRanges[ContentType.AUDIO][0] + 1;
const initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] -
initSegmentRanges[ContentType.VIDEO][0] + 1;
const makeBuffer = (size) => new ArrayBuffer(size);
segmentData = {
audio: {
initSegments: [
makeBuffer(initSegmentSizeAudio),
makeBuffer(initSegmentSizeAudio),
],
segments: [
makeBuffer(segmentSizes[ContentType.AUDIO]),
makeBuffer(segmentSizes[ContentType.AUDIO]),
makeBuffer(segmentSizes[ContentType.AUDIO]),
makeBuffer(segmentSizes[ContentType.AUDIO]),
],
segmentStartTimes: [offset, offset+10, offset+20, offset+30],
segmentDuration: 10,
timestampOffset: timestampOffset,
},
video: {
initSegments: [
makeBuffer(initSegmentSizeVideo),
makeBuffer(initSegmentSizeVideo),
],
segments: [
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
],
segmentStartTimes: [offset, offset+10, offset+20, offset+30],
segmentDuration: 10,
timestampOffset: timestampOffset,
},
text: {
initSegments: [],
segments: [
makeBuffer(segmentSizes[ContentType.TEXT]),
makeBuffer(segmentSizes[ContentType.TEXT]),
makeBuffer(segmentSizes[ContentType.TEXT]),
makeBuffer(segmentSizes[ContentType.TEXT]),
],
segmentStartTimes: [offset, offset+10, offset+20, offset+30],
segmentDuration: 10,
timestampOffset: timestampOffset,
},
};
if (trickMode) {
segmentData.trickvideo = {
initSegments: [
makeBuffer(initSegmentSizeVideo),
makeBuffer(initSegmentSizeVideo),
],
segments: [
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
makeBuffer(segmentSizes[ContentType.VIDEO]),
],
segmentStartTimes: [offset, offset+10, offset+20, offset+30],
segmentDuration: 10,
timestampOffset: timestampOffset,
};
}
presentationTimeInSeconds = 0;
playing = false;
setupNetworkingEngine(
/* segmentsInFirstPeriod= */ 2,
/* segmentsInSecondPeriod= */ 2);
segmentAvailability = {
start: 0,
end: 40,
};
timeline = shaka.test.StreamingEngineUtil.createFakePresentationTimeline(
segmentAvailability,
/* presentationDuration= */ 40,
/* maxSegmentDuration= */ 10,
/* isLive= */ false);
setupManifest(
/* firstPeriodStartTime= */ 0,
/* secondPeriodStartTime= */ 20,
/* presentationDuration= */ 40);
}
function setupLive() {
// For live, we fake a presentation that has 2 Periods of different
// durations (120 seconds and 20 seconds respectively), where each Period
// has 1 Variant and 1 text stream.
//
// There are 4 initialization segments: 1 audio and 1 video for the
// first Period, and 1 audio and 1 video for the second Period.
//
// There are 14 media segments: 12 audio, 12 video, and 12 text for the
// first Period, and 2 audio, 2 video, and 2 text for the second Period.
// All media segments are (by default) 10 seconds long.
//
// The segment availability window starts at t=100 (segment 11) and extends
// to t=120 (segment 13).
// Create SegmentData map for FakeMediaSourceEngine.
const initSegmentSizeAudio = initSegmentRanges[ContentType.AUDIO][1] -
initSegmentRanges[ContentType.AUDIO][0] + 1;
const initSegmentSizeVideo = initSegmentRanges[ContentType.VIDEO][1] -
initSegmentRanges[ContentType.VIDEO][0] + 1;
const makeBuffer = (size) => new ArrayBuffer(size);
segmentData = {
audio: {
initSegments:
[makeBuffer(initSegmentSizeAudio),
makeBuffer(initSegmentSizeAudio)],
segments: [],
segmentStartTimes: [],
segmentDuration: 10,
},
video: {
initSegments:
[makeBuffer(initSegmentSizeVideo),
makeBuffer(initSegmentSizeVideo)],
segments: [],
segmentStartTimes: [],
segmentDuration: 10,
},
text: {
initSegments: [],
segments: [],
segmentStartTimes: [],
segmentDuration: 10,
},
};
const segmentsInFirstPeriod = 12;
for (const i of shaka.util.Iterables.range(segmentsInFirstPeriod)) {
segmentData[ContentType.AUDIO].segments.push(
makeBuffer(segmentSizes[ContentType.AUDIO]));
segmentData[ContentType.VIDEO].segments.push(
makeBuffer(segmentSizes[ContentType.VIDEO]));
segmentData[ContentType.TEXT].segments.push(
makeBuffer(segmentSizes[ContentType.TEXT]));
segmentData[ContentType.AUDIO].segmentStartTimes.push(i * 10);
segmentData[ContentType.VIDEO].segmentStartTimes.push(i * 10);
segmentData[ContentType.TEXT].segmentStartTimes.push(i * 10);
}
const segmentsInSecondPeriod = 2;
for (const i of shaka.util.Iterables.range(segmentsInSecondPeriod)) {
segmentData[ContentType.AUDIO].segments.push(
makeBuffer(segmentSizes[ContentType.AUDIO]));
segmentData[ContentType.VIDEO].segments.push(
makeBuffer(segmentSizes[ContentType.VIDEO]));
segmentData[ContentType.TEXT].segments.push(
makeBuffer(segmentSizes[ContentType.TEXT]));
segmentData[ContentType.AUDIO].segmentStartTimes.push(
(segmentsInFirstPeriod + i) * 10);
segmentData[ContentType.VIDEO].segmentStartTimes.push(
(segmentsInFirstPeriod + i) * 10);
segmentData[ContentType.TEXT].segmentStartTimes.push(
(segmentsInFirstPeriod + i) * 10);
}
presentationTimeInSeconds = 110;
playing = false;
setupNetworkingEngine(
/* segmentsInFirstPeriod= */ 12,
/* segmentsInSecondPeriod= */ 2);
// NOTE: Many tests here start playback at 100, so the availability start is
// 90. This allows the async index creation processes to complete before
// the window moves, which gives us the startup conditions the tests expect.
// Keep in mind that the fake event loop in the tests ticks in whole
// seconds, so real async processes may take a surprising amount of fake
// time to complete. To test actual boundary conditions, you can change
// segmentAvailability.start in the test setup.
segmentAvailability = {
start: 90,
end: 140,
};
timeline = shaka.test.StreamingEngineUtil.createFakePresentationTimeline(
segmentAvailability,
/* presentationDuration= */ 140,
/* maxSegmentDuration= */ 10,
/* isLive= */ true);
setupManifest(
/* firstPeriodStartTime= */ 0,
/* secondPeriodStartTime= */ 120,
/* presentationDuration= */ 140);
}
function setupNetworkingEngine(
segmentsInFirstPeriod, segmentsInSecondPeriod) {
// Create the fake NetworkingEngine. Note: the StreamingEngine should never
// request a segment that does not exist.
netEngineDelays = {
audio: 0,
video: 0,
text: 0,
};
netEngine = shaka.test.StreamingEngineUtil.createFakeNetworkingEngine(
// Init segment generator:
(type, periodIndex) => {
expect((periodIndex == 0) || (periodIndex == 1));
return segmentData[type].initSegments[periodIndex];
},
// Media segment generator:
(type, periodIndex, position) => {
expect(position).toBeGreaterThan(-1);
expect((periodIndex == 0 && position <= segmentsInFirstPeriod) ||
(periodIndex == 1 && position <= segmentsInSecondPeriod));
const segment = segmentData[type].segments[position];
const startTime = segmentData[type].segmentStartTimes[position];
const endTime = startTime + segmentData[type].segmentDuration;
if (endTime < segmentAvailability.start ||
startTime > segmentAvailability.end) {
// Return null if the segment is out of the segment availability
// window.
return null;
}
return segment;
},
/* delays= */ netEngineDelays);
}
function setupManifest(
firstPeriodStartTime, secondPeriodStartTime, presentationDuration) {
const segmentDurations = {
audio: segmentData[ContentType.AUDIO].segmentDuration,
video: segmentData[ContentType.VIDEO].segmentDuration,
text: segmentData[ContentType.TEXT].segmentDuration,
};
const timestampOffsets = {
audio: segmentData[ContentType.AUDIO].timestampOffset,
video: segmentData[ContentType.VIDEO].timestampOffset,
text: segmentData[ContentType.TEXT].timestampOffset,
};
if (segmentData['trickvideo']) {
segmentDurations['trickvideo'] =
segmentData['trickvideo'].segmentDuration;
timestampOffsets['trickvideo'] =
segmentData['trickvideo'].timestampOffset;
}
manifest = shaka.test.StreamingEngineUtil.createManifest(
/** @type {!shaka.media.PresentationTimeline} */(timeline),
[firstPeriodStartTime, secondPeriodStartTime],
presentationDuration, segmentDurations, initSegmentRanges,
timestampOffsets);
audioStream = manifest.variants[0].audio;
videoStream = manifest.variants[0].video;
variant = manifest.variants[0];
textStream = manifest.textStreams[0];
// This Stream is only used to verify that StreamingEngine can setup
// Streams correctly.
alternateVideoStream =
shaka.test.StreamingEngineUtil.createMockVideoStream(8);
alternateVariant = {
audio: audioStream,
video: /** @type {shaka.extern.Stream} */ (alternateVideoStream),
id: 0,
language: 'und',
primary: false,
bandwidth: 0,
allowedByApplication: true,
allowedByKeySystem: true,
decodingInfos: [],
};
manifest.variants.push(alternateVariant);
}
/**
* Creates the StreamingEngine.
**
* @param {shaka.extern.StreamingConfiguration=} config Optional
* configuration object which overrides the default one.
*/
function createStreamingEngine(config) {
onError = jasmine.createSpy('onError');
onError.and.callFake(fail);
onEvent = jasmine.createSpy('onEvent');
onManifestUpdate = jasmine.createSpy('onManifestUpdate');
onSegmentAppended = jasmine.createSpy('onSegmentAppended');
getBandwidthEstimate = jasmine.createSpy('getBandwidthEstimate');
getBandwidthEstimate.and.returnValue(1e3);
if (!config) {
config = shaka.util.PlayerConfiguration.createDefault().streaming;
config.rebufferingGoal = 2;
config.bufferingGoal = 5;
config.bufferBehind = Infinity;
}
goog.asserts.assert(
presentationTimeInSeconds != undefined,
'All tests should have defined an initial presentation time by now!');
const playerInterface = {
modifySegmentRequest: (request, segmentInfo) => {},
getPresentationTime: () => presentationTimeInSeconds,
getBandwidthEstimate: Util.spyFunc(getBandwidthEstimate),
mediaSourceEngine: mediaSourceEngine,
netEngine: /** @type {!shaka.net.NetworkingEngine} */(netEngine),
onError: Util.spyFunc(onError),
onEvent: Util.spyFunc(onEvent),
onManifestUpdate: Util.spyFunc(onManifestUpdate),
onSegmentAppended: Util.spyFunc(onSegmentAppended),
onInitSegmentAppended: () => {},
};
streamingEngine = new shaka.media.StreamingEngine(
/** @type {shaka.extern.Manifest} */(manifest), playerInterface);
streamingEngine.configure(config);
}
afterEach(() => {
streamingEngine.destroy().catch(fail);
});
afterAll(() => {
jasmine.clock().uninstall();
});
// This test initializes the StreamingEngine (SE) and allows it to play
// through both Periods.
//
// After construction of StreamingEngine, the following should occur:
// 1. The owner should immediately call switchVariant() with the initial
// variant.
// 2. The owner should call start().
// 3. SE should setup each of the initial Streams.
// 4. SE should start appending the initial Streams' segments.
// 5. SE should call MediaSourceEngine.endOfStream() after it has appended
// both segments from the second Period. At this point, the playhead
// should not be at the end of the presentation, but the test will be
// effectively over since SE will have nothing else to do.
it('initializes and plays VOD', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
// Verify buffers.
expect(mediaSourceEngine.initSegments).toEqual({
audio: [false, false],
video: [false, false],
text: [],
});
expect(mediaSourceEngine.segments).toEqual({
audio: [false, false, false, false],
video: [false, false, false, false],
text: [false, false, false, false],
});
const expectedMseInit = new Map();
expectedMseInit.set(ContentType.AUDIO, audioStream);
expectedMseInit.set(ContentType.VIDEO, videoStream);
expectedMseInit.set(ContentType.TEXT, textStream);
expect(mediaSourceEngine.init).toHaveBeenCalledWith(expectedMseInit, false);
expect(mediaSourceEngine.init).toHaveBeenCalledTimes(1);
expect(mediaSourceEngine.setDuration).toHaveBeenCalledTimes(1);
expect(mediaSourceEngine.setDuration).toHaveBeenCalledWith(40);
await runTest();
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
// Verify buffers.
expect(mediaSourceEngine.initSegments).toEqual({
audio: [false, true],
video: [false, true],
text: [],
});
expect(mediaSourceEngine.segments).toEqual({
audio: [true, true, true, true],
video: [true, true, true, true],
text: [true, true, true, true],
});
netEngine.expectRangeRequest(
'0_audio_init',
initSegmentRanges[ContentType.AUDIO][0],
initSegmentRanges[ContentType.AUDIO][1]);
netEngine.expectRangeRequest(
'0_video_init',
initSegmentRanges[ContentType.VIDEO][0],
initSegmentRanges[ContentType.VIDEO][1]);
netEngine.expectRangeRequest(
'1_audio_init',
initSegmentRanges[ContentType.AUDIO][0],
initSegmentRanges[ContentType.AUDIO][1]);
netEngine.expectRangeRequest(
'1_video_init',
initSegmentRanges[ContentType.VIDEO][0],
initSegmentRanges[ContentType.VIDEO][1]);
const segmentType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
netEngine.expectRequest('0_audio_0', segmentType);
netEngine.expectRequest('0_video_0', segmentType);
netEngine.expectRequest('0_text_0', segmentType);
netEngine.expectRequest('0_audio_1', segmentType);
netEngine.expectRequest('0_video_1', segmentType);
netEngine.expectRequest('0_text_1', segmentType);
netEngine.expectRequest('1_audio_2', segmentType);
netEngine.expectRequest('1_video_2', segmentType);
netEngine.expectRequest('1_text_2', segmentType);
netEngine.expectRequest('1_audio_3', segmentType);
netEngine.expectRequest('1_video_3', segmentType);
netEngine.expectRequest('1_text_3', segmentType);
});
describe('unloadTextStream', () => {
it('doesn\'t send requests for text after calling unload', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
// Verify that after unloading text stream, no network request for text
// is sent.
await runTest(() => {
const segmentType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
if (presentationTimeInSeconds == 1) {
netEngine.expectRequest('0_text_0', segmentType);
netEngine.request.calls.reset();
streamingEngine.unloadTextStream();
} else if (presentationTimeInSeconds == 35) {
netEngine.expectNoRequest('0_text_0', segmentType);
netEngine.expectNoRequest('0_text_1', segmentType);
netEngine.expectNoRequest('1_text_2', segmentType);
netEngine.expectNoRequest('1_text_3', segmentType);
}
});
});
it('sets the current text stream to null', async () => {
createStreamingEngine();
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
expect(streamingEngine.getCurrentTextStream()).not.toBe(null);
await streamingEngine.start();
playing = true;
streamingEngine.unloadTextStream();
expect(streamingEngine.getCurrentTextStream()).toBe(null);
});
});
it('initializes and plays live', async () => {
setupLive();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
presentationTimeInSeconds = 100;
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest(slideSegmentAvailabilityWindow);
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
// Verify buffers.
expect(mediaSourceEngine.initSegments).toEqual({
audio: [false, true],
video: [false, true],
text: [],
});
// Since we started playback from segment 11, segments 10 through 14
// should be buffered. Those segment numbers are 1-based, and this array
// is 0-based, so we expect i >= 9 to be downloaded.
const segments = mediaSourceEngine.segments;
for (const i of shaka.util.Iterables.range(14)) {
expect(segments[ContentType.AUDIO][i]).withContext(i).toBe(i >= 9);
expect(segments[ContentType.VIDEO][i]).withContext(i).toBe(i >= 9);
expect(segments[ContentType.TEXT][i]).withContext(i).toBe(i >= 9);
}
});
it('appends the ReadableStream data with low latency mode', async () => {
// Use the VOD manifests to test the streamDataCallback function in the low
// latency mode.
setupVod();
const config = shaka.util.PlayerConfiguration.createDefault().streaming;
config.lowLatencyMode = true;
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
mediaSourceEngine.appendBuffer.and.stub();
createStreamingEngine(config);
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
// In the mocks in StreamingEngineUtil, each segment gets fetched as two
// chunks of data, and each chunk contains one MDAT box.
// The streamDataCallback function will be triggered twice for each
// audio/video MP4 segment.
// appendBuffer should be called once for each init segment of the
// audio / video segment, and twice for each segment.
// 4 init segments + 8 audio/video segments * 2 + 4 text segments = 24.
if (window.ReadableStream) {
expect(mediaSourceEngine.appendBuffer).toHaveBeenCalledTimes(24);
} else {
// If ReadableStream is not supported by the browser, fall back to regular
// streaming.
// 4 init segments + 8 audio/video segments + 4 text segments = 16.
expect(mediaSourceEngine.appendBuffer).toHaveBeenCalledTimes(16);
}
});
it('plays when a small gap is present at the beginning', async () => {
const drift = 0.050; // 50 ms
setupVod();
mediaSourceEngine =
new shaka.test.FakeMediaSourceEngine(segmentData, drift);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
});
it('plays with no chosen text streams', async () => {
setupVod();
manifest.textStreams = [];
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
// Don't call switchTextStream.
await streamingEngine.start();
playing = true;
await runTest();
expect(mediaSourceEngine.segments).toEqual({
audio: [true, true, true, true],
video: [true, true, true, true],
text: [false, false, false, false],
});
});
it('updates the timeline duration to match media duration', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
mediaSourceEngine.endOfStream.and.callFake(() => {
expect(mediaSourceEngine.setDuration).toHaveBeenCalledWith(40);
expect(mediaSourceEngine.setDuration).toHaveBeenCalledTimes(1);
mediaSourceEngine.setDuration.calls.reset();
// Simulate the media ending BEFORE the expected (manifest) duration.
mediaSourceEngine.getDuration.and.returnValue(35);
return Promise.resolve();
});
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
expect(timeline.setDuration).toHaveBeenCalledWith(35);
});
// https://github.com/google/shaka-player/issues/979
it('does not expand the timeline duration', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
mediaSourceEngine.endOfStream.and.callFake(() => {
expect(mediaSourceEngine.setDuration).toHaveBeenCalledWith(40);
expect(mediaSourceEngine.setDuration).toHaveBeenCalledTimes(1);
mediaSourceEngine.setDuration.calls.reset();
// Simulate the media ending AFTER the expected (manifest) duration.
mediaSourceEngine.getDuration.and.returnValue(41);
return Promise.resolve();
});
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
expect(timeline.setDuration).not.toHaveBeenCalled();
});
// https://github.com/google/shaka-player/issues/1967
it('does not change duration when 0', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// The duration can spuriously be set to 0, so we should ignore this and not
// update the duration.
mediaSourceEngine.getDuration.and.returnValue(0);
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
expect(timeline.setDuration).not.toHaveBeenCalled();
});
it('applies fudge factors for append window', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
// The second Period starts at 20, so we should set the appendWindowStart to
// 20, but reduced by a small fudge factor.
const lt20 = {
asymmetricMatch: (val) => val >= 19.9 && val < 20,
};
const gt40 = {
asymmetricMatch: (val) => val > 40 && val <= 40.1,
};
expect(mediaSourceEngine.setStreamProperties)
.toHaveBeenCalledWith('video', 0, lt20, gt40);
});
// Regression test for https://github.com/google/shaka-player/issues/3717
it('applies fudge factors for the duration', async () => {
setupVod();
// In #3717, the duration was just barely large enough to encompass an
// additional segment, but that segment didn't exist, so playback never
// completed. Here, we set the duration to just beyond the 3rd segment, and
// we make the 4th segment fail when requested.
const duration = 30.000000005;
timeline.getDuration.and.returnValue(duration);
const targetUri = '1_video_3'; // The URI of the 4th video segment.
failRequestsForTarget(netEngine, targetUri);
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
// The end of the stream should have been reached, and the 4th segment from
// each type should never have been requested.
expect(mediaSourceEngine.endOfStream).toHaveBeenCalled();
const segmentType = shaka.net.NetworkingEngine.RequestType.SEGMENT;
netEngine.expectRequest('0_audio_0', segmentType);
netEngine.expectRequest('0_video_0', segmentType);
netEngine.expectRequest('0_text_0', segmentType);
netEngine.expectRequest('0_audio_1', segmentType);
netEngine.expectRequest('0_video_1', segmentType);
netEngine.expectRequest('0_text_1', segmentType);
netEngine.expectRequest('1_audio_2', segmentType);
netEngine.expectRequest('1_video_2', segmentType);
netEngine.expectRequest('1_text_2', segmentType);
netEngine.expectNoRequest('1_audio_3', segmentType);
netEngine.expectNoRequest('1_video_3', segmentType);
netEngine.expectNoRequest('1_text_3', segmentType);
});
it('does not buffer one media type ahead of another', async () => {
setupVod();
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
const config = shaka.util.PlayerConfiguration.createDefault().streaming;
config.bufferingGoal = 60;
config.failureCallback = () => streamingEngine.retry();
createStreamingEngine(config);
// Make requests for different types take different amounts of time.
// This would let some media types buffer faster than others if unchecked.
netEngineDelays.text = 0.1;
netEngineDelays.audio = 1.0;
netEngineDelays.video = 5.0; // Need init segment and media segment
mediaSourceEngine.appendBuffer.and.callFake((type, data, start, end) => {
// Call to the underlying implementation.
const p = mediaSourceEngine.appendBufferImpl(type, data, start, end);
// Validate that no one media type got ahead of any other.
let minBuffered = Infinity;
let maxBuffered = 0;
for (const t of ['audio', 'video', 'text']) {
const buffered = mediaSourceEngine.bufferedAheadOfImpl(t, 0);
minBuffered = Math.min(minBuffered, buffered);
maxBuffered = Math.max(maxBuffered, buffered);
}
// Simulated playback doesn't start until some of each is buffered. This
// realism is important to the test passing.
if (minBuffered > 0) {
playing = true;
}
// Sanity check.
expect(maxBuffered).not.toBeLessThan(minBuffered);
// Proof that we didn't get too far ahead (10s == 1 segment).
expect(maxBuffered - minBuffered).not.toBeGreaterThan(10);
return p;
});
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
// Simulated playback is started in the appendBuffer fake when some of each
// type is buffered. This realism is important to the test passing.
playing = false;
await runTest();
// Make sure appendBuffer was called, so that we know that we executed the
// checks in our fake above.
expect(mediaSourceEngine.appendBuffer).toHaveBeenCalled();
});
// https://github.com/google/shaka-player/issues/2957
it('plays with fewer text segments', async () => {
setupVod();
// Only use one segment for text, which will buffer less than the others.
segmentData['text'].segments.splice(1, 3);
await textStream.createSegmentIndex();
const oldGet = /** @type {?} */ (textStream.segmentIndex.get);
textStream.segmentIndex.get = (idx) => {
return idx > 0 ? null : oldGet(idx);
};
mediaSourceEngine = new shaka.test.FakeMediaSourceEngine(segmentData);
createStreamingEngine();
// Here we go!
streamingEngine.switchVariant(variant);
streamingEngine.switchTextStream(textStream);
await streamingEngine.start();
playing = true;
await runTest();
expect(mediaSourceEngine.segments).toEqual({
audio: [true, true, true, true],
video: [true, true, true, true],
text: [true],
});
});
describe('switchVariant/switchTextStream', () => {
let initialVariant;
let sameAudioVariant;
let sameVideoVariant;
let differentVariant;
let initialTextStream;
let newTextStream;
beforeEach(() => {
// Set up a manifest with multiple variants and a text stream.
manifest = shaka.test.ManifestGenerator.generate((manifest) => {
manifest.presentationTimeline.setDuration(60);
manifest.addVariant(0, (variant) => {
variant.addAudio(10, (stream) => {
stream.useSegmentTemplate('audio-10-%d.mp4', 10);
});
variant.addVideo(11, (stream) => {
stream.useSegmentTemplate('video-11-%d.mp4', 10);
});
});
manifest.addVariant(1, (variant) => {
variant.addExistingStream(10); // audio
variant.addVideo(12, (stream) => {
stream.useSegmentTemplate('video-12-%d.mp4', 10);
});
});
manifest.addVariant(2, (variant) => {
variant.addAudio(13, (stream) => {
stream.useSegmentTemplate('audio-13-%d.mp4', 10);
});
variant.addExistingStream(12); // video
});
manifest.addVariant(3, (variant) => {
variant.addVideo(14, (stream) => {
stream.useSegmentTemplate('video-14-%d.mp4', 10);
});
variant.addAudio(15, (stream) => {
stream.useSegmentTemplate('audio-15-%d.mp4', 10);
});
});
manifest.addTextStream(20, (stream) => {