/
storage_integration.js
1843 lines (1595 loc) · 63 KB
/
storage_integration.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.Player');
goog.require('shaka.media.DrmEngine');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.SegmentIndex');
goog.require('shaka.net.NetworkingEngine.RequestType');
goog.require('shaka.offline.ManifestConverter');
goog.require('shaka.offline.OfflineUri');
goog.require('shaka.offline.Storage');
goog.require('shaka.offline.StorageMuxer');
goog.require('shaka.test.FakeDrmEngine');
goog.require('shaka.test.FakeManifestParser');
goog.require('shaka.test.FakeNetworkingEngine');
goog.require('shaka.test.Loader');
goog.require('shaka.test.ManifestGenerator');
goog.require('shaka.test.TestScheme');
goog.require('shaka.test.Util');
goog.require('shaka.util.AbortableOperation');
goog.require('shaka.util.BufferUtils');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.PlayerConfiguration');
goog.require('shaka.util.PublicPromise');
goog.require('shaka.util.Uint8ArrayUtils');
goog.requireType('shaka.media.SegmentReference');
/** @return {boolean} */
function storageSupport() {
return shaka.offline.Storage.support();
}
/** @return {!Promise.<boolean>} */
async function drmStorageSupport() {
if (!shaka.offline.Storage.support()) {
return false;
}
const support = await shaka.Player.probeSupport();
const widevineSupport = support.drm['com.widevine.alpha'];
return !!(widevineSupport && widevineSupport.persistentState);
}
filterDescribe('Storage', storageSupport, () => {
const Util = shaka.test.Util;
const englishUS = 'en-us';
const frenchCanadian = 'fr-ca';
const fakeMimeType = 'application/test';
const manifestWithPerStreamBandwidthUri =
'fake:manifest-with-per-stream-bandwidth';
const manifestWithoutPerStreamBandwidthUri =
'fake:manifest-without-per-stream-bandwidth';
const manifestWithNonZeroStartUri = 'fake:manifest-with-non-zero-start';
const manifestWithLiveTimelineUri = 'fake:manifest-with-live-timeline';
const manifestWithAlternateSegmentsUri = 'fake:manifest-with-alt-segments';
const manifestWithVideoInitSegmentsUri =
'fake:manifest-with-video-init-segments';
const initSegmentUri = 'fake:init-segment';
const segment1Uri = 'fake:segment-1';
const segment2Uri = 'fake:segment-2';
const segment3Uri = 'fake:segment-3';
const segment4Uri = 'fake:segment-4';
const alternateInitSegmentUri = 'fake:alt-init-segment';
const alternateSegment1Uri = 'fake:alt-segment-1';
const alternateSegment2Uri = 'fake:alt-segment-2';
const alternateSegment3Uri = 'fake:alt-segment-3';
const alternateSegment4Uri = 'fake:alt-segment-4';
const noMetadata = {};
const kbps = (k) => k * 1000;
beforeEach(async () => {
// Make sure we start with a clean slate between each run.
await eraseStorage();
shaka.media.ManifestParser.registerParserByMime(
fakeMimeType, () => new FakeManifestParser());
});
afterEach(async () => {
shaka.media.ManifestParser.unregisterParserByMime(fakeMimeType);
// Make sure we don't leave anything behind.
await eraseStorage();
});
describe('storage delete all', () => {
/** @type {!shaka.Player} */
let player;
beforeEach(() => {
// Use a real Player since Storage only uses the configuration and
// networking engine. This allows us to use Player.configure in these
// tests.
player = new shaka.Player();
});
afterEach(async () => {
await player.destroy();
});
it('removes all content from storage', async () => {
const testSchemeMimeType = 'application/x-test-manifest';
const manifestUri = 'test:sintel';
// Store a piece of content.
await withStorage((storage) => {
return storage.store(
manifestUri, noMetadata, testSchemeMimeType).promise;
});
// Make sure that the content can be found.
await withStorage(async (storage) => {
const content = await storage.list();
expect(content).toBeTruthy();
expect(content.length).toBe(1);
});
// Ask storage to erase everything.
await shaka.offline.Storage.deleteAll();
// Make sure that all content that was previously found is no gone.
await withStorage(async (storage) => {
const content = await storage.list();
expect(content).toBeTruthy();
expect(content.length).toBe(0);
});
});
/**
* @param {function(!shaka.offline.Storage)|
* function(!shaka.offline.Storage):!Promise} action
* @return {!Promise}
*/
async function withStorage(action) {
/** @type {!shaka.offline.Storage} */
const storage = new shaka.offline.Storage(player);
try {
await action(storage);
} finally {
await storage.destroy();
}
}
});
filterDescribe('persistent license', drmStorageSupport, () => {
/** @type {!shaka.Player} */
let player;
/** @type {!shaka.offline.Storage} */
let storage;
beforeEach(() => {
// Use a real Player since Storage only uses the configuration and
// networking engine. This allows us to use Player.configure in these
// tests.
player = new shaka.Player();
storage = new shaka.offline.Storage(player);
});
afterEach(async () => {
await storage.destroy();
await player.destroy();
});
// TODO: Make a test to ensure that setting delayLicenseRequestUntilPlayed
// to true doesn't break storage, once we have working tests for storing DRM
// content.
// See issue #2218.
// Quarantined due to http://crbug.com/1019298 where a load cannot happen
// immediately after a remove. This can sometimes be fixed with a delay,
// but it is extremely flaky, so these are disabled until the bug is fixed.
quarantinedIt('removes persistent license', async () => {
const testSchemeMimeType = 'application/x-test-manifest';
// PART 1 - Download and store content that has a persistent license
// associated with it.
const stored = await storage.store(
'test:sintel-enc', noMetadata, testSchemeMimeType).promise;
goog.asserts.assert(stored.offlineUri != null, 'URI should not be null!');
/** @type {shaka.offline.OfflineUri} */
const uri = shaka.offline.OfflineUri.parse(stored.offlineUri);
goog.asserts.assert(uri, 'Stored offline uri should be non-null');
const manifest = await getStoredManifest(uri);
expect(manifest.offlineSessionIds).toBeTruthy();
expect(manifest.offlineSessionIds.length).toBeTruthy();
// PART 2 - Check that the licences are stored.
await withDrm(player, manifest, (drm) => {
return Promise.all(manifest.offlineSessionIds.map(async (session) => {
const foundSession = await loadOfflineSession(drm, session);
expect(foundSession).toBeTruthy();
}));
});
// PART 3 - Remove the manifest from storage. This should remove all
// the sessions.
await storage.remove(uri.toString());
// PART 4 - Check that the licenses were removed.
const p = withDrm(player, manifest, (drm) => {
return Promise.all(manifest.offlineSessionIds.map(async (session) => {
const notFoundSession = await loadOfflineSession(drm, session);
expect(notFoundSession).toBeFalsy();
}));
});
const expected = Util.jasmineError(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.OFFLINE_SESSION_REMOVED));
await expectAsync(p).toBeRejectedWith(expected);
});
quarantinedIt('defers removing licenses on error', async () => {
const testSchemeMimeType = 'application/x-test-manifest';
// PART 1 - Download and store content that has a persistent license
// associated with it.
const stored = await storage.store(
'test:sintel-enc', noMetadata, testSchemeMimeType).promise;
goog.asserts.assert(stored.offlineUri != null, 'URI should not be null!');
/** @type {shaka.offline.OfflineUri} */
const uri = shaka.offline.OfflineUri.parse(stored.offlineUri);
goog.asserts.assert(uri, 'Stored offline uri should be non-null');
const manifest = await getStoredManifest(uri);
// PART 2 - Add an error so the release license message fails.
storage.getNetworkingEngine().registerRequestFilter(
(type, request) => {
if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) {
throw new Error('Error should be ignored');
}
});
// PART 3 - Remove the manifest from storage. This should ignore the
// error with the EME session. It should also store the session for
// later removal.
await storage.remove(uri.toString());
// PART 4 - Verify the media was deleted but the session still exists.
const storedContents = await storage.list();
expect(storedContents).toEqual([]);
await withDrm(player, manifest, (drm) => {
return Promise.all(manifest.offlineSessionIds.map(async (session) => {
const foundSession = await loadOfflineSession(drm, session);
expect(foundSession).toBeTruthy();
}));
});
// PART 5 - Disable the error and remove the EME session.
storage.getNetworkingEngine().clearAllRequestFilters();
const didRemoveAll = await storage.removeEmeSessions();
expect(didRemoveAll).toBe(true);
// PART 6 - Check that the licenses were removed.
const p = withDrm(player, manifest, (drm) => {
return Promise.all(manifest.offlineSessionIds.map(async (session) => {
const notFoundSession = await loadOfflineSession(drm, session);
expect(notFoundSession).toBeFalsy();
}));
});
const expected = Util.jasmineError(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,
shaka.util.Error.Code.OFFLINE_SESSION_REMOVED));
await expectAsync(p).toBeRejectedWith(expected);
});
});
describe('default track selection callback', () => {
const PlayerConfiguration = shaka.util.PlayerConfiguration;
it('selects the largest SD video with middle quality audio', () => {
const tracks = [
variantTrack(0, 360, englishUS, kbps(1.0)),
variantTrack(1, 480, englishUS, kbps(2.0)),
variantTrack(2, 480, englishUS, kbps(2.1)),
variantTrack(3, 480, englishUS, kbps(2.2)),
variantTrack(4, 720, englishUS, kbps(3.0)),
variantTrack(5, 1080, englishUS, kbps(4.0)),
];
const selected =
PlayerConfiguration.defaultTrackSelect(tracks, englishUS);
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe(englishUS);
expect(selected[0].height).toBe(480);
expect(selected[0].bandwidth).toBe(kbps(2.1));
});
it('selects all text tracks', () => {
const tracks = [
textTrack(0, englishUS),
textTrack(1, frenchCanadian),
];
const selected =
PlayerConfiguration.defaultTrackSelect(tracks, englishUS);
expect(selected).toBeTruthy();
expect(selected.length).toBe(2);
for (const track of tracks) {
expect(selected).toContain(track);
}
});
describe('language matching', () => {
it('finds exact match', () => {
const tracks = [
variantTrack(0, 480, 'eng-us', kbps(1)),
variantTrack(1, 480, 'fr-ca', kbps(1)),
variantTrack(2, 480, 'eng-ca', kbps(1)),
];
const selected =
PlayerConfiguration.defaultTrackSelect(tracks, 'eng-us');
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe('eng-us');
});
it('finds exact match with only base', () => {
const tracks = [
variantTrack(0, 480, 'eng-us', kbps(1)),
variantTrack(1, 480, 'fr-ca', kbps(1)),
variantTrack(2, 480, 'eng-ca', kbps(1)),
variantTrack(3, 480, 'eng', kbps(1)),
];
const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'eng');
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe('eng');
});
it('finds base match when exact match is not found', () => {
const tracks = [
variantTrack(0, 480, 'eng-us', kbps(1)),
variantTrack(1, 480, 'fr-ca', kbps(1)),
variantTrack(2, 480, 'eng-ca', kbps(1)),
];
const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'fr');
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe('fr-ca');
});
it('finds common base when exact match is not found', () => {
const tracks = [
variantTrack(0, 480, 'eng-us', kbps(1)),
variantTrack(1, 480, 'fr-ca', kbps(1)),
variantTrack(2, 480, 'eng-ca', kbps(1)),
];
const selected =
PlayerConfiguration.defaultTrackSelect(tracks, 'fr-uk');
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe('fr-ca');
});
it('finds primary track when no match is found', () => {
const tracks = [
variantTrack(0, 480, 'eng-us', kbps(1)),
variantTrack(1, 480, 'fr-ca', kbps(1)),
variantTrack(2, 480, 'eng-ca', kbps(1)),
];
tracks[0].primary = true;
const selected = PlayerConfiguration.defaultTrackSelect(tracks, 'de');
expect(selected).toBeTruthy();
expect(selected.length).toBe(1);
expect(selected[0]).toBeTruthy();
expect(selected[0].language).toBe('eng-us');
});
}); // describe('language matching')
}); // describe('default track selection callback')
describe('no support', () => {
const expectedError = Util.jasmineError(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.STORAGE_NOT_SUPPORTED));
/** @type {!shaka.Player} */
let player;
/** @type {!shaka.offline.Storage} */
let storage;
// CAUTION: Do not put overrideSupport() or clearSupport() in
// beforEach/afterEach. They change what is supported at a static level.
// When the test is run, a shim will call the support check and the test
// will be skipped if overrideSupport() has been called already. A shim of
// afterEach will call the same check and skip afterEach's body, too, and
// the clean up will never happen. So the calls to overrideSupport() and
// clearSupport() must be in each test using try/finally.
beforeEach(() => {
player = new shaka.Player();
storage = new shaka.offline.Storage(player);
// NOTE: See above "CAUTION" comment about overrideSupport/clearSupport.
});
afterEach(async () => {
await storage.destroy();
await player.destroy();
// NOTE: See above "CAUTION" comment about overrideSupport/clearSupport.
});
it('throws error using list', async () => {
try {
shaka.offline.StorageMuxer.overrideSupport(new Map());
await expectAsync(storage.list()).toBeRejectedWith(expectedError);
} finally {
shaka.offline.StorageMuxer.clearOverride();
}
});
it('throws error using store', async () => {
try {
shaka.offline.StorageMuxer.overrideSupport(new Map());
const store = storage.store('any-uri', noMetadata, fakeMimeType);
await expectAsync(store.promise).toBeRejectedWith(expectedError);
} finally {
shaka.offline.StorageMuxer.clearOverride();
}
});
it('throws error using remove', async () => {
try {
shaka.offline.StorageMuxer.overrideSupport(new Map());
const remove = storage.remove('any-uri');
await expectAsync(remove).toBeRejectedWith(expectedError);
} finally {
shaka.offline.StorageMuxer.clearOverride();
}
});
});
// Test that progress will be reported as we expect when manifests have
// stream-level bandwidth information and when manifests only have
// variant-level bandwidth information.
//
// Since we build our promise chains to allow each stream to be downloaded
// in parallel (implementation detail) progress can be non-deterministic
// as we see different promise resolution orders between browsers (and
// runs). So to control this, we force resolution order for our network
// requests in these tests.
//
// To allow us to control the network order, our manifests for these tests
// could not repeat/reuse segments uris.
describe('reports progress on store', () => {
const audioSegment1Uri = 'fake:audio-segment-1';
const audioSegment2Uri = 'fake:audio-segment-2';
const audioSegment3Uri = 'fake:audio-segment-3';
const audioSegment4Uri = 'fake:audio-segment-4';
const videoSegment1Uri = 'fake:video-segment-1';
const videoSegment2Uri = 'fake:video-segment-2';
const videoSegment3Uri = 'fake:video-segment-3';
const videoSegment4Uri = 'fake:video-segment-4';
/** @type {!shaka.offline.Storage} */
let storage;
/** @type {!Object.<string, function():!Promise.<ArrayBuffer>>} */
let fakeResponses = {};
let compiledShaka;
beforeAll(async () => {
compiledShaka =
await shaka.test.Loader.loadShaka(getClientArg('uncompiled'));
compiledShaka.net.NetworkingEngine.registerScheme(
'fake', (uri, req, type, progress) => {
if (fakeResponses[uri]) {
const operation = async () => {
const data = await fakeResponses[uri]();
return {
uri,
data,
headers: {},
};
};
return shaka.util.AbortableOperation.notAbortable(operation());
} else {
return shaka.util.AbortableOperation.failed(
new shaka.util.Error(
shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.NETWORK,
shaka.util.Error.Code.HTTP_ERROR));
}
});
});
beforeEach(async () => {
await shaka.test.TestScheme.createManifests(compiledShaka, '_compiled');
storage = new compiledShaka.offline.Storage();
// Since we are using specific manifest with only one video and one audio
// we can return all the tracks.
storage.configure({
offline: {
trackSelectionCallback: (tracks) => { return tracks; },
},
});
// Use these promises to ensure that the data from networking
// engine arrives in the correct order.
const delays = {};
delays[audioSegment1Uri] = new shaka.util.PublicPromise();
delays[audioSegment2Uri] = new shaka.util.PublicPromise();
delays[audioSegment3Uri] = new shaka.util.PublicPromise();
delays[audioSegment4Uri] = new shaka.util.PublicPromise();
delays[videoSegment1Uri] = new shaka.util.PublicPromise();
delays[videoSegment2Uri] = new shaka.util.PublicPromise();
delays[videoSegment3Uri] = new shaka.util.PublicPromise();
delays[videoSegment4Uri] = new shaka.util.PublicPromise();
/**
* Since the promise chains will be built so that each stream can be
* downloaded in parallel, we can force the network requests to
* resolve in lock-step (audio seg 0, video seg 0, audio seg 1,
* video seg 1, ...).
*
* @param {string} segment A URI
* @param {?string} dependingOn Another URI, or null
*/
function setResponseFor(segment, dependingOn) {
fakeResponses[segment] = async () => {
if (dependingOn) {
await delays[dependingOn];
}
// Tell anyone waiting on |segment| that they are clear to execute
// now.
delays[segment].resolve();
return new ArrayBuffer(16);
};
}
fakeResponses = {};
setResponseFor(audioSegment1Uri, null);
setResponseFor(audioSegment2Uri, videoSegment1Uri);
setResponseFor(audioSegment3Uri, videoSegment2Uri);
setResponseFor(audioSegment4Uri, videoSegment3Uri);
setResponseFor(videoSegment1Uri, audioSegment1Uri);
setResponseFor(videoSegment2Uri, audioSegment2Uri);
setResponseFor(videoSegment3Uri, audioSegment3Uri);
setResponseFor(videoSegment4Uri, audioSegment4Uri);
});
afterEach(async () => {
await storage.destroy();
});
afterAll(() => {
compiledShaka.net.NetworkingEngine.unregisterScheme('fake');
});
it('uses stream bandwidth', async () => {
/**
* These numbers are the overall progress based on the segment sizes
* per stream. We assume a specific download order for the content
* based on the order of the streams and segments.
*
* Since the audio stream has smaller segments, its contribution to
* the overall progress is much smaller than the video stream segments.
*
* @type {!Array.<number>}
*/
const progressSteps = [
0.057, 0.250, 0.307, 0.500, 0.557, 0.750, 0.807, 1.000,
];
const manifest = makeWithStreamBandwidth();
await runProgressTest(manifest, progressSteps);
});
it('uses variant bandwidth when stream bandwidth is unavailable',
async () => {
/**
* These numbers are the overall progress based on the segment sizes
* per stream. We assume a specific download order for the content
* based on the order of the streams and segments.
*
* Since we do not have per-stream bandwidth, the amount each
* influences the overall progress is based on the stream type,
* storage's default bandwidth assumptions, and the variant's
* bandwidth.
*
* In this example we see a larger difference between the audio and
* video contributions to progress.
*
* @type {!Array.<number>}
*/
const progressSteps = [
0.241, 0.250, 0.491, 0.500, 0.741, 0.750, 0.991, 1.000,
];
const manifest = makeWithVariantBandwidth();
await runProgressTest(manifest, progressSteps);
});
/**
* Download |manifest| and make sure that the reported progress matches
* |expectedProgressSteps|.
*
* @param {shaka.extern.Manifest} manifest
* @param {!Array.<number>} expectedProgressSteps
*/
async function runProgressTest(manifest, expectedProgressSteps) {
/**
* Create a copy of the array so that we are not modifying the original
* while we are tracking progress.
*
* @type {!Array.<number>}
*/
const remainingProgress = expectedProgressSteps.slice();
const progressCallback = (content, progress) => {
expect(progress).toBeCloseTo(remainingProgress.shift());
};
storage.configure({
offline: {
progressCallback: progressCallback,
},
});
compiledShaka.media.ManifestParser.registerParserByMime(
fakeMimeType, () => new shaka.test.FakeManifestParser(manifest));
// Store a manifest with bandwidth only for the variant (no per
// stream bandwidth). This should result in a less accurate
// progression of progress values as default values will be used.
await storage.store('uri-wont-matter', noMetadata, fakeMimeType).promise;
// We should have hit all the progress steps.
expect(remainingProgress.length).toBe(0);
}
/**
* Build a custom manifest for testing progress. Each segment will be
* unique so that there will only be one request per segment uri (we
* often reuse segments in our tests).
*
* This manifest will have the variant-level bandwidth value and per-stream
* bandwidth values.
*
* @return {shaka.extern.Manifest}
*/
function makeWithStreamBandwidth() {
const manifest = shaka.test.ManifestGenerator.generate((manifest) => {
manifest.presentationTimeline.setDuration(20);
manifest.addVariant(0, (variant) => {
variant.language = englishUS;
variant.bandwidth = kbps(13);
variant.addVideo(1, (stream) => {
stream.bandwidth = kbps(10);
stream.size(100, 200);
});
variant.addAudio(2, (stream) => {
stream.language = englishUS;
stream.bandwidth = kbps(3);
});
});
}, compiledShaka);
const audio = manifest.variants[0].audio;
goog.asserts.assert(audio, 'Created manifest with audio, where is it?');
overrideSegmentIndex(audio, [
makeReference(audioSegment1Uri, 0, 1, compiledShaka),
makeReference(audioSegment2Uri, 1, 2, compiledShaka),
makeReference(audioSegment3Uri, 2, 3, compiledShaka),
makeReference(audioSegment4Uri, 3, 4, compiledShaka),
]);
const video = manifest.variants[0].video;
goog.asserts.assert(video, 'Created manifest with video, where is it?');
overrideSegmentIndex(video, [
makeReference(videoSegment1Uri, 0, 1, compiledShaka),
makeReference(videoSegment2Uri, 1, 2, compiledShaka),
makeReference(videoSegment3Uri, 2, 3, compiledShaka),
makeReference(videoSegment4Uri, 3, 4, compiledShaka),
]);
return manifest;
}
/**
* Build a custom manifest for testing progress. Each segment will be
* unique so that there will only be one request per segment uri (we
* often reuse segments in our tests).
*
* This manifest will only have the variant-level bandwidth value.
*
* @return {shaka.extern.Manifest}
*/
function makeWithVariantBandwidth() {
// Start with the manifest that had per-stream bandwidths. Then remove
// the per-stream values.
const manifest = makeWithStreamBandwidth();
goog.asserts.assert(
manifest.variants.length == 1,
'Expecting manifest to only have one variant');
const variant = manifest.variants[0];
goog.asserts.assert(
variant.audio,
'Expecting manifest to have audio stream');
goog.asserts.assert(
variant.video,
'Expecting manigest to have video stream');
// Remove the per stream bandwidth information.
variant.audio.bandwidth = undefined;
variant.video.bandwidth = undefined;
return manifest;
}
});
describe('basic function', () => {
/**
* Keep a reference to the networking engine so that we can interrupt
* networking calls.
*
* @type {!shaka.test.FakeNetworkingEngine}
*/
let netEngine;
/** @type {!shaka.Player} */
let player;
/** @type {!shaka.offline.Storage} */
let storage;
/** @type {!shaka.util.EventManager} */
let eventManager;
/** @type {!HTMLVideoElement} */
const videoElement = /** @type {!HTMLVideoElement} */(
document.createElement('video'));
beforeEach(() => {
netEngine = makeNetworkEngine();
// Use a real Player since Storage only uses the configuration and
// networking engine. This allows us to use Player.configure in these
// tests.
player = new shaka.Player(videoElement, ((player) => {
player.createNetworkingEngine = () => netEngine;
}));
storage = new shaka.offline.Storage(player);
eventManager = new shaka.util.EventManager();
});
afterEach(async () => {
eventManager.release();
await storage.destroy();
await player.destroy();
});
it('stores and lists content', async () => {
/** @type {!Array.<string>} */
const manifestUris = [
manifestWithPerStreamBandwidthUri,
manifestWithoutPerStreamBandwidthUri,
manifestWithNonZeroStartUri,
];
// NOTE: We're working around an apparent compiler bug here, with Closure
// version v20180402. "Violation: Using properties of unknown types is
// not allowed; add an explicit type to the variable. The property "next"
// on type "Iterator<?>".
for (let i = 0; i < manifestUris.length; ++i) {
const uri = manifestUris[i];
// eslint-disable-next-line no-await-in-loop
await storage.store(uri, noMetadata, fakeMimeType).promise;
}
const content = await storage.list();
const originalUris = content.map((c) => c.originalManifestUri);
expect(originalUris.length).toBe(manifestUris.length);
// NOTE: We're working around an apparent compiler bug here. See comment
// above.
for (let i = 0; i < manifestUris.length; ++i) {
const uri = manifestUris[i];
expect(originalUris).toContain(uri);
}
});
it('snapshots config when store is called', async () => {
/** @type {!jasmine.Spy} */
const selectTracksOne =
jasmine.createSpy('selectTracksOne').and.callFake((tracks) => tracks);
/** @type {!jasmine.Spy} */
const selectTracksTwo =
jasmine.createSpy('selectTracksTwo').and.callFake((tracks) => tracks);
/** @type {!jasmine.Spy} */
const selectTracksBad =
jasmine.createSpy('selectTracksBad').and.callFake((tracks) => []);
storage.configure('offline.trackSelectionCallback', selectTracksOne);
const storeOne = storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType);
storage.configure('offline.trackSelectionCallback', selectTracksTwo);
const storeTwo = storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType);
storage.configure('offline.trackSelectionCallback', selectTracksBad);
await Promise.all([storeOne.promise, storeTwo.promise]);
expect(selectTracksOne).toHaveBeenCalled();
expect(selectTracksTwo).toHaveBeenCalled();
expect(selectTracksBad).not.toHaveBeenCalled();
});
it('only stores chosen tracks', async () => {
// Change storage to only store one track so that it will be easy
// for us to ensure that only the one track was stored.
const selectTracks = (tracks) => {
const selected = tracks.filter((t) => t.language == frenchCanadian);
expect(selected.length).toBe(1);
return selected;
};
storage.configure({
offline: {
trackSelectionCallback: selectTracks,
},
});
const stored = await storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType).promise;
goog.asserts.assert(stored.offlineUri != null, 'URI should not be null!');
expect(stored.tracks.length).toBe(1);
expect(stored.tracks[0].language).toBe(frenchCanadian);
// Pull the manifest out of storage so that we can ensure that it only
// has one variant.
/** @type {shaka.offline.OfflineUri} */
const uri = shaka.offline.OfflineUri.parse(stored.offlineUri);
/** @type {!shaka.offline.StorageMuxer} */
const muxer = new shaka.offline.StorageMuxer();
try {
await muxer.init();
const cell = await muxer.getCell(uri.mechanism(), uri.cell());
const manifests = await cell.getManifests([uri.key()]);
expect(manifests.length).toBe(1);
const manifest = manifests[0];
// There should be 2 streams, an audio and a video stream.
expect(manifest.streams.length).toBe(2);
const audio = manifest.streams.filter(
(s) => s.type == 'audio')[0];
expect(audio.language).toBe(frenchCanadian);
} finally {
await muxer.destroy();
}
});
it('can choose tracks asynchronously', async () => {
storage.configure({
offline: {
trackSelectionCallback: async (tracks) => {
await Util.delay(0.1);
const selected = tracks.filter((t) => t.language == frenchCanadian);
expect(selected.length).toBe(1);
return selected;
},
},
});
const stored = await storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType).promise;
expect(stored.tracks.length).toBe(1);
expect(stored.tracks[0].language).toBe(frenchCanadian);
});
it('stores drm info without license', async () => {
const drmInfo = makeDrmInfo();
const session1 = 'session-1';
const session2 = 'session-2';
const expiration = 1000;
// TODO(vaage): Is there a way we can set the session ids without needing
// to overload an internal call in storage.
const drm = new shaka.test.FakeDrmEngine();
drm.setDrmInfo(drmInfo);
drm.setSessionIds([session1, session2]);
drm.getExpiration.and.returnValue(expiration);
overrideDrmAndManifest(
storage,
drm,
makeManifestWithPerStreamBandwidth());
const stored = await storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType).promise;
goog.asserts.assert(stored.offlineUri != null, 'URI should not be null!');
/** @type {shaka.offline.OfflineUri} */
const uri = shaka.offline.OfflineUri.parse(stored.offlineUri);
expect(uri).toBeTruthy();
/** @type {!shaka.offline.StorageMuxer} */
const muxer = new shaka.offline.StorageMuxer();
try {
await muxer.init();
const cell = await muxer.getCell(uri.mechanism(), uri.cell());
const manifests = await cell.getManifests([uri.key()]);
const manifest = manifests[0];
expect(manifest).toBeTruthy();
expect(manifest.drmInfo).toEqual(drmInfo);
expect(manifest.expiration).toBe(expiration);
expect(manifest.sessionIds).toBeTruthy();
expect(manifest.sessionIds.length).toBe(2);
expect(manifest.sessionIds).toContain(session1);
expect(manifest.sessionIds).toContain(session2);
} finally {
await muxer.destroy();
}
});
it('can extract DRM info from segments', async () => {
const pssh1 =
'00000028' + // atom size
'70737368' + // atom type='pssh'
'00000000' + // v0, flags=0
'edef8ba979d64acea3c827dcd51d21ed' + // system id (Widevine)
'00000008' + // data size
'0102030405060708'; // data
const psshData1 = shaka.util.Uint8ArrayUtils.fromHex(pssh1);
const pssh2 =
'00000028' + // atom size
'70737368' + // atom type='pssh'
'00000000' + // v0, flags=0
'edef8ba979d64acea3c827dcd51d21ed' + // system id (Widevine)
'00000008' + // data size
'1337420123456789'; // data
const psshData2 = shaka.util.Uint8ArrayUtils.fromHex(pssh2);
netEngine.setResponseValue(initSegmentUri,
shaka.util.BufferUtils.toArrayBuffer(psshData1));
netEngine.setResponseValue(alternateInitSegmentUri,
shaka.util.BufferUtils.toArrayBuffer(psshData2));
const drm = new shaka.test.FakeDrmEngine();
const drmInfo = makeDrmInfo();
drmInfo.keySystem = 'com.widevine.alpha';
drm.setDrmInfo(drmInfo);
overrideDrmAndManifest(
storage,
drm,
makeManifestWithVideoInitSegments());
const stored = await storage.store(
manifestWithVideoInitSegmentsUri, noMetadata, fakeMimeType).promise;
goog.asserts.assert(stored.offlineUri != null, 'URI should not be null!');
// The manifest chooses the alternate stream, so expect only the alt init
// segment.
expect(drm.newInitData).toHaveBeenCalledWith('cenc', psshData2);
});
it('can store multiple assets at once', async () => {
// Block the network so that we won't finish the first store command.
/** @type {!shaka.util.PublicPromise} */
const hangingPromise = netEngine.delayNextRequest();
/** @type {!shaka.extern.IAbortableOperation} */
const storeOperation = storage.store(
manifestWithPerStreamBandwidthUri, noMetadata, fakeMimeType);