shaka-player 3.2.2 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +1 -1
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +1 -1
  3. package/.github/ISSUE_TEMPLATE/question.md +1 -1
  4. package/AUTHORS +6 -5
  5. package/CHANGELOG.md +247 -0
  6. package/CONTRIBUTORS +4 -2
  7. package/build/types/core +3 -0
  8. package/build/types/offline +1 -0
  9. package/build/types/polyfill +1 -0
  10. package/build/types/ui +2 -0
  11. package/demo/common/assets.js +18 -0
  12. package/demo/common/message_ids.js +13 -1
  13. package/demo/config.js +31 -1
  14. package/demo/index.html +1 -1
  15. package/demo/locales/en.json +12 -0
  16. package/demo/locales/source.json +48 -0
  17. package/dist/controls.css +26 -2
  18. package/dist/controls.css.map +1 -1
  19. package/dist/demo.compiled.debug.js +19 -16
  20. package/dist/demo.compiled.debug.map +3 -3
  21. package/dist/demo.compiled.js +19 -16
  22. package/dist/demo.compiled.map +3 -3
  23. package/dist/deps.js +18 -11
  24. package/dist/locales.js +28 -26
  25. package/dist/receiver.compiled.debug.js +11 -9
  26. package/dist/receiver.compiled.debug.map +3 -3
  27. package/dist/receiver.compiled.js +11 -9
  28. package/dist/receiver.compiled.map +3 -3
  29. package/dist/shaka-player.compiled.d.ts +205 -15
  30. package/dist/shaka-player.compiled.debug.d.ts +205 -15
  31. package/dist/shaka-player.compiled.debug.externs.js +256 -6
  32. package/dist/shaka-player.compiled.debug.js +406 -354
  33. package/dist/shaka-player.compiled.debug.map +4 -4
  34. package/dist/shaka-player.compiled.externs.js +256 -6
  35. package/dist/shaka-player.compiled.js +826 -800
  36. package/dist/shaka-player.compiled.map +4 -4
  37. package/dist/shaka-player.ui.d.ts +221 -16
  38. package/dist/shaka-player.ui.debug.d.ts +221 -16
  39. package/dist/shaka-player.ui.debug.externs.js +283 -6
  40. package/dist/shaka-player.ui.debug.js +547 -476
  41. package/dist/shaka-player.ui.debug.map +4 -4
  42. package/dist/shaka-player.ui.externs.js +283 -6
  43. package/dist/shaka-player.ui.js +1019 -980
  44. package/dist/shaka-player.ui.map +4 -4
  45. package/docs/design/bg-fetch-after.gv +29 -0
  46. package/docs/design/bg-fetch-after.gv.png +0 -0
  47. package/docs/design/bg-fetch-before.gv +18 -0
  48. package/docs/design/bg-fetch-before.gv.png +0 -0
  49. package/docs/design/bg-fetch.md +134 -0
  50. package/docs/tutorials/blob-url.md +15 -0
  51. package/docs/tutorials/index.json +1 -0
  52. package/docs/tutorials/ui-customization.md +66 -0
  53. package/docs/tutorials/ui.md +5 -5
  54. package/externs/ima.js +3 -0
  55. package/externs/shaka/ads.js +5 -0
  56. package/externs/shaka/manifest.js +12 -1
  57. package/externs/shaka/manifest_parser.js +10 -1
  58. package/externs/shaka/net.js +20 -4
  59. package/externs/shaka/offline.js +31 -2
  60. package/externs/shaka/player.js +130 -5
  61. package/externs/shaka/text.js +14 -0
  62. package/externs/webcrypto.js +18 -0
  63. package/lib/abr/ewma.js +14 -0
  64. package/lib/abr/ewma_bandwidth_estimator.js +16 -2
  65. package/lib/abr/simple_abr_manager.js +6 -0
  66. package/lib/ads/client_side_ad.js +8 -0
  67. package/lib/ads/client_side_ad_manager.js +8 -4
  68. package/lib/ads/server_side_ad.js +7 -0
  69. package/lib/cast/cast_utils.js +1 -0
  70. package/lib/dash/dash_parser.js +48 -14
  71. package/lib/dash/segment_base.js +25 -1
  72. package/lib/dash/segment_list.js +18 -9
  73. package/lib/dash/segment_template.js +23 -10
  74. package/lib/hls/hls_parser.js +86 -23
  75. package/lib/media/quality_observer.js +291 -0
  76. package/lib/media/segment_index.js +6 -0
  77. package/lib/media/segment_reference.js +18 -3
  78. package/lib/media/streaming_engine.js +42 -4
  79. package/lib/net/http_fetch_plugin.js +31 -11
  80. package/lib/net/http_plugin_utils.js +1 -0
  81. package/lib/net/http_xhr_plugin.js +40 -14
  82. package/lib/net/networking_engine.js +81 -18
  83. package/lib/offline/download_info.js +68 -0
  84. package/lib/offline/download_manager.js +13 -5
  85. package/lib/offline/indexeddb/base_storage_cell.js +35 -0
  86. package/lib/offline/indexeddb/storage_mechanism.js +1 -1
  87. package/lib/offline/indexeddb/v5_storage_cell.js +5 -0
  88. package/lib/offline/storage.js +393 -284
  89. package/lib/offline/stored_content_utils.js +2 -0
  90. package/lib/player.js +206 -7
  91. package/lib/polyfill/random_uuid.js +52 -0
  92. package/lib/text/cue.js +12 -0
  93. package/lib/text/ttml_text_parser.js +25 -2
  94. package/lib/text/ui_text_displayer.js +2 -2
  95. package/lib/util/cmcd_manager.js +826 -0
  96. package/lib/util/error.js +6 -0
  97. package/lib/util/language_utils.js +12 -0
  98. package/lib/util/mutex.js +52 -0
  99. package/lib/util/periods.js +98 -64
  100. package/lib/util/player_configuration.js +18 -0
  101. package/package.json +1 -1
  102. package/shaka-player.uncompiled.js +3 -0
  103. package/test/dash/dash_parser_content_protection_unit.js +2 -0
  104. package/test/dash/dash_parser_live_unit.js +101 -1
  105. package/test/dash/dash_parser_manifest_unit.js +35 -1
  106. package/test/dash/dash_parser_segment_base_unit.js +2 -0
  107. package/test/dash/dash_parser_segment_list_unit.js +2 -1
  108. package/test/dash/dash_parser_segment_template_unit.js +2 -1
  109. package/test/hls/hls_live_unit.js +2 -0
  110. package/test/hls/hls_parser_unit.js +2 -0
  111. package/test/media/quality_observer_unit.js +139 -0
  112. package/test/media/segment_reference_unit.js +16 -1
  113. package/test/media/streaming_engine_integration.js +2 -1
  114. package/test/media/streaming_engine_unit.js +2 -0
  115. package/test/net/http_plugin_unit.js +20 -15
  116. package/test/offline/storage_integration.js +108 -4
  117. package/test/player_integration.js +99 -0
  118. package/test/test/util/dash_parser_util.js +4 -0
  119. package/test/test/util/fake_ad.js +7 -0
  120. package/test/test/util/fake_drm_engine.js +9 -2
  121. package/test/test/util/manifest_generator.js +3 -2
  122. package/test/test/util/test_scheme.js +14 -1
  123. package/test/text/ttml_text_parser_unit.js +47 -0
  124. package/test/ui/ui_unit.js +250 -0
  125. package/test/util/cmcd_manager_unit.js +277 -0
  126. package/ui/airplay_button.js +1 -0
  127. package/ui/audio_language_selection.js +7 -0
  128. package/ui/cast_button.js +1 -0
  129. package/ui/context_menu.js +109 -0
  130. package/ui/controls.js +41 -7
  131. package/ui/controls.less +1 -0
  132. package/ui/enums.js +4 -0
  133. package/ui/externs/ui.js +28 -1
  134. package/ui/fast_forward_button.js +14 -5
  135. package/ui/fullscreen_button.js +1 -0
  136. package/ui/less/buttons.less +0 -4
  137. package/ui/less/containers.less +74 -0
  138. package/ui/less/overflow_menu.less +0 -10
  139. package/ui/less/tooltip.less +97 -0
  140. package/ui/locales/en.json +1 -0
  141. package/ui/locales/source.json +4 -0
  142. package/ui/loop_button.js +5 -0
  143. package/ui/mute_button.js +2 -1
  144. package/ui/overflow_menu.js +5 -25
  145. package/ui/pip_button.js +5 -0
  146. package/ui/play_button.js +2 -2
  147. package/ui/playback_rate_selection.js +8 -9
  148. package/ui/resolution_selection.js +7 -0
  149. package/ui/rewind_button.js +15 -6
  150. package/ui/seek_bar.js +4 -2
  151. package/ui/settings_menu.js +36 -4
  152. package/ui/small_play_button.js +1 -0
  153. package/ui/statistics_button.js +253 -0
  154. package/ui/text_selection.js +11 -4
  155. package/ui/ui.js +30 -0
  156. package/ui/volume_bar.js +1 -1
@@ -13,6 +13,7 @@ goog.require('shaka.log');
13
13
  goog.require('shaka.media.DrmEngine');
14
14
  goog.require('shaka.media.ManifestParser');
15
15
  goog.require('shaka.net.NetworkingEngine');
16
+ goog.require('shaka.offline.DownloadInfo');
16
17
  goog.require('shaka.offline.DownloadManager');
17
18
  goog.require('shaka.offline.OfflineUri');
18
19
  goog.require('shaka.offline.SessionDeleter');
@@ -28,11 +29,10 @@ goog.require('shaka.util.Functional');
28
29
  goog.require('shaka.util.IDestroyable');
29
30
  goog.require('shaka.util.Iterables');
30
31
  goog.require('shaka.util.MimeUtils');
31
- goog.require('shaka.util.Networking');
32
+ goog.require('shaka.util.Mutex');
32
33
  goog.require('shaka.util.Platform');
33
34
  goog.require('shaka.util.PlayerConfiguration');
34
35
  goog.require('shaka.util.StreamUtils');
35
- goog.requireType('shaka.media.InitSegmentReference');
36
36
  goog.requireType('shaka.media.SegmentReference');
37
37
  goog.requireType('shaka.offline.StorageCellHandle');
38
38
 
@@ -95,14 +95,6 @@ shaka.offline.Storage = class {
95
95
  this.networkingEngine_ = new shaka.net.NetworkingEngine();
96
96
  }
97
97
 
98
- /**
99
- * A list of segment ids for all the segments that were added during the
100
- * current store. If the store fails or is aborted, these need to be
101
- * removed from storage.
102
- * @private {!Array.<number>}
103
- */
104
- this.segmentsFromStore_ = [];
105
-
106
98
  /**
107
99
  * A list of open operations that are being performed by this instance of
108
100
  * |shaka.offline.Storage|.
@@ -285,7 +277,7 @@ shaka.offline.Storage = class {
285
277
  store(uri, appMetadata, mimeType) {
286
278
  goog.asserts.assert(
287
279
  this.networkingEngine_,
288
- 'Cannot call |downloadManifest_| after calling |destroy|.');
280
+ 'Cannot call |store| after calling |destroy|.');
289
281
 
290
282
  // Get a copy of the current config.
291
283
  const config = this.getConfiguration();
@@ -371,6 +363,8 @@ shaka.offline.Storage = class {
371
363
  const muxer = new shaka.offline.StorageMuxer();
372
364
  /** @type {?shaka.offline.StorageCellHandle} */
373
365
  let activeHandle = null;
366
+ /** @type {?number} */
367
+ let manifestId = null;
374
368
 
375
369
  // This will be used to store any errors from drm engine. Whenever drm
376
370
  // engine is passed to another function to do work, we should check if this
@@ -398,6 +392,7 @@ shaka.offline.Storage = class {
398
392
  uri);
399
393
  }
400
394
 
395
+ // Create the DRM engine, and load the keys in the manifest.
401
396
  drmEngine = await this.createDrmEngine(
402
397
  manifest,
403
398
  (e) => { drmError = drmError || e; },
@@ -422,38 +417,38 @@ shaka.offline.Storage = class {
422
417
  this.ensureNotDestroyed_();
423
418
 
424
419
  goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
420
+ const {manifestDB, toDownload} = this.makeManifestDB_(
421
+ drmEngine, manifest, uri, appMetadata, config, downloader);
425
422
 
426
- const manifestDB = await this.downloadManifest_(
427
- activeHandle.cell, drmEngine, manifest, uri, appMetadata, config,
428
- downloader);
423
+ // Store the empty manifest, before downloading the segments.
424
+ const ids = await activeHandle.cell.addManifests([manifestDB]);
425
+ this.ensureNotDestroyed_();
426
+ manifestId = ids[0];
427
+
428
+ goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
429
429
  this.ensureNotDestroyed_();
430
430
  if (drmError) {
431
431
  throw drmError;
432
432
  }
433
433
 
434
- const ids = await activeHandle.cell.addManifests([manifestDB]);
434
+ await this.downloadSegments_(toDownload, manifestId, manifestDB,
435
+ downloader, config, activeHandle.cell, manifest, drmEngine);
435
436
  this.ensureNotDestroyed_();
436
437
 
437
438
  const offlineUri = shaka.offline.OfflineUri.manifest(
438
- activeHandle.path.mechanism, activeHandle.path.cell, ids[0]);
439
+ activeHandle.path.mechanism, activeHandle.path.cell, manifestId);
439
440
 
440
441
  return shaka.offline.StoredContentUtils.fromManifestDB(
441
442
  offlineUri, manifestDB);
442
443
  } catch (e) {
443
- // If we did start saving some data, we need to remove it all to avoid
444
- // wasting storage. However if the muxer did not manage to initialize,
445
- // then we won't have an active cell to remove the segments from.
446
- if (activeHandle) {
447
- await activeHandle.cell.removeSegments(
448
- this.segmentsFromStore_, () => {});
444
+ if (manifestId != null) {
445
+ await shaka.offline.Storage.cleanStoredManifest(manifestId);
449
446
  }
450
447
 
451
448
  // If we already had an error, ignore this error to avoid hiding
452
449
  // the original error.
453
450
  throw drmError || e;
454
451
  } finally {
455
- this.segmentsFromStore_ = [];
456
-
457
452
  await muxer.destroy();
458
453
 
459
454
  if (parser) {
@@ -466,6 +461,215 @@ shaka.offline.Storage = class {
466
461
  }
467
462
  }
468
463
 
464
+ /**
465
+ * Download and then store the contents of each segment.
466
+ * The promise this returns will wait for local downloads.
467
+ *
468
+ * @param {!Array.<!shaka.offline.DownloadInfo>} toDownload
469
+ * @param {number} manifestId
470
+ * @param {shaka.extern.ManifestDB} manifestDB
471
+ * @param {!shaka.offline.DownloadManager} downloader
472
+ * @param {shaka.extern.PlayerConfiguration} config
473
+ * @param {shaka.extern.StorageCell} storage
474
+ * @param {shaka.extern.Manifest} manifest
475
+ * @param {!shaka.media.DrmEngine} drmEngine
476
+ * @return {!Promise}
477
+ * @private
478
+ */
479
+ async downloadSegments_(
480
+ toDownload, manifestId, manifestDB, downloader, config, storage,
481
+ manifest, drmEngine) {
482
+ /**
483
+ * @param {!Array.<!shaka.offline.DownloadInfo>} toDownload
484
+ * @param {boolean} updateDRM
485
+ */
486
+ const download = async (toDownload, updateDRM) => {
487
+ const throwIfAbortedFn = () => {
488
+ this.ensureNotDestroyed_();
489
+ };
490
+ for (const download of toDownload) {
491
+ /** @param {?BufferSource} data */
492
+ let data;
493
+ const request = download.makeSegmentRequest(config);
494
+ const estimateId = download.estimateId;
495
+ const isInitSegment = download.isInitSegment;
496
+ const onDownloaded = (d) => {
497
+ data = d;
498
+ return Promise.resolve();
499
+ };
500
+ downloader.queue(download.groupId,
501
+ request, estimateId, isInitSegment, onDownloaded);
502
+ downloader.queueWork(download.groupId, async () => {
503
+ goog.asserts.assert(data, 'We should have loaded data by now');
504
+ goog.asserts.assert(data instanceof ArrayBuffer,
505
+ 'The data should be an ArrayBuffer');
506
+
507
+ const ref = /** @type {!shaka.media.SegmentReference} */ (
508
+ download.ref);
509
+ manifestDB = (await shaka.offline.Storage.assignStreamToManifest(
510
+ manifestId, ref, {data}, throwIfAbortedFn)) || manifestDB;
511
+ });
512
+ }
513
+ await downloader.waitToFinish();
514
+
515
+ if (updateDRM) {
516
+ // Re-store the manifest, to attach session IDs.
517
+ // These were (maybe) discovered inside the downloader; we can only add
518
+ // them now, at the end, since the manifestDB is in flux during the
519
+ // process of downloading and storing, and assignStreamToManifest does
520
+ // not know about the DRM engine.
521
+ this.ensureNotDestroyed_();
522
+ this.setManifestDrmFields_(manifest, manifestDB, drmEngine, config);
523
+ await storage.updateManifest(manifestId, manifestDB);
524
+ }
525
+ };
526
+
527
+ const usingBgFetch = false; // TODO: Get.
528
+
529
+ if (this.getManifestIsEncrypted_(manifest) && usingBgFetch &&
530
+ !this.getManifestIncludesInitData_(manifest)) {
531
+ // Background fetch can't make DRM sessions, so if we have to get the
532
+ // init data from the init segments, download those first before anything
533
+ // else.
534
+ await download(toDownload.filter((info) => info.isInitSegment), true);
535
+ this.ensureNotDestroyed_();
536
+ toDownload = toDownload.filter((info) => !info.isInitSegment);
537
+ }
538
+
539
+ if (!usingBgFetch) {
540
+ await download(toDownload, false);
541
+ this.ensureNotDestroyed_();
542
+
543
+ goog.asserts.assert(
544
+ !manifestDB.isIncomplete, 'The manifest should be complete by now');
545
+ } else {
546
+ // TODO: Send the request to the service worker. Don't await the result.
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Removes all of the contents for a given manifest, statelessly.
552
+ *
553
+ * @param {number} manifestId
554
+ * @return {!Promise}
555
+ */
556
+ static async cleanStoredManifest(manifestId) {
557
+ const muxer = new shaka.offline.StorageMuxer();
558
+ await muxer.init();
559
+ const activeHandle = await muxer.getActive();
560
+ const uri = shaka.offline.OfflineUri.manifest(
561
+ activeHandle.path.mechanism,
562
+ activeHandle.path.cell,
563
+ manifestId);
564
+ await muxer.destroy();
565
+ const storage = new shaka.offline.Storage();
566
+ await storage.remove(uri.toString());
567
+ }
568
+
569
+ /**
570
+ * Load the given manifest, modifies it by assigning the given data to the
571
+ * segments corresponding to "ref", then re-stores the manifest.
572
+ * The parts of this function that modify the manifest are protected by a
573
+ * mutex, to prevent race conditions; specifically, it prevents two parallel
574
+ * instances of this method from both loading the manifest into memory at the
575
+ * same time, which would result in the slower/later call overwriting the
576
+ * changes of the other.
577
+ *
578
+ * @param {number} manifestId
579
+ * @param {!shaka.media.SegmentReference} ref
580
+ * @param {shaka.extern.SegmentDataDB} data
581
+ * @param {function()} throwIfAbortedFn A function that should throw if the
582
+ * download has been aborted.
583
+ * @return {!Promise.<?shaka.extern.ManifestDB>}
584
+ */
585
+ static async assignStreamToManifest(manifestId, ref, data, throwIfAbortedFn) {
586
+ /** @type {shaka.offline.StorageMuxer} */
587
+ const muxer = new shaka.offline.StorageMuxer();
588
+
589
+ const idForRef = shaka.offline.DownloadInfo.idForSegmentRef(ref);
590
+ let manifestUpdated = false;
591
+ let dataKey;
592
+ let activeHandle;
593
+ /** @type {!shaka.extern.ManifestDB} */
594
+ let manifestDB;
595
+
596
+ let mutexId = 0;
597
+
598
+ try {
599
+ await muxer.init();
600
+ activeHandle = await muxer.getActive();
601
+
602
+ // Store the data.
603
+ const dataKeys = await activeHandle.cell.addSegments([data]);
604
+ dataKey = dataKeys[0];
605
+ throwIfAbortedFn();
606
+
607
+ // Acquire the mutex before accessing the manifest, since there could be
608
+ // multiple instances of this method running at once.
609
+ mutexId = await shaka.offline.Storage.mutex_.acquire();
610
+ throwIfAbortedFn();
611
+
612
+ // Load the manifest.
613
+ const manifests = await activeHandle.cell.getManifests([manifestId]);
614
+ throwIfAbortedFn();
615
+ manifestDB = manifests[0];
616
+
617
+ // Assign the stored data to the manifest.
618
+ let complete = true;
619
+ for (const stream of manifestDB.streams) {
620
+ for (const segment of stream.segments) {
621
+ if (segment.pendingSegmentRefId == idForRef) {
622
+ segment.dataKey = dataKey;
623
+ // Now that the segment has been associated with the appropriate
624
+ // dataKey, the pendingSegmentRefId is no longer necessary.
625
+ segment.pendingSegmentRefId = undefined;
626
+ }
627
+ if (segment.pendingInitSegmentRefId == idForRef) {
628
+ segment.initSegmentKey = dataKey;
629
+ // Now that the init segment has been associated with the
630
+ // appropriate initSegmentKey, the pendingInitSegmentRefId is no
631
+ // longer necessary.
632
+ segment.pendingInitSegmentRefId = undefined;
633
+ }
634
+ if (segment.pendingSegmentRefId) {
635
+ complete = false;
636
+ }
637
+ if (segment.pendingInitSegmentRefId) {
638
+ complete = false;
639
+ }
640
+ }
641
+ }
642
+
643
+ // Update the size of the manifest.
644
+ manifestDB.size += data.data.byteLength;
645
+
646
+ // Mark the manifest as complete, if all segments are downloaded.
647
+ if (complete) {
648
+ manifestDB.isIncomplete = false;
649
+ }
650
+
651
+ // Re-store the manifest.
652
+ await activeHandle.cell.updateManifest(manifestId, manifestDB);
653
+ manifestUpdated = true;
654
+ throwIfAbortedFn();
655
+ } catch (e) {
656
+ await shaka.offline.Storage.cleanStoredManifest(manifestId);
657
+
658
+ if (activeHandle && !manifestUpdated && dataKey) {
659
+ // The cleanStoredManifest method will not "see" any segments that have
660
+ // been downloaded but not assigned to the manifest yet. So un-store
661
+ // them separately.
662
+ await activeHandle.cell.removeSegments([dataKey], (key) => {});
663
+ }
664
+
665
+ throw e;
666
+ } finally {
667
+ await muxer.destroy();
668
+ shaka.offline.Storage.mutex_.release(mutexId);
669
+ }
670
+ return manifestDB;
671
+ }
672
+
469
673
  /**
470
674
  * Filter |manifest| such that it will only contain the variants and text
471
675
  * streams that we want to store and can actually play.
@@ -584,19 +788,21 @@ shaka.offline.Storage = class {
584
788
 
585
789
  /**
586
790
  * Create a download manager and download the manifest.
791
+ * This also sets up download infos for each segment to be downloaded.
587
792
  *
588
- * @param {shaka.extern.StorageCell} storage
589
793
  * @param {!shaka.media.DrmEngine} drmEngine
590
794
  * @param {shaka.extern.Manifest} manifest
591
795
  * @param {string} uri
592
796
  * @param {!Object} metadata
593
797
  * @param {shaka.extern.PlayerConfiguration} config
594
798
  * @param {!shaka.offline.DownloadManager} downloader
595
- * @return {!Promise.<shaka.extern.ManifestDB>}
799
+ * @return {{
800
+ * manifestDB: shaka.extern.ManifestDB,
801
+ * toDownload: !Array.<!shaka.offline.DownloadInfo>
802
+ * }}
596
803
  * @private
597
804
  */
598
- async downloadManifest_(
599
- storage, drmEngine, manifest, uri, metadata, config, downloader) {
805
+ makeManifestDB_(drmEngine, manifest, uri, metadata, config, downloader) {
600
806
  const pendingContent = shaka.offline.StoredContentUtils.fromManifest(
601
807
  uri, manifest, /* size= */ 0, metadata);
602
808
  // In https://github.com/google/shaka-player/issues/2652, we found that this
@@ -619,12 +825,73 @@ shaka.offline.Storage = class {
619
825
  };
620
826
  downloader.setCallbacks(onProgress, onInitData);
621
827
 
622
- const isEncrypted = manifest.variants.some((variant) => {
828
+ const needsInitData = this.getManifestIsEncrypted_(manifest) &&
829
+ !this.getManifestIncludesInitData_(manifest);
830
+
831
+ let currentSystemId = null;
832
+ if (needsInitData) {
833
+ const drmInfo = drmEngine.getDrmInfo();
834
+ currentSystemId =
835
+ shaka.offline.Storage.defaultSystemIds_.get(drmInfo.keySystem);
836
+ }
837
+
838
+ // Make the estimator, which is used to make the download registries.
839
+ const estimator = new shaka.offline.StreamBandwidthEstimator();
840
+ for (const stream of manifest.textStreams) {
841
+ estimator.addText(stream);
842
+ }
843
+ for (const stream of manifest.imageStreams) {
844
+ estimator.addImage(stream);
845
+ }
846
+ for (const variant of manifest.variants) {
847
+ estimator.addVariant(variant);
848
+ }
849
+ const {streams, toDownload} = this.createStreams_(
850
+ downloader, estimator, drmEngine, manifest, config);
851
+
852
+ const drmInfo = drmEngine.getDrmInfo();
853
+ const usePersistentLicense = config.offline.usePersistentLicense;
854
+ if (drmInfo && usePersistentLicense) {
855
+ // Don't store init data, since we have stored sessions.
856
+ drmInfo.initData = [];
857
+ }
858
+
859
+ const manifestDB = {
860
+ creationTime: Date.now(),
861
+ originalManifestUri: uri,
862
+ duration: manifest.presentationTimeline.getDuration(),
863
+ size: 0,
864
+ expiration: drmEngine.getExpiration(),
865
+ streams,
866
+ sessionIds: usePersistentLicense ? drmEngine.getSessionIds() : [],
867
+ drmInfo,
868
+ appMetadata: metadata,
869
+ isIncomplete: true,
870
+ };
871
+
872
+ return {manifestDB, toDownload};
873
+ }
874
+
875
+ /**
876
+ * @param {shaka.extern.Manifest} manifest
877
+ * @return {boolean}
878
+ * @private
879
+ */
880
+ getManifestIsEncrypted_(manifest) {
881
+ return manifest.variants.some((variant) => {
623
882
  const videoEncrypted = variant.video && variant.video.encrypted;
624
883
  const audioEncrypted = variant.audio && variant.audio.encrypted;
625
884
  return videoEncrypted || audioEncrypted;
626
885
  });
627
- const includesInitData = manifest.variants.some((variant) => {
886
+ }
887
+
888
+ /**
889
+ * @param {shaka.extern.Manifest} manifest
890
+ * @return {boolean}
891
+ * @private
892
+ */
893
+ getManifestIncludesInitData_(manifest) {
894
+ return manifest.variants.some((variant) => {
628
895
  const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
629
896
  const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
630
897
  const drmInfos = videoDrmInfos.concat(audioDrmInfos);
@@ -632,36 +899,28 @@ shaka.offline.Storage = class {
632
899
  return drmInfos.initData && drmInfos.initData.length;
633
900
  });
634
901
  });
635
- const needsInitData = isEncrypted && !includesInitData;
636
-
637
- let currentSystemId = null;
638
- if (needsInitData) {
639
- const drmInfo = drmEngine.getDrmInfo();
640
- currentSystemId =
641
- shaka.offline.Storage.defaultSystemIds_.get(drmInfo.keySystem);
642
- }
643
-
644
- try {
645
- const manifestDB = this.createOfflineManifest_(
646
- downloader, storage, drmEngine, manifest, uri, metadata, config);
902
+ }
647
903
 
648
- manifestDB.size = await downloader.waitToFinish();
649
- manifestDB.expiration = drmEngine.getExpiration();
650
- const sessions = drmEngine.getSessionIds();
651
- manifestDB.sessionIds = config.offline.usePersistentLicense ?
652
- sessions : [];
904
+ /**
905
+ * @param {shaka.extern.Manifest} manifest
906
+ * @param {shaka.extern.ManifestDB} manifestDB
907
+ * @param {!shaka.media.DrmEngine} drmEngine
908
+ * @param {shaka.extern.PlayerConfiguration} config
909
+ * @private
910
+ */
911
+ setManifestDrmFields_(manifest, manifestDB, drmEngine, config) {
912
+ manifestDB.expiration = drmEngine.getExpiration();
653
913
 
654
- if (isEncrypted && config.offline.usePersistentLicense &&
655
- !sessions.length) {
656
- throw new shaka.util.Error(
657
- shaka.util.Error.Severity.CRITICAL,
658
- shaka.util.Error.Category.STORAGE,
659
- shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
660
- }
914
+ const sessions = drmEngine.getSessionIds();
915
+ manifestDB.sessionIds = config.offline.usePersistentLicense ?
916
+ sessions : [];
661
917
 
662
- return manifestDB;
663
- } finally {
664
- await downloader.destroy();
918
+ if (this.getManifestIsEncrypted_(manifest) &&
919
+ config.offline.usePersistentLicense && !sessions.length) {
920
+ throw new shaka.util.Error(
921
+ shaka.util.Error.Severity.CRITICAL,
922
+ shaka.util.Error.Category.STORAGE,
923
+ shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
665
924
  }
666
925
  }
667
926
 
@@ -764,7 +1023,7 @@ shaka.offline.Storage = class {
764
1023
  * @return {!Promise}
765
1024
  * @private
766
1025
  */
767
- removeFromStorage_( storage, uri, manifest) {
1026
+ removeFromStorage_(storage, uri, manifest) {
768
1027
  /** @type {!Array.<number>} */
769
1028
  const segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest);
770
1029
 
@@ -921,6 +1180,10 @@ shaka.offline.Storage = class {
921
1180
  const playerInterface = {
922
1181
  networkingEngine: networkingEngine,
923
1182
 
1183
+ // No need to apply CMCD data for offline requests
1184
+ modifyManifestRequest: (request, manifestInfo) => {},
1185
+ modifySegmentRequest: (request, segmentInfo) => {},
1186
+
924
1187
  // Don't bother filtering now. We will do that later when we have all the
925
1188
  // information we need to filter.
926
1189
  filter: () => Promise.resolve(),
@@ -1007,100 +1270,23 @@ shaka.offline.Storage = class {
1007
1270
  }
1008
1271
 
1009
1272
  /**
1010
- * Creates an offline 'manifest' for the real manifest. This does not store
1011
- * the segments yet, only adds them to the download manager through
1012
- * createStreams_.
1273
+ * Converts manifest Streams to database Streams.
1013
1274
  *
1014
1275
  * @param {!shaka.offline.DownloadManager} downloader
1015
- * @param {shaka.extern.StorageCell} storage
1016
- * @param {!shaka.media.DrmEngine} drmEngine
1017
- * @param {shaka.extern.Manifest} manifest
1018
- * @param {string} originalManifestUri
1019
- * @param {!Object} metadata
1020
- * @param {shaka.extern.PlayerConfiguration} config
1021
- * @return {shaka.extern.ManifestDB}
1022
- * @private
1023
- */
1024
- createOfflineManifest_(
1025
- downloader, storage, drmEngine, manifest, originalManifestUri, metadata,
1026
- config) {
1027
- const estimator = new shaka.offline.StreamBandwidthEstimator();
1028
-
1029
- const streams = this.createStreams_(
1030
- downloader, storage, estimator, drmEngine, manifest, config);
1031
-
1032
- const usePersistentLicense = config.offline.usePersistentLicense;
1033
- const drmInfo = drmEngine.getDrmInfo();
1034
-
1035
- if (drmInfo && usePersistentLicense) {
1036
- // Don't store init data, since we have stored sessions.
1037
- drmInfo.initData = [];
1038
- }
1039
-
1040
- return {
1041
- creationTime: Date.now(),
1042
- originalManifestUri: originalManifestUri,
1043
- duration: manifest.presentationTimeline.getDuration(),
1044
- size: 0,
1045
- expiration: drmEngine.getExpiration(),
1046
- streams: streams,
1047
- sessionIds: usePersistentLicense ? drmEngine.getSessionIds() : [],
1048
- drmInfo: drmInfo,
1049
- appMetadata: metadata,
1050
- };
1051
- }
1052
-
1053
- /**
1054
- * Converts manifest Streams to database Streams. This will use the current
1055
- * configuration to get the tracks to use, then it will search each segment
1056
- * index and add all the segments to the download manager through
1057
- * createStream_.
1058
- *
1059
- * @param {!shaka.offline.DownloadManager} downloader
1060
- * @param {shaka.extern.StorageCell} storage
1061
1276
  * @param {shaka.offline.StreamBandwidthEstimator} estimator
1062
1277
  * @param {!shaka.media.DrmEngine} drmEngine
1063
1278
  * @param {shaka.extern.Manifest} manifest
1064
1279
  * @param {shaka.extern.PlayerConfiguration} config
1065
- * @return {!Array.<shaka.extern.StreamDB>}
1280
+ * @return {{
1281
+ * streams: !Array.<shaka.extern.StreamDB>,
1282
+ * toDownload: !Array.<!shaka.offline.DownloadInfo>
1283
+ * }}
1066
1284
  * @private
1067
1285
  */
1068
- createStreams_(downloader, storage, estimator, drmEngine, manifest, config) {
1069
- // Pass all variants and text streams to the estimator so that we can
1070
- // get the best estimate for each stream later.
1071
- for (const variant of manifest.variants) {
1072
- estimator.addVariant(variant);
1073
- }
1074
- for (const text of manifest.textStreams) {
1075
- estimator.addText(text);
1076
- }
1077
- for (const image of manifest.imageStreams) {
1078
- estimator.addImage(image);
1079
- }
1080
-
1081
- // TODO(joeyparrish): Break out stack-based state and method params into a
1082
- // separate class to clean up. See:
1083
- // https://github.com/google/shaka-player/issues/2781#issuecomment-678438039
1084
-
1085
- /**
1086
- * A cache mapping init segment references to Promises to their DB key.
1087
- *
1088
- * @type {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
1089
- */
1090
- const initSegmentDbKeyCache = new Map();
1091
-
1092
- // A null init segment reference always maps to a null DB key.
1093
- initSegmentDbKeyCache.set(
1094
- null, /** @type {!Promise.<?number>} */(Promise.resolve(null)));
1095
-
1096
- /**
1097
- * A cache mapping equivalent segment references to Promises to their DB
1098
- * key. The key in this map is a string of the form
1099
- * "<URI>-<startByte>-<endByte>".
1100
- *
1101
- * @type {!Map.<string, !Promise.<number>>}
1102
- */
1103
- const segmentDbKeyCache = new Map();
1286
+ createStreams_(downloader, estimator, drmEngine, manifest, config) {
1287
+ // Download infos are stored based on their refId, to dedup them.
1288
+ /** @type {!Map.<string, !shaka.offline.DownloadInfo>} */
1289
+ const toDownload = new Map();
1104
1290
 
1105
1291
  // Find the streams we want to download and create a stream db instance
1106
1292
  // for each of them.
@@ -1110,8 +1296,7 @@ shaka.offline.Storage = class {
1110
1296
 
1111
1297
  for (const stream of streamSet) {
1112
1298
  const streamDB = this.createStream_(
1113
- downloader, storage, estimator, manifest, stream, config,
1114
- initSegmentDbKeyCache, segmentDbKeyCache);
1299
+ downloader, estimator, manifest, stream, config, toDownload);
1115
1300
  streamDBs.set(stream.id, streamDB);
1116
1301
  }
1117
1302
 
@@ -1125,27 +1310,26 @@ shaka.offline.Storage = class {
1125
1310
  }
1126
1311
  }
1127
1312
 
1128
- return Array.from(streamDBs.values());
1313
+ return {
1314
+ streams: Array.from(streamDBs.values()),
1315
+ toDownload: Array.from(toDownload.values()),
1316
+ };
1129
1317
  }
1130
1318
 
1131
1319
  /**
1132
1320
  * Converts a manifest stream to a database stream. This will search the
1133
- * segment index and add all the segments to the download manager.
1321
+ * segment index and add all the segments to the download infos.
1134
1322
  *
1135
1323
  * @param {!shaka.offline.DownloadManager} downloader
1136
- * @param {shaka.extern.StorageCell} storage
1137
1324
  * @param {shaka.offline.StreamBandwidthEstimator} estimator
1138
1325
  * @param {shaka.extern.Manifest} manifest
1139
1326
  * @param {shaka.extern.Stream} stream
1140
1327
  * @param {shaka.extern.PlayerConfiguration} config
1141
- * @param {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
1142
- * initSegmentDbKeyCache
1143
- * @param {!Map.<string, !Promise.<number>>} segmentDbKeyCache
1328
+ * @param {!Map.<string, !shaka.offline.DownloadInfo>} toDownload
1144
1329
  * @return {shaka.extern.StreamDB}
1145
1330
  * @private
1146
1331
  */
1147
- createStream_(downloader, storage, estimator, manifest, stream, config,
1148
- initSegmentDbKeyCache, segmentDbKeyCache) {
1332
+ createStream_(downloader, estimator, manifest, stream, config, toDownload) {
1149
1333
  /** @type {shaka.extern.StreamDB} */
1150
1334
  const streamDb = {
1151
1335
  id: stream.id,
@@ -1175,138 +1359,60 @@ shaka.offline.Storage = class {
1175
1359
  tilesLayout: stream.tilesLayout,
1176
1360
  };
1177
1361
 
1178
- // Download each stream in parallel.
1179
- const downloadGroup = stream.id;
1180
-
1181
1362
  const startTime =
1182
1363
  manifest.presentationTimeline.getSegmentAvailabilityStart();
1183
1364
 
1184
1365
  shaka.offline.Storage.forEachSegment_(stream, startTime, (segment) => {
1185
- const initSegmentKeyPromise = this.getInitSegmentDbKey_(
1186
- downloader, downloadGroup, stream.id, storage, estimator,
1187
- segment.initSegmentReference, config, initSegmentDbKeyCache);
1188
-
1189
- const segmentKeyPromise = this.getSegmentDbKey_(
1190
- downloader, downloadGroup, stream.id, storage, estimator, segment,
1191
- config, segmentDbKeyCache);
1192
-
1193
- downloader.queueWork(downloadGroup, async () => {
1194
- const initSegmentKey = await initSegmentKeyPromise;
1195
- const dataKey = await segmentKeyPromise;
1196
-
1197
- streamDb.segments.push({
1198
- initSegmentKey,
1199
- startTime: segment.startTime,
1200
- endTime: segment.endTime,
1201
- appendWindowStart: segment.appendWindowStart,
1202
- appendWindowEnd: segment.appendWindowEnd,
1203
- timestampOffset: segment.timestampOffset,
1204
- tilesLayout: segment.tilesLayout,
1205
- dataKey,
1206
- });
1207
- });
1208
- });
1209
-
1210
- return streamDb;
1211
- }
1212
-
1213
- /**
1214
- * Get a Promise to the DB key for a given init segment reference.
1215
- *
1216
- * The return values will be cached so that multiple calls with the same init
1217
- * segment reference will only trigger one request.
1218
- *
1219
- * @param {!shaka.offline.DownloadManager} downloader
1220
- * @param {number} downloadGroup
1221
- * @param {number} streamId
1222
- * @param {shaka.extern.StorageCell} storage
1223
- * @param {shaka.offline.StreamBandwidthEstimator} estimator
1224
- * @param {shaka.media.InitSegmentReference} initSegmentReference
1225
- * @param {shaka.extern.PlayerConfiguration} config
1226
- * @param {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
1227
- * initSegmentDbKeyCache
1228
- * @return {!Promise.<?number>}
1229
- * @private
1230
- */
1231
- getInitSegmentDbKey_(
1232
- downloader, downloadGroup, streamId, storage, estimator,
1233
- initSegmentReference, config, initSegmentDbKeyCache) {
1234
- if (initSegmentDbKeyCache.has(initSegmentReference)) {
1235
- return initSegmentDbKeyCache.get(initSegmentReference);
1236
- }
1237
-
1238
- const request = shaka.util.Networking.createSegmentRequest(
1239
- initSegmentReference.getUris(),
1240
- initSegmentReference.startByte,
1241
- initSegmentReference.endByte,
1242
- config.streaming.retryParameters);
1243
-
1244
- const promise = downloader.queue(
1245
- downloadGroup,
1246
- request,
1247
- estimator.getInitSegmentEstimate(streamId),
1248
- /* isInitSegment= */ true,
1249
- async (data) => {
1250
- /** @type {!Array.<number>} */
1251
- const ids = await storage.addSegments([{data: data}]);
1252
- this.segmentsFromStore_.push(ids[0]);
1253
- return ids[0];
1254
- });
1255
-
1256
- initSegmentDbKeyCache.set(initSegmentReference, promise);
1257
- return promise;
1258
- }
1366
+ const pendingSegmentRefId =
1367
+ shaka.offline.DownloadInfo.idForSegmentRef(segment);
1368
+ let pendingInitSegmentRefId = undefined;
1369
+
1370
+ // Set up the download for the segment, which will be downloaded later,
1371
+ // perhaps in a service worker.
1372
+ if (!toDownload.has(pendingSegmentRefId)) {
1373
+ const estimateId = downloader.addDownloadEstimate(
1374
+ estimator.getSegmentEstimate(stream.id, segment));
1375
+ const segmentDownload = new shaka.offline.DownloadInfo(
1376
+ segment,
1377
+ estimateId,
1378
+ stream.id,
1379
+ /* isInitSegment= */ false);
1380
+ toDownload.set(pendingSegmentRefId, segmentDownload);
1381
+ }
1259
1382
 
1260
- /**
1261
- * Get a Promise to the DB key for a given segment reference.
1262
- *
1263
- * The return values will be cached so that multiple calls with the same
1264
- * segment reference will only trigger one request.
1265
- *
1266
- * @param {!shaka.offline.DownloadManager} downloader
1267
- * @param {number} downloadGroup
1268
- * @param {number} streamId
1269
- * @param {shaka.extern.StorageCell} storage
1270
- * @param {shaka.offline.StreamBandwidthEstimator} estimator
1271
- * @param {shaka.media.SegmentReference} segmentReference
1272
- * @param {shaka.extern.PlayerConfiguration} config
1273
- * @param {!Map.<string, !Promise.<number>>} segmentDbKeyCache
1274
- * @return {!Promise.<number>}
1275
- * @private
1276
- */
1277
- getSegmentDbKey_(
1278
- downloader, downloadGroup, streamId, storage, estimator,
1279
- segmentReference, config, segmentDbKeyCache) {
1280
- const mapKey = [
1281
- segmentReference.getUris()[0],
1282
- segmentReference.startByte,
1283
- segmentReference.endByte,
1284
- ].join('-');
1285
-
1286
- if (segmentDbKeyCache.has(mapKey)) {
1287
- return segmentDbKeyCache.get(mapKey);
1288
- }
1383
+ // Set up the download for the init segment, similarly, if there is one.
1384
+ if (segment.initSegmentReference) {
1385
+ pendingInitSegmentRefId = shaka.offline.DownloadInfo.idForSegmentRef(
1386
+ segment.initSegmentReference);
1387
+ if (!toDownload.has(pendingInitSegmentRefId)) {
1388
+ const estimateId = downloader.addDownloadEstimate(
1389
+ estimator.getInitSegmentEstimate(stream.id));
1390
+ const initDownload = new shaka.offline.DownloadInfo(
1391
+ segment.initSegmentReference,
1392
+ estimateId,
1393
+ stream.id,
1394
+ /* isInitSegment= */ true);
1395
+ toDownload.set(pendingInitSegmentRefId, initDownload);
1396
+ }
1397
+ }
1289
1398
 
1290
- const request = shaka.util.Networking.createSegmentRequest(
1291
- segmentReference.getUris(),
1292
- segmentReference.startByte,
1293
- segmentReference.endByte,
1294
- config.streaming.retryParameters);
1295
-
1296
- const promise = downloader.queue(
1297
- downloadGroup,
1298
- request,
1299
- estimator.getSegmentEstimate(streamId, segmentReference),
1300
- /* isInitSegment= */ false,
1301
- async (data) => {
1302
- /** @type {!Array.<number>} */
1303
- const ids = await storage.addSegments([{data: data}]);
1304
- this.segmentsFromStore_.push(ids[0]);
1305
- return ids[0];
1306
- });
1399
+ /** @type {!shaka.extern.SegmentDB} */
1400
+ const segmentDB = {
1401
+ pendingInitSegmentRefId,
1402
+ initSegmentKey: pendingInitSegmentRefId ? 0 : null,
1403
+ startTime: segment.startTime,
1404
+ endTime: segment.endTime,
1405
+ appendWindowStart: segment.appendWindowStart,
1406
+ appendWindowEnd: segment.appendWindowEnd,
1407
+ timestampOffset: segment.timestampOffset,
1408
+ tilesLayout: segment.tilesLayout,
1409
+ pendingSegmentRefId,
1410
+ dataKey: 0,
1411
+ };
1412
+ streamDb.segments.push(segmentDB);
1413
+ });
1307
1414
 
1308
- segmentDbKeyCache.set(mapKey, promise);
1309
- return promise;
1415
+ return streamDb;
1310
1416
  }
1311
1417
 
1312
1418
  /**
@@ -1408,21 +1514,21 @@ shaka.offline.Storage = class {
1408
1514
  * @private
1409
1515
  */
1410
1516
  static getAllSegmentIds_(manifest) {
1411
- /** @type {!Array.<number>} */
1412
- const ids = [];
1517
+ /** @type {!Set.<number>} */
1518
+ const ids = new Set();
1413
1519
 
1414
1520
  // Get every segment for every stream in the manifest.
1415
1521
  for (const stream of manifest.streams) {
1416
1522
  for (const segment of stream.segments) {
1417
1523
  if (segment.initSegmentKey != null) {
1418
- ids.push(segment.initSegmentKey);
1524
+ ids.add(segment.initSegmentKey);
1419
1525
  }
1420
1526
 
1421
- ids.push(segment.dataKey);
1527
+ ids.add(segment.dataKey);
1422
1528
  }
1423
1529
  }
1424
1530
 
1425
- return ids;
1531
+ return Array.from(ids);
1426
1532
  }
1427
1533
 
1428
1534
  /**
@@ -1557,6 +1663,9 @@ shaka.offline.Storage = class {
1557
1663
  }
1558
1664
  };
1559
1665
 
1666
+ /** @private {!shaka.util.Mutex} */
1667
+ shaka.offline.Storage.mutex_ = new shaka.util.Mutex();
1668
+
1560
1669
  shaka.offline.Storage.defaultSystemIds_ = new Map()
1561
1670
  .set('org.w3.clearkey', '1077efecc0b24d02ace33c1e52e2fb4b')
1562
1671
  .set('com.widevine.alpha', 'edef8ba979d64acea3c827dcd51d21ed')