forked from shaka-project/shaka-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
1651 lines (1445 loc) · 54.4 KB
/
storage.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.provide('shaka.offline.Storage');
goog.require('goog.asserts');
goog.require('shaka.Player');
goog.require('shaka.log');
goog.require('shaka.media.DrmEngine');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.offline.DownloadInfo');
goog.require('shaka.offline.DownloadManager');
goog.require('shaka.offline.OfflineUri');
goog.require('shaka.offline.SessionDeleter');
goog.require('shaka.offline.StorageMuxer');
goog.require('shaka.offline.StoredContentUtils');
goog.require('shaka.offline.StreamBandwidthEstimator');
goog.require('shaka.util.AbortableOperation');
goog.require('shaka.util.ArrayUtils');
goog.require('shaka.util.ConfigUtils');
goog.require('shaka.util.Destroyer');
goog.require('shaka.util.Error');
goog.require('shaka.util.IDestroyable');
goog.require('shaka.util.Iterables');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.Platform');
goog.require('shaka.util.PlayerConfiguration');
goog.require('shaka.util.StreamUtils');
goog.requireType('shaka.media.SegmentReference');
goog.requireType('shaka.offline.StorageCellHandle');
/**
* @summary
* This manages persistent offline data including storage, listing, and deleting
* stored manifests. Playback of offline manifests are done through the Player
* using a special URI (see shaka.offline.OfflineUri).
*
* First, check support() to see if offline is supported by the platform.
* Second, configure() the storage object with callbacks to your application.
* Third, call store(), remove(), or list() as needed.
* When done, call destroy().
*
* @implements {shaka.util.IDestroyable}
* @export
*/
shaka.offline.Storage = class {
/**
* @param {!shaka.Player=} player
* A player instance to share a networking engine and configuration with.
* When initializing with a player, storage is only valid as long as
* |destroy| has not been called on the player instance. When omitted,
* storage will manage its own networking engine and configuration.
*/
constructor(player) {
// It is an easy mistake to make to pass a Player proxy from CastProxy.
// Rather than throw a vague exception later, throw an explicit and clear
// one now.
//
// TODO(vaage): After we decide whether or not we want to support
// initializing storage with a player proxy, we should either remove
// this error or rename the error.
if (player && player.constructor != shaka.Player) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.LOCAL_PLAYER_INSTANCE_REQUIRED);
}
/** @private {?shaka.extern.PlayerConfiguration} */
this.config_ = null;
/** @private {shaka.net.NetworkingEngine} */
this.networkingEngine_ = null;
// Initialize |config_| and |networkingEngine_| based on whether or not
// we were given a player instance.
if (player) {
this.config_ = player.getSharedConfiguration();
this.networkingEngine_ = player.getNetworkingEngine();
goog.asserts.assert(
this.networkingEngine_,
'Storage should not be initialized with a player that had ' +
'|destroy| called on it.');
} else {
this.config_ = shaka.util.PlayerConfiguration.createDefault();
this.networkingEngine_ = new shaka.net.NetworkingEngine();
}
/**
* A list of open operations that are being performed by this instance of
* |shaka.offline.Storage|.
*
* @private {!Array.<!Promise>}
*/
this.openOperations_ = [];
/**
* A list of open download managers that are being used to download things.
*
* @private {!Array.<!shaka.offline.DownloadManager>}
*/
this.openDownloadManagers_ = [];
/**
* Storage should only destroy the networking engine if it was initialized
* without a player instance. Store this as a flag here to avoid including
* the player object in the destoyer's closure.
*
* @type {boolean}
*/
const destroyNetworkingEngine = !player;
/** @private {!shaka.util.Destroyer} */
this.destroyer_ = new shaka.util.Destroyer(async () => {
// Cancel all in-progress store operations.
await Promise.all(this.openDownloadManagers_.map((dl) => dl.abortAll()));
// Wait for all remaining open operations to end. Wrap each operations so
// that a single rejected promise won't cause |Promise.all| to return
// early or to return a rejected Promise.
const noop = () => {};
const awaits = [];
for (const op of this.openOperations_) {
awaits.push(op.then(noop, noop));
}
await Promise.all(awaits);
// Wait until after all the operations have finished before we destroy
// the networking engine to avoid any unexpected errors.
if (destroyNetworkingEngine) {
await this.networkingEngine_.destroy();
}
// Drop all references to internal objects to help with GC.
this.config_ = null;
this.networkingEngine_ = null;
});
}
/**
* Gets whether offline storage is supported. Returns true if offline storage
* is supported for clear content. Support for offline storage of encrypted
* content will not be determined until storage is attempted.
*
* @return {boolean}
* @export
*/
static support() {
// Our Storage system is useless without MediaSource. MediaSource allows us
// to pull data from anywhere (including our Storage system) and feed it to
// the video element.
if (!shaka.util.Platform.supportsMediaSource()) {
return false;
}
return shaka.offline.StorageMuxer.support();
}
/**
* @override
* @export
*/
destroy() {
return this.destroyer_.destroy();
}
/**
* Sets configuration values for Storage. This is associated with
* Player.configure and will change the player instance given at
* initialization.
*
* @param {string|!Object} config This should either be a field name or an
* object following the form of {@link shaka.extern.PlayerConfiguration},
* where you may omit any field you do not wish to change.
* @param {*=} value This should be provided if the previous parameter
* was a string field name.
* @return {boolean}
* @export
*/
configure(config, value) {
goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
'String configs should have values!');
// ('fieldName', value) format
if (arguments.length == 2 && typeof(config) == 'string') {
config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
}
goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
goog.asserts.assert(
this.config_, 'Cannot reconfigure storage after calling destroy.');
return shaka.util.PlayerConfiguration.mergeConfigObjects(
/* destination= */ this.config_, /* updates= */ config );
}
/**
* Return a copy of the current configuration. Modifications of the returned
* value will not affect the Storage instance's active configuration. You
* must call storage.configure() to make changes.
*
* @return {shaka.extern.PlayerConfiguration}
* @export
*/
getConfiguration() {
goog.asserts.assert(this.config_, 'Config must not be null!');
const ret = shaka.util.PlayerConfiguration.createDefault();
shaka.util.PlayerConfiguration.mergeConfigObjects(
ret, this.config_, shaka.util.PlayerConfiguration.createDefault());
return ret;
}
/**
* Return the networking engine that storage is using. If storage was
* initialized with a player instance, then the networking engine returned
* will be the same as |player.getNetworkingEngine()|.
*
* The returned value will only be null if |destroy| was called before
* |getNetworkingEngine|.
*
* @return {shaka.net.NetworkingEngine}
* @export
*/
getNetworkingEngine() {
return this.networkingEngine_;
}
/**
* Stores the given manifest. If the content is encrypted, and encrypted
* content cannot be stored on this platform, the Promise will be rejected
* with error code 6001, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE.
* Multiple assets can be downloaded at the same time, but note that since
* the storage instance has a single networking engine, multiple storage
* objects will be necessary if some assets require unique network filters.
* This snapshots the storage config at the time of the call, so it will not
* honor any changes to config mid-store operation.
*
* @param {string} uri The URI of the manifest to store.
* @param {!Object=} appMetadata An arbitrary object from the application
* that will be stored along-side the offline content. Use this for any
* application-specific metadata you need associated with the stored
* content. For details on the data types that can be stored here, please
* refer to {@link https://bit.ly/StructClone}
* @param {string=} mimeType
* The mime type for the content |manifestUri| points to.
* @return {!shaka.extern.IAbortableOperation.<shaka.extern.StoredContent>}
* An AbortableOperation that resolves with a structure representing what
* was stored. The "offlineUri" member is the URI that should be given to
* Player.load() to play this piece of content offline. The "appMetadata"
* member is the appMetadata argument you passed to store().
* If you want to cancel this download, call the "abort" method on
* AbortableOperation.
* @export
*/
store(uri, appMetadata, mimeType) {
goog.asserts.assert(
this.networkingEngine_,
'Cannot call |store| after calling |destroy|.');
// Get a copy of the current config.
const config = this.getConfiguration();
const getParser = async () => {
goog.asserts.assert(
this.networkingEngine_, 'Should not call |store| after |destroy|');
const factory = await shaka.media.ManifestParser.getFactory(
uri,
this.networkingEngine_,
config.manifest.retryParameters,
mimeType || null);
return factory();
};
/** @type {!shaka.offline.DownloadManager} */
const downloader =
new shaka.offline.DownloadManager(this.networkingEngine_);
this.openDownloadManagers_.push(downloader);
const storeOp = this.store_(
uri, appMetadata || {}, getParser, config, downloader);
const abortableStoreOp = new shaka.util.AbortableOperation(storeOp, () => {
return downloader.abortAll();
});
abortableStoreOp.finally(() => {
shaka.util.ArrayUtils.remove(this.openDownloadManagers_, downloader);
});
return this.startAbortableOperation_(abortableStoreOp);
}
/**
* See |shaka.offline.Storage.store| for details.
*
* @param {string} uri
* @param {!Object} appMetadata
* @param {function():!Promise.<shaka.extern.ManifestParser>} getParser
* @param {shaka.extern.PlayerConfiguration} config
* @param {!shaka.offline.DownloadManager} downloader
* @return {!Promise.<shaka.extern.StoredContent>}
* @private
*/
async store_(uri, appMetadata, getParser, config, downloader) {
this.requireSupport_();
// Since we will need to use |parser|, |drmEngine|, |activeHandle|, and
// |muxer| in the catch/finally blocks, we need to define them out here.
// Since they may not get initialized when we enter the catch/finally block,
// we need to assume that they may be null/undefined when we get there.
/** @type {?shaka.extern.ManifestParser} */
let parser = null;
/** @type {?shaka.media.DrmEngine} */
let drmEngine = null;
/** @type {shaka.offline.StorageMuxer} */
const muxer = new shaka.offline.StorageMuxer();
/** @type {?shaka.offline.StorageCellHandle} */
let activeHandle = null;
/** @type {?number} */
let manifestId = null;
// This will be used to store any errors from drm engine. Whenever drm
// engine is passed to another function to do work, we should check if this
// was set.
let drmError = null;
try {
parser = await getParser();
const manifest = await this.parseManifest(uri, parser, config);
// Check if we were asked to destroy ourselves while we were "away"
// downloading the manifest.
this.ensureNotDestroyed_();
// Check if we can even download this type of manifest before trying to
// create the drm engine.
const canDownload = !manifest.presentationTimeline.isLive() &&
!manifest.presentationTimeline.isInProgress();
if (!canDownload) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE,
uri);
}
// Create the DRM engine, and load the keys in the manifest.
drmEngine = await this.createDrmEngine(
manifest,
(e) => { drmError = drmError || e; },
config);
// We could have been asked to destroy ourselves while we were "away"
// creating the drm engine.
this.ensureNotDestroyed_();
if (drmError) {
throw drmError;
}
await this.filterManifest_(manifest, drmEngine, config);
await muxer.init();
this.ensureNotDestroyed_();
// Get the cell that we are saving the manifest to. Once we get a cell
// we will only reference the cell and not the muxer so that the manifest
// and segments will all be saved to the same cell.
activeHandle = await muxer.getActive();
this.ensureNotDestroyed_();
goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
const {manifestDB, toDownload} = this.makeManifestDB_(
drmEngine, manifest, uri, appMetadata, config, downloader);
// Store the empty manifest, before downloading the segments.
const ids = await activeHandle.cell.addManifests([manifestDB]);
this.ensureNotDestroyed_();
manifestId = ids[0];
goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
this.ensureNotDestroyed_();
if (drmError) {
throw drmError;
}
await this.downloadSegments_(toDownload, manifestId, manifestDB,
downloader, config, activeHandle.cell, manifest, drmEngine);
this.ensureNotDestroyed_();
const offlineUri = shaka.offline.OfflineUri.manifest(
activeHandle.path.mechanism, activeHandle.path.cell, manifestId);
return shaka.offline.StoredContentUtils.fromManifestDB(
offlineUri, manifestDB);
} catch (e) {
if (manifestId != null) {
await shaka.offline.Storage.cleanStoredManifest(manifestId);
}
// If we already had an error, ignore this error to avoid hiding
// the original error.
throw drmError || e;
} finally {
await muxer.destroy();
if (parser) {
await parser.stop();
}
if (drmEngine) {
await drmEngine.destroy();
}
}
}
/**
* Download and then store the contents of each segment.
* The promise this returns will wait for local downloads.
*
* @param {!Array.<!shaka.offline.DownloadInfo>} toDownload
* @param {number} manifestId
* @param {shaka.extern.ManifestDB} manifestDB
* @param {!shaka.offline.DownloadManager} downloader
* @param {shaka.extern.PlayerConfiguration} config
* @param {shaka.extern.StorageCell} storage
* @param {shaka.extern.Manifest} manifest
* @param {!shaka.media.DrmEngine} drmEngine
* @return {!Promise}
* @private
*/
async downloadSegments_(
toDownload, manifestId, manifestDB, downloader, config, storage,
manifest, drmEngine) {
let pendingManifestUpdates = {};
let pendingDataSize = 0;
/**
* @param {!Array.<!shaka.offline.DownloadInfo>} toDownload
* @param {boolean} updateDRM
*/
const download = async (toDownload, updateDRM) => {
for (const download of toDownload) {
const request = download.makeSegmentRequest(config);
const estimateId = download.estimateId;
const isInitSegment = download.isInitSegment;
const onDownloaded = async (data) => {
// Store the data.
const dataKeys = await storage.addSegments([{data}]);
this.ensureNotDestroyed_();
// Store the necessary update to the manifest, to be processed later.
const ref = /** @type {!shaka.media.SegmentReference} */ (
download.ref);
const id = shaka.offline.DownloadInfo.idForSegmentRef(ref);
pendingManifestUpdates[id] = dataKeys[0];
pendingDataSize += data.byteLength;
};
downloader.queue(download.groupId,
request, estimateId, isInitSegment, onDownloaded);
}
await downloader.waitToFinish();
if (updateDRM) {
// Re-store the manifest, to attach session IDs.
// These were (maybe) discovered inside the downloader; we can only add
// them now, at the end, since the manifestDB is in flux during the
// process of downloading and storing, and assignSegmentsToManifest
// does not know about the DRM engine.
this.ensureNotDestroyed_();
this.setManifestDrmFields_(manifest, manifestDB, drmEngine, config);
await storage.updateManifest(manifestId, manifestDB);
}
};
const usingBgFetch = false; // TODO: Get.
try {
if (this.getManifestIsEncrypted_(manifest) && usingBgFetch &&
!this.getManifestIncludesInitData_(manifest)) {
// Background fetch can't make DRM sessions, so if we have to get the
// init data from the init segments, download those first before
// anything else.
await download(toDownload.filter((info) => info.isInitSegment), true);
this.ensureNotDestroyed_();
toDownload = toDownload.filter((info) => !info.isInitSegment);
// Copy these and reset them now, before calling await.
const manifestUpdates = pendingManifestUpdates;
const dataSize = pendingDataSize;
pendingManifestUpdates = {};
pendingDataSize = 0;
await shaka.offline.Storage.assignSegmentsToManifest(
storage, manifestId, manifestDB, manifestUpdates, dataSize,
() => this.ensureNotDestroyed_());
this.ensureNotDestroyed_();
}
if (!usingBgFetch) {
await download(toDownload, false);
this.ensureNotDestroyed_();
// Copy these and reset them now, before calling await.
const manifestUpdates = pendingManifestUpdates;
const dataSize = pendingDataSize;
pendingManifestUpdates = {};
pendingDataSize = 0;
await shaka.offline.Storage.assignSegmentsToManifest(
storage, manifestId, manifestDB, manifestUpdates, dataSize,
() => this.ensureNotDestroyed_());
this.ensureNotDestroyed_();
goog.asserts.assert(
!manifestDB.isIncomplete, 'The manifest should be complete by now');
} else {
// TODO: Send the request to the service worker. Don't await the result.
}
} catch (error) {
const dataKeys = Object.values(pendingManifestUpdates);
// Remove these pending segments that are not yet linked to the manifest.
await storage.removeSegments(dataKeys, (key) => {});
throw error;
}
}
/**
* Removes all of the contents for a given manifest, statelessly.
*
* @param {number} manifestId
* @return {!Promise}
*/
static async cleanStoredManifest(manifestId) {
const muxer = new shaka.offline.StorageMuxer();
await muxer.init();
const activeHandle = await muxer.getActive();
const uri = shaka.offline.OfflineUri.manifest(
activeHandle.path.mechanism,
activeHandle.path.cell,
manifestId);
await muxer.destroy();
const storage = new shaka.offline.Storage();
await storage.remove(uri.toString());
}
/**
* Updates the given manifest, assigns database keys to segments, then stores
* the updated manifest.
*
* It is up to the caller to ensure that this method is not called
* concurrently on the same manifest.
*
* @param {shaka.extern.StorageCell} storage
* @param {number} manifestId
* @param {!shaka.extern.ManifestDB} manifestDB
* @param {!Object.<string, number>} manifestUpdates
* @param {number} dataSizeUpdate
* @param {function()} throwIfAbortedFn A function that should throw if the
* download has been aborted.
* @return {!Promise}
*/
static async assignSegmentsToManifest(
storage, manifestId, manifestDB, manifestUpdates, dataSizeUpdate,
throwIfAbortedFn) {
let manifestUpdated = false;
try {
// Assign the stored data to the manifest.
let complete = true;
for (const stream of manifestDB.streams) {
for (const segment of stream.segments) {
let dataKey = segment.pendingSegmentRefId ?
manifestUpdates[segment.pendingSegmentRefId] : null;
if (dataKey != null) {
segment.dataKey = dataKey;
// Now that the segment has been associated with the appropriate
// dataKey, the pendingSegmentRefId is no longer necessary.
segment.pendingSegmentRefId = undefined;
}
dataKey = segment.pendingInitSegmentRefId ?
manifestUpdates[segment.pendingInitSegmentRefId] : null;
if (dataKey != null) {
segment.initSegmentKey = dataKey;
// Now that the init segment has been associated with the
// appropriate initSegmentKey, the pendingInitSegmentRefId is no
// longer necessary.
segment.pendingInitSegmentRefId = undefined;
}
if (segment.pendingSegmentRefId) {
complete = false;
}
if (segment.pendingInitSegmentRefId) {
complete = false;
}
}
}
// Update the size of the manifest.
manifestDB.size += dataSizeUpdate;
// Mark the manifest as complete, if all segments are downloaded.
if (complete) {
manifestDB.isIncomplete = false;
}
// Update the manifest.
await storage.updateManifest(manifestId, manifestDB);
manifestUpdated = true;
throwIfAbortedFn();
} catch (e) {
await shaka.offline.Storage.cleanStoredManifest(manifestId);
if (!manifestUpdated) {
const dataKeys = Object.values(manifestUpdates);
// The cleanStoredManifest method will not "see" any segments that have
// been downloaded but not assigned to the manifest yet. So un-store
// them separately.
await storage.removeSegments(dataKeys, (key) => {});
}
throw e;
}
}
/**
* Filter |manifest| such that it will only contain the variants and text
* streams that we want to store and can actually play.
*
* @param {shaka.extern.Manifest} manifest
* @param {!shaka.media.DrmEngine} drmEngine
* @param {shaka.extern.PlayerConfiguration} config
* @return {!Promise}
* @private
*/
async filterManifest_(manifest, drmEngine, config) {
// Filter the manifest based on the restrictions given in the player
// configuration.
const maxHwRes = {width: Infinity, height: Infinity};
shaka.util.StreamUtils.filterByRestrictions(
manifest, config.restrictions, maxHwRes);
// Filter the manifest based on what we know MediaCapabilities will be able
// to play later (no point storing something we can't play).
await shaka.util.StreamUtils.filterManifestByMediaCapabilities(
manifest, config.offline.usePersistentLicense);
// Gather all tracks.
const allTracks = [];
// Choose the codec that has the lowest average bandwidth.
const preferredAudioChannelCount = config.preferredAudioChannelCount;
const preferredDecodingAttributes = config.preferredDecodingAttributes;
const preferredVideoCodecs = config.preferredVideoCodecs;
const preferredAudioCodecs = config.preferredAudioCodecs;
shaka.util.StreamUtils.chooseCodecsAndFilterManifest(
manifest, preferredVideoCodecs, preferredAudioCodecs,
preferredAudioChannelCount, preferredDecodingAttributes);
for (const variant of manifest.variants) {
goog.asserts.assert(
shaka.util.StreamUtils.isPlayable(variant),
'We should have already filtered by "is playable"');
allTracks.push(shaka.util.StreamUtils.variantToTrack(variant));
}
for (const text of manifest.textStreams) {
allTracks.push(shaka.util.StreamUtils.textStreamToTrack(text));
}
for (const image of manifest.imageStreams) {
allTracks.push(shaka.util.StreamUtils.imageStreamToTrack(image));
}
// Let the application choose which tracks to store.
const chosenTracks =
await config.offline.trackSelectionCallback(allTracks);
const duration = manifest.presentationTimeline.getDuration();
let sizeEstimate = 0;
for (const track of chosenTracks) {
const trackSize = track.bandwidth * duration / 8;
sizeEstimate += trackSize;
}
try {
const allowedDownload =
await config.offline.downloadSizeCallback(sizeEstimate);
if (!allowedDownload) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.STORAGE_LIMIT_REACHED);
}
} catch (e) {
// It is necessary to be able to catch the STORAGE_LIMIT_REACHED error
if (e instanceof shaka.util.Error) {
throw e;
}
shaka.log.warning(
'downloadSizeCallback has produced an unexpected error', e);
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.DOWNLOAD_SIZE_CALLBACK_ERROR);
}
/** @type {!Set.<number>} */
const variantIds = new Set();
/** @type {!Set.<number>} */
const textIds = new Set();
/** @type {!Set.<number>} */
const imageIds = new Set();
// Collect the IDs of the chosen tracks.
for (const track of chosenTracks) {
if (track.type == 'variant') {
variantIds.add(track.id);
}
if (track.type == 'text') {
textIds.add(track.id);
}
if (track.type == 'image') {
imageIds.add(track.id);
}
}
// Filter the manifest to keep only what the app chose.
manifest.variants =
manifest.variants.filter((variant) => variantIds.has(variant.id));
manifest.textStreams =
manifest.textStreams.filter((stream) => textIds.has(stream.id));
manifest.imageStreams =
manifest.imageStreams.filter((stream) => imageIds.has(stream.id));
// Check the post-filtered manifest for characteristics that may indicate
// issues with how the app selected tracks.
shaka.offline.Storage.validateManifest_(manifest);
}
/**
* Create a download manager and download the manifest.
* This also sets up download infos for each segment to be downloaded.
*
* @param {!shaka.media.DrmEngine} drmEngine
* @param {shaka.extern.Manifest} manifest
* @param {string} uri
* @param {!Object} metadata
* @param {shaka.extern.PlayerConfiguration} config
* @param {!shaka.offline.DownloadManager} downloader
* @return {{
* manifestDB: shaka.extern.ManifestDB,
* toDownload: !Array.<!shaka.offline.DownloadInfo>
* }}
* @private
*/
makeManifestDB_(drmEngine, manifest, uri, metadata, config, downloader) {
const pendingContent = shaka.offline.StoredContentUtils.fromManifest(
uri, manifest, /* size= */ 0, metadata);
// In https://github.com/shaka-project/shaka-player/issues/2652, we found
// that this callback would be removed by the compiler if we reference the
// config in the onProgress closure below. Reading it into a local
// variable first seems to work around this apparent compiler bug.
const progressCallback = config.offline.progressCallback;
const onProgress = (progress, size) => {
// Update the size of the stored content before issuing a progress
// update.
pendingContent.size = size;
progressCallback(pendingContent, progress);
};
const onInitData = (initData, systemId) => {
if (needsInitData && config.offline.usePersistentLicense &&
currentSystemId == systemId) {
drmEngine.newInitData('cenc', initData);
}
};
downloader.setCallbacks(onProgress, onInitData);
const needsInitData = this.getManifestIsEncrypted_(manifest) &&
!this.getManifestIncludesInitData_(manifest);
let currentSystemId = null;
if (needsInitData) {
const drmInfo = drmEngine.getDrmInfo();
currentSystemId =
shaka.offline.Storage.defaultSystemIds_.get(drmInfo.keySystem);
}
// Make the estimator, which is used to make the download registries.
const estimator = new shaka.offline.StreamBandwidthEstimator();
for (const stream of manifest.textStreams) {
estimator.addText(stream);
}
for (const stream of manifest.imageStreams) {
estimator.addImage(stream);
}
for (const variant of manifest.variants) {
estimator.addVariant(variant);
}
const {streams, toDownload} = this.createStreams_(
downloader, estimator, drmEngine, manifest, config);
const drmInfo = drmEngine.getDrmInfo();
const usePersistentLicense = config.offline.usePersistentLicense;
if (drmInfo && usePersistentLicense) {
// Don't store init data, since we have stored sessions.
drmInfo.initData = [];
}
const manifestDB = {
creationTime: Date.now(),
originalManifestUri: uri,
duration: manifest.presentationTimeline.getDuration(),
size: 0,
expiration: drmEngine.getExpiration(),
streams,
sessionIds: usePersistentLicense ? drmEngine.getSessionIds() : [],
drmInfo,
appMetadata: metadata,
isIncomplete: true,
sequenceMode: manifest.sequenceMode,
type: manifest.type,
};
return {manifestDB, toDownload};
}
/**
* @param {shaka.extern.Manifest} manifest
* @return {boolean}
* @private
*/
getManifestIsEncrypted_(manifest) {
return manifest.variants.some((variant) => {
const videoEncrypted = variant.video && variant.video.encrypted;
const audioEncrypted = variant.audio && variant.audio.encrypted;
return videoEncrypted || audioEncrypted;
});
}
/**
* @param {shaka.extern.Manifest} manifest
* @return {boolean}
* @private
*/
getManifestIncludesInitData_(manifest) {
return manifest.variants.some((variant) => {
const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
const drmInfos = videoDrmInfos.concat(audioDrmInfos);
return drmInfos.some((drmInfos) => {
return drmInfos.initData && drmInfos.initData.length;
});
});
}
/**
* @param {shaka.extern.Manifest} manifest
* @param {shaka.extern.ManifestDB} manifestDB
* @param {!shaka.media.DrmEngine} drmEngine
* @param {shaka.extern.PlayerConfiguration} config
* @private
*/
setManifestDrmFields_(manifest, manifestDB, drmEngine, config) {
manifestDB.expiration = drmEngine.getExpiration();
const sessions = drmEngine.getSessionIds();
manifestDB.sessionIds = config.offline.usePersistentLicense ?
sessions : [];
if (this.getManifestIsEncrypted_(manifest) &&
config.offline.usePersistentLicense && !sessions.length) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
}
}
/**
* Removes the given stored content. This will also attempt to release the
* licenses, if any.
*
* @param {string} contentUri
* @return {!Promise}
* @export
*/
remove(contentUri) {
return this.startOperation_(this.remove_(contentUri));
}
/**
* See |shaka.offline.Storage.remove| for details.
*
* @param {string} contentUri
* @return {!Promise}
* @private
*/
async remove_(contentUri) {
this.requireSupport_();
const nullableUri = shaka.offline.OfflineUri.parse(contentUri);
if (nullableUri == null || !nullableUri.isManifest()) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
contentUri);
}
/** @type {!shaka.offline.OfflineUri} */
const uri = nullableUri;
/** @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];
await Promise.all([
this.removeFromDRM_(uri, manifest, muxer),
this.removeFromStorage_(cell, uri, manifest),
]);
} finally {
await muxer.destroy();
}
}
/**
* @param {shaka.extern.ManifestDB} manifestDb
* @param {boolean} isVideo
* @return {!Array.<MediaKeySystemMediaCapability>}
* @private
*/
static getCapabilities_(manifestDb, isVideo) {
const MimeUtils = shaka.util.MimeUtils;
const ret = [];
for (const stream of manifestDb.streams) {
if (isVideo && stream.type == 'video') {
ret.push({
contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
robustness: manifestDb.drmInfo.videoRobustness,
});
} else if (!isVideo && stream.type == 'audio') {
ret.push({
contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
robustness: manifestDb.drmInfo.audioRobustness,
});
}
}
return ret;
}
/**
* @param {!shaka.offline.OfflineUri} uri
* @param {shaka.extern.ManifestDB} manifestDb
* @param {!shaka.offline.StorageMuxer} muxer
* @return {!Promise}
* @private
*/
async removeFromDRM_(uri, manifestDb, muxer) {
goog.asserts.assert(this.networkingEngine_, 'Cannot be destroyed');
await shaka.offline.Storage.deleteLicenseFor_(
this.networkingEngine_, this.config_.drm, muxer, manifestDb);
}
/**
* @param {shaka.extern.StorageCell} storage
* @param {!shaka.offline.OfflineUri} uri
* @param {shaka.extern.ManifestDB} manifest
* @return {!Promise}
* @private
*/
removeFromStorage_(storage, uri, manifest) {
/** @type {!Array.<number>} */
const segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest);
// Count(segments) + Count(manifests)
const toRemove = segmentIds.length + 1;
let removed = 0;