Source: lib/offline/storage.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.offline.Storage');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.Player');
  9. goog.require('shaka.drm.DrmEngine');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.ManifestParser');
  12. goog.require('shaka.media.SegmentIndex');
  13. goog.require('shaka.media.SegmentReference');
  14. goog.require('shaka.media.SegmentUtils');
  15. goog.require('shaka.net.NetworkingEngine');
  16. goog.require('shaka.net.NetworkingUtils');
  17. goog.require('shaka.offline.DownloadInfo');
  18. goog.require('shaka.offline.DownloadManager');
  19. goog.require('shaka.offline.OfflineUri');
  20. goog.require('shaka.offline.SessionDeleter');
  21. goog.require('shaka.offline.StorageMuxer');
  22. goog.require('shaka.offline.StoredContentUtils');
  23. goog.require('shaka.offline.StreamBandwidthEstimator');
  24. goog.require('shaka.text.TextEngine');
  25. goog.require('shaka.util.AbortableOperation');
  26. goog.require('shaka.util.ArrayUtils');
  27. goog.require('shaka.util.BufferUtils');
  28. goog.require('shaka.util.ConfigUtils');
  29. goog.require('shaka.util.Destroyer');
  30. goog.require('shaka.util.Error');
  31. goog.require('shaka.util.IDestroyable');
  32. goog.require('shaka.util.Iterables');
  33. goog.require('shaka.util.ManifestParserUtils');
  34. goog.require('shaka.util.MimeUtils');
  35. goog.require('shaka.util.Platform');
  36. goog.require('shaka.util.PlayerConfiguration');
  37. goog.require('shaka.util.StreamUtils');
  38. goog.requireType('shaka.media.SegmentReference');
  39. goog.requireType('shaka.offline.StorageCellHandle');
  40. /**
  41. * @summary
  42. * This manages persistent offline data including storage, listing, and deleting
  43. * stored manifests. Playback of offline manifests are done through the Player
  44. * using a special URI (see shaka.offline.OfflineUri).
  45. *
  46. * First, check support() to see if offline is supported by the platform.
  47. * Second, configure() the storage object with callbacks to your application.
  48. * Third, call store(), remove(), or list() as needed.
  49. * When done, call destroy().
  50. *
  51. * @implements {shaka.util.IDestroyable}
  52. * @export
  53. */
  54. shaka.offline.Storage = class {
  55. /**
  56. * @param {!shaka.Player=} player
  57. * A player instance to share a networking engine and configuration with.
  58. * When initializing with a player, storage is only valid as long as
  59. * |destroy| has not been called on the player instance. When omitted,
  60. * storage will manage its own networking engine and configuration.
  61. */
  62. constructor(player) {
  63. // It is an easy mistake to make to pass a Player proxy from CastProxy.
  64. // Rather than throw a vague exception later, throw an explicit and clear
  65. // one now.
  66. //
  67. // TODO(vaage): After we decide whether or not we want to support
  68. // initializing storage with a player proxy, we should either remove
  69. // this error or rename the error.
  70. if (player && player.constructor != shaka.Player) {
  71. throw new shaka.util.Error(
  72. shaka.util.Error.Severity.CRITICAL,
  73. shaka.util.Error.Category.STORAGE,
  74. shaka.util.Error.Code.LOCAL_PLAYER_INSTANCE_REQUIRED);
  75. }
  76. /** @private {?shaka.extern.PlayerConfiguration} */
  77. this.config_ = null;
  78. /** @private {shaka.net.NetworkingEngine} */
  79. this.networkingEngine_ = null;
  80. // Initialize |config_| and |networkingEngine_| based on whether or not
  81. // we were given a player instance.
  82. if (player) {
  83. this.config_ = player.getSharedConfiguration();
  84. this.networkingEngine_ = player.getNetworkingEngine();
  85. goog.asserts.assert(
  86. this.networkingEngine_,
  87. 'Storage should not be initialized with a player that had ' +
  88. '|destroy| called on it.');
  89. } else {
  90. this.config_ = shaka.util.PlayerConfiguration.createDefault();
  91. this.networkingEngine_ = new shaka.net.NetworkingEngine();
  92. }
  93. /**
  94. * A list of open operations that are being performed by this instance of
  95. * |shaka.offline.Storage|.
  96. *
  97. * @private {!Array<!Promise>}
  98. */
  99. this.openOperations_ = [];
  100. /**
  101. * A list of open download managers that are being used to download things.
  102. *
  103. * @private {!Array<!shaka.offline.DownloadManager>}
  104. */
  105. this.openDownloadManagers_ = [];
  106. /**
  107. * Storage should only destroy the networking engine if it was initialized
  108. * without a player instance. Store this as a flag here to avoid including
  109. * the player object in the destroyer's closure.
  110. *
  111. * @type {boolean}
  112. */
  113. const destroyNetworkingEngine = !player;
  114. /** @private {!shaka.util.Destroyer} */
  115. this.destroyer_ = new shaka.util.Destroyer(async () => {
  116. // Cancel all in-progress store operations.
  117. await Promise.all(this.openDownloadManagers_.map((dl) => dl.abortAll()));
  118. // Wait for all remaining open operations to end. Wrap each operations so
  119. // that a single rejected promise won't cause |Promise.all| to return
  120. // early or to return a rejected Promise.
  121. const noop = () => {};
  122. const awaits = [];
  123. for (const op of this.openOperations_) {
  124. awaits.push(op.then(noop, noop));
  125. }
  126. await Promise.all(awaits);
  127. // Wait until after all the operations have finished before we destroy
  128. // the networking engine to avoid any unexpected errors.
  129. if (destroyNetworkingEngine) {
  130. await this.networkingEngine_.destroy();
  131. }
  132. // Drop all references to internal objects to help with GC.
  133. this.config_ = null;
  134. this.networkingEngine_ = null;
  135. });
  136. /**
  137. * Contains an ID for use with creating streams. The manifest parser should
  138. * start with small IDs, so this starts with a large one.
  139. * @private {number}
  140. */
  141. this.nextExternalStreamId_ = 1e9;
  142. }
  143. /**
  144. * Gets whether offline storage is supported. Returns true if offline storage
  145. * is supported for clear content. Support for offline storage of encrypted
  146. * content will not be determined until storage is attempted.
  147. *
  148. * @return {boolean}
  149. * @export
  150. */
  151. static support() {
  152. // Our Storage system is useless without MediaSource. MediaSource allows us
  153. // to pull data from anywhere (including our Storage system) and feed it to
  154. // the video element.
  155. if (!shaka.util.Platform.supportsMediaSource()) {
  156. return false;
  157. }
  158. return shaka.offline.StorageMuxer.support();
  159. }
  160. /**
  161. * @override
  162. * @export
  163. */
  164. destroy() {
  165. return this.destroyer_.destroy();
  166. }
  167. /**
  168. * Sets configuration values for Storage. This is associated with
  169. * Player.configure and will change the player instance given at
  170. * initialization.
  171. *
  172. * @param {string|!Object} config This should either be a field name or an
  173. * object following the form of {@link shaka.extern.PlayerConfiguration},
  174. * where you may omit any field you do not wish to change.
  175. * @param {*=} value This should be provided if the previous parameter
  176. * was a string field name.
  177. * @return {boolean}
  178. * @export
  179. */
  180. configure(config, value) {
  181. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  182. 'String configs should have values!');
  183. // ('fieldName', value) format
  184. if (arguments.length == 2 && typeof(config) == 'string') {
  185. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  186. }
  187. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  188. goog.asserts.assert(
  189. this.config_, 'Cannot reconfigure storage after calling destroy.');
  190. return shaka.util.PlayerConfiguration.mergeConfigObjects(
  191. /* destination= */ this.config_, /* updates= */ config );
  192. }
  193. /**
  194. * Return a copy of the current configuration. Modifications of the returned
  195. * value will not affect the Storage instance's active configuration. You
  196. * must call storage.configure() to make changes.
  197. *
  198. * @return {shaka.extern.PlayerConfiguration}
  199. * @export
  200. */
  201. getConfiguration() {
  202. goog.asserts.assert(this.config_, 'Config must not be null!');
  203. const ret = shaka.util.PlayerConfiguration.createDefault();
  204. shaka.util.PlayerConfiguration.mergeConfigObjects(
  205. ret, this.config_, shaka.util.PlayerConfiguration.createDefault());
  206. return ret;
  207. }
  208. /**
  209. * Return the networking engine that storage is using. If storage was
  210. * initialized with a player instance, then the networking engine returned
  211. * will be the same as |player.getNetworkingEngine()|.
  212. *
  213. * The returned value will only be null if |destroy| was called before
  214. * |getNetworkingEngine|.
  215. *
  216. * @return {shaka.net.NetworkingEngine}
  217. * @export
  218. */
  219. getNetworkingEngine() {
  220. return this.networkingEngine_;
  221. }
  222. /**
  223. * Stores the given manifest. If the content is encrypted, and encrypted
  224. * content cannot be stored on this platform, the Promise will be rejected
  225. * with error code 6001, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE.
  226. * Multiple assets can be downloaded at the same time, but note that since
  227. * the storage instance has a single networking engine, multiple storage
  228. * objects will be necessary if some assets require unique network filters.
  229. * This snapshots the storage config at the time of the call, so it will not
  230. * honor any changes to config mid-store operation.
  231. *
  232. * @param {string} uri The URI of the manifest to store.
  233. * @param {!Object=} appMetadata An arbitrary object from the application
  234. * that will be stored along-side the offline content. Use this for any
  235. * application-specific metadata you need associated with the stored
  236. * content. For details on the data types that can be stored here, please
  237. * refer to {@link https://bit.ly/StructClone}
  238. * @param {?string=} mimeType
  239. * The mime type for the content |manifestUri| points to.
  240. * @param {?Array<string>=} externalThumbnails
  241. * The external thumbnails to store along the main content.
  242. * @param {?Array<shaka.extern.ExtraText>=} externalText
  243. * The external text to store along the main content.
  244. * @return {!shaka.extern.IAbortableOperation.<shaka.extern.StoredContent>}
  245. * An AbortableOperation that resolves with a structure representing what
  246. * was stored. The "offlineUri" member is the URI that should be given to
  247. * Player.load() to play this piece of content offline. The "appMetadata"
  248. * member is the appMetadata argument you passed to store().
  249. * If you want to cancel this download, call the "abort" method on
  250. * AbortableOperation.
  251. * @export
  252. */
  253. store(uri, appMetadata, mimeType, externalThumbnails, externalText) {
  254. goog.asserts.assert(
  255. this.networkingEngine_,
  256. 'Cannot call |store| after calling |destroy|.');
  257. // Get a copy of the current config.
  258. const config = this.getConfiguration();
  259. const getParser = async () => {
  260. goog.asserts.assert(
  261. this.networkingEngine_, 'Should not call |store| after |destroy|');
  262. if (!mimeType) {
  263. mimeType = await shaka.net.NetworkingUtils.getMimeType(
  264. uri, this.networkingEngine_, config.manifest.retryParameters);
  265. }
  266. const factory = shaka.media.ManifestParser.getFactory(
  267. uri,
  268. mimeType || null);
  269. return factory();
  270. };
  271. /** @type {!shaka.offline.DownloadManager} */
  272. const downloader =
  273. new shaka.offline.DownloadManager(this.networkingEngine_);
  274. this.openDownloadManagers_.push(downloader);
  275. const storeOp = this.store_(
  276. uri, appMetadata || {}, externalThumbnails || [], externalText || [],
  277. getParser, config, downloader);
  278. const abortableStoreOp = new shaka.util.AbortableOperation(storeOp, () => {
  279. return downloader.abortAll();
  280. });
  281. abortableStoreOp.finally(() => {
  282. shaka.util.ArrayUtils.remove(this.openDownloadManagers_, downloader);
  283. });
  284. return this.startAbortableOperation_(abortableStoreOp);
  285. }
  286. /**
  287. * See |shaka.offline.Storage.store| for details.
  288. *
  289. * @param {string} uri
  290. * @param {!Object} appMetadata
  291. * @param {!Array<string>} externalThumbnails
  292. * @param {!Array<shaka.extern.ExtraText>} externalText
  293. * @param {function(): !Promise<shaka.extern.ManifestParser>} getParser
  294. * @param {shaka.extern.PlayerConfiguration} config
  295. * @param {!shaka.offline.DownloadManager} downloader
  296. * @return {!Promise<shaka.extern.StoredContent>}
  297. * @private
  298. */
  299. async store_(uri, appMetadata, externalThumbnails, externalText,
  300. getParser, config, downloader) {
  301. this.requireSupport_();
  302. // Since we will need to use |parser|, |drmEngine|, |activeHandle|, and
  303. // |muxer| in the catch/finally blocks, we need to define them out here.
  304. // Since they may not get initialized when we enter the catch/finally block,
  305. // we need to assume that they may be null/undefined when we get there.
  306. /** @type {?shaka.extern.ManifestParser} */
  307. let parser = null;
  308. /** @type {?shaka.drm.DrmEngine} */
  309. let drmEngine = null;
  310. /** @type {shaka.offline.StorageMuxer} */
  311. const muxer = new shaka.offline.StorageMuxer();
  312. /** @type {?shaka.offline.StorageCellHandle} */
  313. let activeHandle = null;
  314. /** @type {?number} */
  315. let manifestId = null;
  316. // This will be used to store any errors from drm engine. Whenever drm
  317. // engine is passed to another function to do work, we should check if this
  318. // was set.
  319. let drmError = null;
  320. try {
  321. parser = await getParser();
  322. const manifest = await this.parseManifest(uri, parser, config);
  323. // Check if we were asked to destroy ourselves while we were "away"
  324. // downloading the manifest.
  325. this.ensureNotDestroyed_();
  326. // Check if we can even download this type of manifest before trying to
  327. // create the drm engine.
  328. const canDownload = !manifest.presentationTimeline.isLive() &&
  329. !manifest.presentationTimeline.isInProgress();
  330. if (!canDownload) {
  331. throw new shaka.util.Error(
  332. shaka.util.Error.Severity.CRITICAL,
  333. shaka.util.Error.Category.STORAGE,
  334. shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE,
  335. uri);
  336. }
  337. for (const thumbnailUri of externalThumbnails) {
  338. const imageStream =
  339. // eslint-disable-next-line no-await-in-loop
  340. await this.createExternalImageStream_(thumbnailUri, manifest);
  341. manifest.imageStreams.push(imageStream);
  342. this.ensureNotDestroyed_();
  343. }
  344. for (const text of externalText) {
  345. const textStream =
  346. // eslint-disable-next-line no-await-in-loop
  347. await this.createExternalTextStream_(manifest,
  348. text.uri, text.language, text.kind, text.mime, text.codecs);
  349. manifest.textStreams.push(textStream);
  350. this.ensureNotDestroyed_();
  351. }
  352. shaka.drm.DrmEngine.configureClearKey(
  353. config.drm.clearKeys, manifest.variants);
  354. const clearKeyDataLicenseServerUri = manifest.variants.some((v) => {
  355. if (v.audio) {
  356. for (const drmInfo of v.audio.drmInfos) {
  357. if (drmInfo.licenseServerUri.startsWith('data:')) {
  358. return true;
  359. }
  360. }
  361. }
  362. if (v.video) {
  363. for (const drmInfo of v.video.drmInfos) {
  364. if (drmInfo.licenseServerUri.startsWith('data:')) {
  365. return true;
  366. }
  367. }
  368. }
  369. return false;
  370. });
  371. let usePersistentLicense = config.offline.usePersistentLicense;
  372. if (clearKeyDataLicenseServerUri) {
  373. usePersistentLicense = false;
  374. }
  375. // Create the DRM engine, and load the keys in the manifest.
  376. drmEngine = await this.createDrmEngine(
  377. manifest,
  378. (e) => { drmError = drmError || e; },
  379. config,
  380. usePersistentLicense);
  381. // We could have been asked to destroy ourselves while we were "away"
  382. // creating the drm engine.
  383. this.ensureNotDestroyed_();
  384. if (drmError) {
  385. throw drmError;
  386. }
  387. await this.filterManifest_(
  388. manifest, drmEngine, config, usePersistentLicense);
  389. await muxer.init();
  390. this.ensureNotDestroyed_();
  391. // Get the cell that we are saving the manifest to. Once we get a cell
  392. // we will only reference the cell and not the muxer so that the manifest
  393. // and segments will all be saved to the same cell.
  394. activeHandle = await muxer.getActive();
  395. this.ensureNotDestroyed_();
  396. goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
  397. const {manifestDB, toDownload} = this.makeManifestDB_(
  398. drmEngine, manifest, uri, appMetadata, config, downloader,
  399. usePersistentLicense);
  400. // Store the empty manifest, before downloading the segments.
  401. const ids = await activeHandle.cell.addManifests([manifestDB]);
  402. this.ensureNotDestroyed_();
  403. manifestId = ids[0];
  404. goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
  405. this.ensureNotDestroyed_();
  406. if (drmError) {
  407. throw drmError;
  408. }
  409. await this.downloadSegments_(toDownload, manifestId, manifestDB,
  410. downloader, config, activeHandle.cell, manifest, drmEngine,
  411. usePersistentLicense);
  412. this.ensureNotDestroyed_();
  413. this.setManifestDrmFields_(
  414. manifest, manifestDB, drmEngine, usePersistentLicense);
  415. await activeHandle.cell.updateManifest(manifestId, manifestDB);
  416. this.ensureNotDestroyed_();
  417. const offlineUri = shaka.offline.OfflineUri.manifest(
  418. activeHandle.path.mechanism, activeHandle.path.cell, manifestId);
  419. return shaka.offline.StoredContentUtils.fromManifestDB(
  420. offlineUri, manifestDB);
  421. } catch (e) {
  422. if (manifestId != null) {
  423. await shaka.offline.Storage.cleanStoredManifest(manifestId);
  424. }
  425. // If we already had an error, ignore this error to avoid hiding
  426. // the original error.
  427. throw drmError || e;
  428. } finally {
  429. await muxer.destroy();
  430. if (parser) {
  431. await parser.stop();
  432. }
  433. if (drmEngine) {
  434. await drmEngine.destroy();
  435. }
  436. }
  437. }
  438. /**
  439. * Download and then store the contents of each segment.
  440. * The promise this returns will wait for local downloads.
  441. *
  442. * @param {!Array<!shaka.offline.DownloadInfo>} toDownload
  443. * @param {number} manifestId
  444. * @param {shaka.extern.ManifestDB} manifestDB
  445. * @param {!shaka.offline.DownloadManager} downloader
  446. * @param {shaka.extern.PlayerConfiguration} config
  447. * @param {shaka.extern.StorageCell} storage
  448. * @param {shaka.extern.Manifest} manifest
  449. * @param {!shaka.drm.DrmEngine} drmEngine
  450. * @param {boolean} usePersistentLicense
  451. * @return {!Promise}
  452. * @private
  453. */
  454. async downloadSegments_(
  455. toDownload, manifestId, manifestDB, downloader, config, storage,
  456. manifest, drmEngine, usePersistentLicense) {
  457. let pendingManifestUpdates = {};
  458. let pendingDataSize = 0;
  459. const ensureNotAbortedOrDestroyed = () => {
  460. if (this.destroyer_.destroyed() || downloader.isAborted()) {
  461. throw new shaka.util.Error(
  462. shaka.util.Error.Severity.CRITICAL,
  463. shaka.util.Error.Category.STORAGE,
  464. shaka.util.Error.Code.OPERATION_ABORTED);
  465. }
  466. };
  467. /**
  468. * @param {!Array<!shaka.offline.DownloadInfo>} toDownload
  469. * @param {boolean} updateDRM
  470. */
  471. const download = async (toDownload, updateDRM) => {
  472. for (const download of toDownload) {
  473. ensureNotAbortedOrDestroyed();
  474. const request = download.makeSegmentRequest(config);
  475. const estimateId = download.estimateId;
  476. const isInitSegment = download.isInitSegment;
  477. const onDownloaded = async (data) => {
  478. const ref = /** @type {!shaka.media.SegmentReference} */ (
  479. download.ref);
  480. const id = shaka.offline.DownloadInfo.idForSegmentRef(ref);
  481. if (ref.aesKey) {
  482. data = await shaka.media.SegmentUtils.aesDecrypt(
  483. data, ref.aesKey, download.refPosition);
  484. }
  485. // Store the data.
  486. const dataKeys = await storage.addSegments([{data}]);
  487. ensureNotAbortedOrDestroyed();
  488. // Store the necessary update to the manifest, to be processed later.
  489. pendingManifestUpdates[id] = dataKeys[0];
  490. pendingDataSize += data.byteLength;
  491. };
  492. const ref = /** @type {!shaka.media.SegmentReference} */ (
  493. download.ref);
  494. const segmentData = ref.getSegmentData();
  495. if (segmentData) {
  496. downloader.queueData(download.groupId,
  497. segmentData, estimateId, isInitSegment, onDownloaded);
  498. } else {
  499. downloader.queue(download.groupId,
  500. request, estimateId, isInitSegment, onDownloaded);
  501. }
  502. }
  503. await downloader.waitToFinish();
  504. ensureNotAbortedOrDestroyed();
  505. if (updateDRM && !downloader.isAborted()) {
  506. // Re-store the manifest, to attach session IDs.
  507. // These were (maybe) discovered inside the downloader; we can only add
  508. // them now, at the end, since the manifestDB is in flux during the
  509. // process of downloading and storing, and assignSegmentsToManifest
  510. // does not know about the DRM engine.
  511. this.setManifestDrmFields_(
  512. manifest, manifestDB, drmEngine, usePersistentLicense);
  513. await storage.updateManifest(manifestId, manifestDB);
  514. }
  515. };
  516. const usingBgFetch = false; // TODO: Get.
  517. try {
  518. if (this.getManifestIsEncrypted_(manifest) && usingBgFetch &&
  519. !this.getManifestIncludesInitData_(manifest)) {
  520. // Background fetch can't make DRM sessions, so if we have to get the
  521. // init data from the init segments, download those first before
  522. // anything else.
  523. await download(toDownload.filter((info) => info.isInitSegment), true);
  524. ensureNotAbortedOrDestroyed();
  525. toDownload = toDownload.filter((info) => !info.isInitSegment);
  526. // Copy these and reset them now, before calling await.
  527. const manifestUpdates = pendingManifestUpdates;
  528. const dataSize = pendingDataSize;
  529. pendingManifestUpdates = {};
  530. pendingDataSize = 0;
  531. await shaka.offline.Storage.assignSegmentsToManifest(
  532. storage, manifestId, manifestDB, manifestUpdates, dataSize,
  533. () => this.ensureNotDestroyed_());
  534. ensureNotAbortedOrDestroyed();
  535. }
  536. if (!usingBgFetch) {
  537. await download(toDownload, false);
  538. ensureNotAbortedOrDestroyed();
  539. // Copy these and reset them now, before calling await.
  540. const manifestUpdates = pendingManifestUpdates;
  541. const dataSize = pendingDataSize;
  542. pendingManifestUpdates = {};
  543. pendingDataSize = 0;
  544. await shaka.offline.Storage.assignSegmentsToManifest(
  545. storage, manifestId, manifestDB, manifestUpdates, dataSize,
  546. () => ensureNotAbortedOrDestroyed());
  547. ensureNotAbortedOrDestroyed();
  548. goog.asserts.assert(
  549. !manifestDB.isIncomplete, 'The manifest should be complete by now');
  550. } else {
  551. // TODO: Send the request to the service worker. Don't await the result.
  552. }
  553. } catch (error) {
  554. const dataKeys = Object.values(pendingManifestUpdates);
  555. // Remove these pending segments that are not yet linked to the manifest.
  556. await storage.removeSegments(dataKeys, (key) => {});
  557. throw error;
  558. }
  559. }
  560. /**
  561. * Removes all of the contents for a given manifest, statelessly.
  562. *
  563. * @param {number} manifestId
  564. * @return {!Promise}
  565. */
  566. static async cleanStoredManifest(manifestId) {
  567. const muxer = new shaka.offline.StorageMuxer();
  568. await muxer.init();
  569. const activeHandle = await muxer.getActive();
  570. const uri = shaka.offline.OfflineUri.manifest(
  571. activeHandle.path.mechanism,
  572. activeHandle.path.cell,
  573. manifestId);
  574. await muxer.destroy();
  575. const storage = new shaka.offline.Storage();
  576. await storage.remove(uri.toString());
  577. }
  578. /**
  579. * Updates the given manifest, assigns database keys to segments, then stores
  580. * the updated manifest.
  581. *
  582. * It is up to the caller to ensure that this method is not called
  583. * concurrently on the same manifest.
  584. *
  585. * @param {shaka.extern.StorageCell} storage
  586. * @param {number} manifestId
  587. * @param {!shaka.extern.ManifestDB} manifestDB
  588. * @param {!Object<string, number>} manifestUpdates
  589. * @param {number} dataSizeUpdate
  590. * @param {function()} throwIfAbortedFn A function that should throw if the
  591. * download has been aborted.
  592. * @return {!Promise}
  593. */
  594. static async assignSegmentsToManifest(
  595. storage, manifestId, manifestDB, manifestUpdates, dataSizeUpdate,
  596. throwIfAbortedFn) {
  597. let manifestUpdated = false;
  598. try {
  599. // Assign the stored data to the manifest.
  600. let complete = true;
  601. for (const stream of manifestDB.streams) {
  602. for (const segment of stream.segments) {
  603. let dataKey = segment.pendingSegmentRefId ?
  604. manifestUpdates[segment.pendingSegmentRefId] : null;
  605. if (dataKey != null) {
  606. segment.dataKey = dataKey;
  607. // Now that the segment has been associated with the appropriate
  608. // dataKey, the pendingSegmentRefId is no longer necessary.
  609. segment.pendingSegmentRefId = undefined;
  610. }
  611. dataKey = segment.pendingInitSegmentRefId ?
  612. manifestUpdates[segment.pendingInitSegmentRefId] : null;
  613. if (dataKey != null) {
  614. segment.initSegmentKey = dataKey;
  615. // Now that the init segment has been associated with the
  616. // appropriate initSegmentKey, the pendingInitSegmentRefId is no
  617. // longer necessary.
  618. segment.pendingInitSegmentRefId = undefined;
  619. }
  620. if (segment.pendingSegmentRefId) {
  621. complete = false;
  622. }
  623. if (segment.pendingInitSegmentRefId) {
  624. complete = false;
  625. }
  626. }
  627. }
  628. // Update the size of the manifest.
  629. manifestDB.size += dataSizeUpdate;
  630. // Mark the manifest as complete, if all segments are downloaded.
  631. if (complete) {
  632. manifestDB.isIncomplete = false;
  633. }
  634. // Update the manifest.
  635. await storage.updateManifest(manifestId, manifestDB);
  636. manifestUpdated = true;
  637. throwIfAbortedFn();
  638. } catch (e) {
  639. await shaka.offline.Storage.cleanStoredManifest(manifestId);
  640. if (!manifestUpdated) {
  641. const dataKeys = Object.values(manifestUpdates);
  642. // The cleanStoredManifest method will not "see" any segments that have
  643. // been downloaded but not assigned to the manifest yet. So un-store
  644. // them separately.
  645. await storage.removeSegments(dataKeys, (key) => {});
  646. }
  647. throw e;
  648. }
  649. }
  650. /**
  651. * Filter |manifest| such that it will only contain the variants and text
  652. * streams that we want to store and can actually play.
  653. *
  654. * @param {shaka.extern.Manifest} manifest
  655. * @param {!shaka.drm.DrmEngine} drmEngine
  656. * @param {shaka.extern.PlayerConfiguration} config
  657. * @param {boolean} usePersistentLicense
  658. * @return {!Promise}
  659. * @private
  660. */
  661. async filterManifest_(manifest, drmEngine, config, usePersistentLicense) {
  662. // Filter the manifest based on the restrictions given in the player
  663. // configuration.
  664. const maxHwRes = {width: Infinity, height: Infinity};
  665. shaka.util.StreamUtils.filterByRestrictions(
  666. manifest, config.restrictions, maxHwRes);
  667. // Filter the manifest based on what we know MediaCapabilities will be able
  668. // to play later (no point storing something we can't play).
  669. await shaka.util.StreamUtils.filterManifestByMediaCapabilities(
  670. drmEngine, manifest, usePersistentLicense,
  671. config.drm.preferredKeySystems, config.drm.keySystemsMapping);
  672. // Gather all tracks.
  673. const allTracks = [];
  674. // Choose the codec that has the lowest average bandwidth.
  675. const preferredDecodingAttributes = config.preferredDecodingAttributes;
  676. const preferredVideoCodecs = config.preferredVideoCodecs;
  677. const preferredAudioCodecs = config.preferredAudioCodecs;
  678. const preferredTextFormats = config.preferredTextFormats;
  679. shaka.util.StreamUtils.chooseCodecsAndFilterManifest(
  680. manifest, preferredVideoCodecs, preferredAudioCodecs,
  681. preferredDecodingAttributes, preferredTextFormats);
  682. for (const variant of manifest.variants) {
  683. goog.asserts.assert(
  684. shaka.util.StreamUtils.isPlayable(variant),
  685. 'We should have already filtered by "is playable"');
  686. allTracks.push(shaka.util.StreamUtils.variantToTrack(variant));
  687. }
  688. for (const text of manifest.textStreams) {
  689. allTracks.push(shaka.util.StreamUtils.textStreamToTrack(text));
  690. }
  691. for (const image of manifest.imageStreams) {
  692. allTracks.push(shaka.util.StreamUtils.imageStreamToTrack(image));
  693. }
  694. // Let the application choose which tracks to store.
  695. const chosenTracks =
  696. await config.offline.trackSelectionCallback(allTracks);
  697. const duration = manifest.presentationTimeline.getDuration();
  698. let sizeEstimate = 0;
  699. for (const track of chosenTracks) {
  700. const trackSize = track.bandwidth * duration / 8;
  701. sizeEstimate += trackSize;
  702. }
  703. try {
  704. const allowedDownload =
  705. await config.offline.downloadSizeCallback(sizeEstimate);
  706. if (!allowedDownload) {
  707. throw new shaka.util.Error(
  708. shaka.util.Error.Severity.CRITICAL,
  709. shaka.util.Error.Category.STORAGE,
  710. shaka.util.Error.Code.STORAGE_LIMIT_REACHED);
  711. }
  712. } catch (e) {
  713. // It is necessary to be able to catch the STORAGE_LIMIT_REACHED error
  714. if (e instanceof shaka.util.Error) {
  715. throw e;
  716. }
  717. shaka.log.warning(
  718. 'downloadSizeCallback has produced an unexpected error', e);
  719. throw new shaka.util.Error(
  720. shaka.util.Error.Severity.CRITICAL,
  721. shaka.util.Error.Category.STORAGE,
  722. shaka.util.Error.Code.DOWNLOAD_SIZE_CALLBACK_ERROR);
  723. }
  724. /** @type {!Set<number>} */
  725. const variantIds = new Set();
  726. /** @type {!Set<number>} */
  727. const textIds = new Set();
  728. /** @type {!Set<number>} */
  729. const imageIds = new Set();
  730. // Collect the IDs of the chosen tracks.
  731. for (const track of chosenTracks) {
  732. if (track.type == 'variant') {
  733. variantIds.add(track.id);
  734. }
  735. if (track.type == 'text') {
  736. textIds.add(track.id);
  737. }
  738. if (track.type == 'image') {
  739. imageIds.add(track.id);
  740. }
  741. }
  742. // Filter the manifest to keep only what the app chose.
  743. manifest.variants =
  744. manifest.variants.filter((variant) => variantIds.has(variant.id));
  745. manifest.textStreams =
  746. manifest.textStreams.filter((stream) => textIds.has(stream.id));
  747. manifest.imageStreams =
  748. manifest.imageStreams.filter((stream) => imageIds.has(stream.id));
  749. // Check the post-filtered manifest for characteristics that may indicate
  750. // issues with how the app selected tracks.
  751. shaka.offline.Storage.validateManifest_(manifest);
  752. }
  753. /**
  754. * Create a download manager and download the manifest.
  755. * This also sets up download infos for each segment to be downloaded.
  756. *
  757. * @param {!shaka.drm.DrmEngine} drmEngine
  758. * @param {shaka.extern.Manifest} manifest
  759. * @param {string} uri
  760. * @param {!Object} metadata
  761. * @param {shaka.extern.PlayerConfiguration} config
  762. * @param {!shaka.offline.DownloadManager} downloader
  763. * @param {boolean} usePersistentLicense
  764. * @return {{
  765. * manifestDB: shaka.extern.ManifestDB,
  766. * toDownload: !Array<!shaka.offline.DownloadInfo>
  767. * }}
  768. * @private
  769. */
  770. makeManifestDB_(drmEngine, manifest, uri, metadata, config, downloader,
  771. usePersistentLicense) {
  772. const pendingContent = shaka.offline.StoredContentUtils.fromManifest(
  773. uri, manifest, /* size= */ 0, metadata);
  774. // In https://github.com/shaka-project/shaka-player/issues/2652, we found
  775. // that this callback would be removed by the compiler if we reference the
  776. // config in the onProgress closure below. Reading it into a local
  777. // variable first seems to work around this apparent compiler bug.
  778. const progressCallback = config.offline.progressCallback;
  779. const onProgress = (progress, size) => {
  780. // Update the size of the stored content before issuing a progress
  781. // update.
  782. pendingContent.size = size;
  783. progressCallback(pendingContent, progress);
  784. };
  785. const onInitData = (initData, systemId) => {
  786. if (needsInitData && usePersistentLicense &&
  787. currentSystemId == systemId) {
  788. drmEngine.newInitData('cenc', initData);
  789. }
  790. };
  791. downloader.setCallbacks(onProgress, onInitData);
  792. const needsInitData = this.getManifestIsEncrypted_(manifest) &&
  793. !this.getManifestIncludesInitData_(manifest);
  794. let currentSystemId = null;
  795. if (needsInitData) {
  796. const drmInfo = drmEngine.getDrmInfo();
  797. currentSystemId =
  798. shaka.offline.Storage.defaultSystemIds_.get(drmInfo.keySystem);
  799. }
  800. // Make the estimator, which is used to make the download registries.
  801. const estimator = new shaka.offline.StreamBandwidthEstimator();
  802. for (const stream of manifest.textStreams) {
  803. estimator.addText(stream);
  804. }
  805. for (const stream of manifest.imageStreams) {
  806. estimator.addImage(stream);
  807. }
  808. for (const variant of manifest.variants) {
  809. estimator.addVariant(variant);
  810. }
  811. const {streams, toDownload} = this.createStreams_(
  812. downloader, estimator, drmEngine, manifest, config);
  813. const drmInfo = drmEngine.getDrmInfo();
  814. if (drmInfo && usePersistentLicense) {
  815. // Don't store init data, since we have stored sessions.
  816. drmInfo.initData = [];
  817. }
  818. const manifestDB = {
  819. creationTime: Date.now(),
  820. originalManifestUri: uri,
  821. duration: manifest.presentationTimeline.getDuration(),
  822. size: 0,
  823. expiration: drmEngine.getExpiration(),
  824. streams,
  825. sessionIds: usePersistentLicense ? drmEngine.getSessionIds() : [],
  826. drmInfo,
  827. appMetadata: metadata,
  828. isIncomplete: true,
  829. sequenceMode: manifest.sequenceMode,
  830. type: manifest.type,
  831. };
  832. return {manifestDB, toDownload};
  833. }
  834. /**
  835. * @param {shaka.extern.Manifest} manifest
  836. * @return {boolean}
  837. * @private
  838. */
  839. getManifestIsEncrypted_(manifest) {
  840. return manifest.variants.some((variant) => {
  841. const videoEncrypted = variant.video && variant.video.encrypted;
  842. const audioEncrypted = variant.audio && variant.audio.encrypted;
  843. return videoEncrypted || audioEncrypted;
  844. });
  845. }
  846. /**
  847. * @param {shaka.extern.Manifest} manifest
  848. * @return {boolean}
  849. * @private
  850. */
  851. getManifestIncludesInitData_(manifest) {
  852. return manifest.variants.some((variant) => {
  853. const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
  854. const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
  855. const drmInfos = videoDrmInfos.concat(audioDrmInfos);
  856. return drmInfos.some((drmInfos) => {
  857. return drmInfos.initData && drmInfos.initData.length;
  858. });
  859. });
  860. }
  861. /**
  862. * @param {shaka.extern.Manifest} manifest
  863. * @param {shaka.extern.ManifestDB} manifestDB
  864. * @param {!shaka.drm.DrmEngine} drmEngine
  865. * @param {boolean} usePersistentLicense
  866. * @private
  867. */
  868. setManifestDrmFields_(manifest, manifestDB, drmEngine, usePersistentLicense) {
  869. manifestDB.expiration = drmEngine.getExpiration();
  870. const sessions = drmEngine.getSessionIds();
  871. manifestDB.sessionIds = usePersistentLicense ? sessions : [];
  872. if (this.getManifestIsEncrypted_(manifest) &&
  873. usePersistentLicense && !sessions.length) {
  874. throw new shaka.util.Error(
  875. shaka.util.Error.Severity.CRITICAL,
  876. shaka.util.Error.Category.STORAGE,
  877. shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
  878. }
  879. }
  880. /**
  881. * Removes the given stored content. This will also attempt to release the
  882. * licenses, if any.
  883. *
  884. * @param {string} contentUri
  885. * @return {!Promise}
  886. * @export
  887. */
  888. remove(contentUri) {
  889. return this.startOperation_(this.remove_(contentUri));
  890. }
  891. /**
  892. * See |shaka.offline.Storage.remove| for details.
  893. *
  894. * @param {string} contentUri
  895. * @return {!Promise}
  896. * @private
  897. */
  898. async remove_(contentUri) {
  899. this.requireSupport_();
  900. const nullableUri = shaka.offline.OfflineUri.parse(contentUri);
  901. if (nullableUri == null || !nullableUri.isManifest()) {
  902. throw new shaka.util.Error(
  903. shaka.util.Error.Severity.CRITICAL,
  904. shaka.util.Error.Category.STORAGE,
  905. shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
  906. contentUri);
  907. }
  908. /** @type {!shaka.offline.OfflineUri} */
  909. const uri = nullableUri;
  910. /** @type {!shaka.offline.StorageMuxer} */
  911. const muxer = new shaka.offline.StorageMuxer();
  912. try {
  913. await muxer.init();
  914. const cell = await muxer.getCell(uri.mechanism(), uri.cell());
  915. const manifests = await cell.getManifests([uri.key()]);
  916. const manifest = manifests[0];
  917. await Promise.all([
  918. this.removeFromDRM_(uri, manifest, muxer),
  919. this.removeFromStorage_(cell, uri, manifest),
  920. ]);
  921. } finally {
  922. await muxer.destroy();
  923. }
  924. }
  925. /**
  926. * @param {shaka.extern.ManifestDB} manifestDb
  927. * @param {boolean} isVideo
  928. * @return {!Array<MediaKeySystemMediaCapability>}
  929. * @private
  930. */
  931. static getCapabilities_(manifestDb, isVideo) {
  932. const MimeUtils = shaka.util.MimeUtils;
  933. const ret = [];
  934. for (const stream of manifestDb.streams) {
  935. if (isVideo && stream.type == 'video') {
  936. ret.push({
  937. contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
  938. robustness: manifestDb.drmInfo.videoRobustness,
  939. });
  940. } else if (!isVideo && stream.type == 'audio') {
  941. ret.push({
  942. contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
  943. robustness: manifestDb.drmInfo.audioRobustness,
  944. });
  945. }
  946. }
  947. return ret;
  948. }
  949. /**
  950. * @param {!shaka.offline.OfflineUri} uri
  951. * @param {shaka.extern.ManifestDB} manifestDb
  952. * @param {!shaka.offline.StorageMuxer} muxer
  953. * @return {!Promise}
  954. * @private
  955. */
  956. async removeFromDRM_(uri, manifestDb, muxer) {
  957. goog.asserts.assert(this.networkingEngine_, 'Cannot be destroyed');
  958. await shaka.offline.Storage.deleteLicenseFor_(
  959. this.networkingEngine_, this.config_.drm, muxer, manifestDb);
  960. }
  961. /**
  962. * @param {shaka.extern.StorageCell} storage
  963. * @param {!shaka.offline.OfflineUri} uri
  964. * @param {shaka.extern.ManifestDB} manifest
  965. * @return {!Promise}
  966. * @private
  967. */
  968. removeFromStorage_(storage, uri, manifest) {
  969. /** @type {!Array<number>} */
  970. const segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest);
  971. // Count(segments) + Count(manifests)
  972. const toRemove = segmentIds.length + 1;
  973. let removed = 0;
  974. const pendingContent = shaka.offline.StoredContentUtils.fromManifestDB(
  975. uri, manifest);
  976. const onRemove = (key) => {
  977. removed += 1;
  978. this.config_.offline.progressCallback(pendingContent, removed / toRemove);
  979. };
  980. return Promise.all([
  981. storage.removeSegments(segmentIds, onRemove),
  982. storage.removeManifests([uri.key()], onRemove),
  983. ]);
  984. }
  985. /**
  986. * Removes any EME sessions that were not successfully removed before. This
  987. * returns whether all the sessions were successfully removed.
  988. *
  989. * @return {!Promise<boolean>}
  990. * @export
  991. */
  992. removeEmeSessions() {
  993. return this.startOperation_(this.removeEmeSessions_());
  994. }
  995. /**
  996. * @return {!Promise<boolean>}
  997. * @private
  998. */
  999. async removeEmeSessions_() {
  1000. this.requireSupport_();
  1001. goog.asserts.assert(this.networkingEngine_, 'Cannot be destroyed');
  1002. const net = this.networkingEngine_;
  1003. const config = this.config_.drm;
  1004. /** @type {!shaka.offline.StorageMuxer} */
  1005. const muxer = new shaka.offline.StorageMuxer();
  1006. /** @type {!shaka.offline.SessionDeleter} */
  1007. const deleter = new shaka.offline.SessionDeleter();
  1008. let hasRemaining = false;
  1009. try {
  1010. await muxer.init();
  1011. /** @type {!Array<shaka.extern.EmeSessionStorageCell>} */
  1012. const cells = [];
  1013. muxer.forEachEmeSessionCell((c) => cells.push(c));
  1014. // Run these sequentially to avoid creating too many DrmEngine instances
  1015. // and having multiple CDMs alive at once. Some embedded platforms may
  1016. // not support that.
  1017. for (const sessionIdCell of cells) {
  1018. /* eslint-disable no-await-in-loop */
  1019. const sessions = await sessionIdCell.getAll();
  1020. const deletedSessionIds = await deleter.delete(config, net, sessions);
  1021. await sessionIdCell.remove(deletedSessionIds);
  1022. if (deletedSessionIds.length != sessions.length) {
  1023. hasRemaining = true;
  1024. }
  1025. /* eslint-enable no-await-in-loop */
  1026. }
  1027. } finally {
  1028. await muxer.destroy();
  1029. }
  1030. return !hasRemaining;
  1031. }
  1032. /**
  1033. * Lists all the stored content available.
  1034. *
  1035. * @return {!Promise<!Array<shaka.extern.StoredContent>>} A Promise to an
  1036. * array of structures representing all stored content. The "offlineUri"
  1037. * member of the structure is the URI that should be given to Player.load()
  1038. * to play this piece of content offline. The "appMetadata" member is the
  1039. * appMetadata argument you passed to store().
  1040. * @export
  1041. */
  1042. list() {
  1043. return this.startOperation_(this.list_());
  1044. }
  1045. /**
  1046. * See |shaka.offline.Storage.list| for details.
  1047. *
  1048. * @return {!Promise<!Array<shaka.extern.StoredContent>>}
  1049. * @private
  1050. */
  1051. async list_() {
  1052. this.requireSupport_();
  1053. /** @type {!Array<shaka.extern.StoredContent>} */
  1054. const result = [];
  1055. /** @type {!shaka.offline.StorageMuxer} */
  1056. const muxer = new shaka.offline.StorageMuxer();
  1057. try {
  1058. await muxer.init();
  1059. let p = Promise.resolve();
  1060. muxer.forEachCell((path, cell) => {
  1061. p = p.then(async () => {
  1062. const manifests = await cell.getAllManifests();
  1063. manifests.forEach((manifest, key) => {
  1064. const uri = shaka.offline.OfflineUri.manifest(
  1065. path.mechanism,
  1066. path.cell,
  1067. key);
  1068. const content = shaka.offline.StoredContentUtils.fromManifestDB(
  1069. uri,
  1070. manifest);
  1071. result.push(content);
  1072. });
  1073. });
  1074. });
  1075. await p;
  1076. } finally {
  1077. await muxer.destroy();
  1078. }
  1079. return result;
  1080. }
  1081. /**
  1082. * This method is public so that it can be overridden in testing.
  1083. *
  1084. * @param {string} uri
  1085. * @param {shaka.extern.ManifestParser} parser
  1086. * @param {shaka.extern.PlayerConfiguration} config
  1087. * @return {!Promise<shaka.extern.Manifest>}
  1088. */
  1089. async parseManifest(uri, parser, config) {
  1090. let error = null;
  1091. const networkingEngine = this.networkingEngine_;
  1092. goog.asserts.assert(networkingEngine, 'Should be initialized!');
  1093. /** @type {shaka.extern.ManifestParser.PlayerInterface} */
  1094. const playerInterface = {
  1095. networkingEngine: networkingEngine,
  1096. // Don't bother filtering now. We will do that later when we have all the
  1097. // information we need to filter.
  1098. filter: () => Promise.resolve(),
  1099. // The responsibility for making mock text streams for closed captions is
  1100. // handled inside shaka.offline.OfflineManifestParser, before playback.
  1101. makeTextStreamsForClosedCaptions: (manifest) => {},
  1102. onTimelineRegionAdded: () => {},
  1103. onEvent: () => {},
  1104. // Used to capture an error from the manifest parser. We will check the
  1105. // error before returning.
  1106. onError: (e) => {
  1107. error = e;
  1108. },
  1109. isLowLatencyMode: () => false,
  1110. updateDuration: () => {},
  1111. newDrmInfo: (stream) => {},
  1112. onManifestUpdated: () => {},
  1113. getBandwidthEstimate: () => config.abr.defaultBandwidthEstimate,
  1114. onMetadata: () => {},
  1115. disableStream: (stream) => {},
  1116. addFont: (name, url) => {},
  1117. };
  1118. parser.configure(config.manifest);
  1119. // We may have been destroyed while we were waiting on |getParser| to
  1120. // resolve.
  1121. this.ensureNotDestroyed_();
  1122. const manifest = await parser.start(uri, playerInterface);
  1123. // We may have been destroyed while we were waiting on |start| to
  1124. // resolve.
  1125. this.ensureNotDestroyed_();
  1126. // Get all the streams that are used in the manifest.
  1127. const streams =
  1128. shaka.offline.Storage.getAllStreamsFromManifest_(manifest);
  1129. // Wait for each stream to create their segment indexes.
  1130. await Promise.all(shaka.util.Iterables.map(streams, (stream) => {
  1131. return stream.createSegmentIndex();
  1132. }));
  1133. // We may have been destroyed while we were waiting on
  1134. // |createSegmentIndex| to resolve for each stream.
  1135. this.ensureNotDestroyed_();
  1136. // If we saw an error while parsing, surface the error.
  1137. if (error) {
  1138. throw error;
  1139. }
  1140. return manifest;
  1141. }
  1142. /**
  1143. * @param {string} uri
  1144. * @param {shaka.extern.Manifest} manifest
  1145. * @return {!Promise<shaka.extern.Stream>}
  1146. * @private
  1147. */
  1148. async createExternalImageStream_(uri, manifest) {
  1149. const mimeType = await this.getTextMimetype_(uri);
  1150. if (mimeType != 'text/vtt') {
  1151. throw new shaka.util.Error(
  1152. shaka.util.Error.Severity.RECOVERABLE,
  1153. shaka.util.Error.Category.TEXT,
  1154. shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,
  1155. uri);
  1156. }
  1157. goog.asserts.assert(
  1158. this.networkingEngine_, 'Need networking engine.');
  1159. const buffer = await this.getTextData_(uri,
  1160. this.networkingEngine_,
  1161. this.config_.streaming.retryParameters);
  1162. const factory = shaka.text.TextEngine.findParser(mimeType);
  1163. if (!factory) {
  1164. throw new shaka.util.Error(
  1165. shaka.util.Error.Severity.CRITICAL,
  1166. shaka.util.Error.Category.TEXT,
  1167. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  1168. mimeType);
  1169. }
  1170. const TextParser = factory();
  1171. const time = {
  1172. periodStart: 0,
  1173. segmentStart: 0,
  1174. segmentEnd: manifest.presentationTimeline.getDuration(),
  1175. vttOffset: 0,
  1176. };
  1177. const data = shaka.util.BufferUtils.toUint8(buffer);
  1178. const cues = TextParser.parseMedia(data, time, uri, /* images= */ []);
  1179. const references = [];
  1180. for (const cue of cues) {
  1181. let uris = null;
  1182. const getUris = () => {
  1183. if (uris == null) {
  1184. uris = shaka.util.ManifestParserUtils.resolveUris(
  1185. [uri], [cue.payload]);
  1186. }
  1187. return uris || [];
  1188. };
  1189. const reference = new shaka.media.SegmentReference(
  1190. cue.startTime,
  1191. cue.endTime,
  1192. getUris,
  1193. /* startByte= */ 0,
  1194. /* endByte= */ null,
  1195. /* initSegmentReference= */ null,
  1196. /* timestampOffset= */ 0,
  1197. /* appendWindowStart= */ 0,
  1198. /* appendWindowEnd= */ Infinity,
  1199. );
  1200. if (cue.payload.includes('#xywh')) {
  1201. const spriteInfo = cue.payload.split('#xywh=')[1].split(',');
  1202. if (spriteInfo.length === 4) {
  1203. reference.setThumbnailSprite({
  1204. height: parseInt(spriteInfo[3], 10),
  1205. positionX: parseInt(spriteInfo[0], 10),
  1206. positionY: parseInt(spriteInfo[1], 10),
  1207. width: parseInt(spriteInfo[2], 10),
  1208. });
  1209. }
  1210. }
  1211. references.push(reference);
  1212. }
  1213. let segmentMimeType = mimeType;
  1214. if (references.length) {
  1215. segmentMimeType = await shaka.net.NetworkingUtils.getMimeType(
  1216. references[0].getUris()[0],
  1217. this.networkingEngine_, this.config_.manifest.retryParameters);
  1218. }
  1219. return {
  1220. id: this.nextExternalStreamId_++,
  1221. originalId: null,
  1222. groupId: null,
  1223. createSegmentIndex: () => Promise.resolve(),
  1224. segmentIndex: new shaka.media.SegmentIndex(references),
  1225. mimeType: segmentMimeType || '',
  1226. codecs: '',
  1227. kind: '',
  1228. encrypted: false,
  1229. drmInfos: [],
  1230. keyIds: new Set(),
  1231. language: 'und',
  1232. originalLanguage: null,
  1233. label: null,
  1234. type: shaka.util.ManifestParserUtils.ContentType.IMAGE,
  1235. primary: false,
  1236. trickModeVideo: null,
  1237. emsgSchemeIdUris: null,
  1238. roles: [],
  1239. forced: false,
  1240. channelsCount: null,
  1241. audioSamplingRate: null,
  1242. spatialAudio: false,
  1243. closedCaptions: null,
  1244. tilesLayout: '1x1',
  1245. accessibilityPurpose: null,
  1246. external: true,
  1247. fastSwitching: false,
  1248. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  1249. segmentMimeType || '', '')]),
  1250. isAudioMuxedInVideo: false,
  1251. };
  1252. }
  1253. /**
  1254. * @param {shaka.extern.Manifest} manifest
  1255. * @param {string} uri
  1256. * @param {string} language
  1257. * @param {string} kind
  1258. * @param {string=} mimeType
  1259. * @param {string=} codec
  1260. * @private
  1261. */
  1262. async createExternalTextStream_(manifest, uri, language, kind, mimeType,
  1263. codec) {
  1264. if (!mimeType) {
  1265. mimeType = await this.getTextMimetype_(uri);
  1266. }
  1267. /** @type {shaka.extern.Stream} */
  1268. const stream = {
  1269. id: this.nextExternalStreamId_++,
  1270. originalId: null,
  1271. groupId: null,
  1272. createSegmentIndex: () => Promise.resolve(),
  1273. segmentIndex: shaka.media.SegmentIndex.forSingleSegment(
  1274. /* startTime= */ 0,
  1275. /* duration= */ manifest.presentationTimeline.getDuration(),
  1276. /* uris= */ [uri]),
  1277. mimeType: mimeType || '',
  1278. codecs: codec || '',
  1279. kind: kind,
  1280. encrypted: false,
  1281. drmInfos: [],
  1282. keyIds: new Set(),
  1283. language: language,
  1284. originalLanguage: language,
  1285. label: null,
  1286. type: shaka.util.ManifestParserUtils.ContentType.TEXT,
  1287. primary: false,
  1288. trickModeVideo: null,
  1289. emsgSchemeIdUris: null,
  1290. roles: [],
  1291. forced: false,
  1292. channelsCount: null,
  1293. audioSamplingRate: null,
  1294. spatialAudio: false,
  1295. closedCaptions: null,
  1296. accessibilityPurpose: null,
  1297. external: true,
  1298. fastSwitching: false,
  1299. fullMimeTypes: new Set([shaka.util.MimeUtils.getFullType(
  1300. mimeType || '', codec || '')]),
  1301. isAudioMuxedInVideo: false,
  1302. };
  1303. const fullMimeType = shaka.util.MimeUtils.getFullType(
  1304. stream.mimeType, stream.codecs);
  1305. const supported = shaka.text.TextEngine.isTypeSupported(fullMimeType);
  1306. if (!supported) {
  1307. throw new shaka.util.Error(
  1308. shaka.util.Error.Severity.CRITICAL,
  1309. shaka.util.Error.Category.TEXT,
  1310. shaka.util.Error.Code.MISSING_TEXT_PLUGIN,
  1311. mimeType);
  1312. }
  1313. return stream;
  1314. }
  1315. /**
  1316. * @param {string} uri
  1317. * @return {!Promise<string>}
  1318. * @private
  1319. */
  1320. async getTextMimetype_(uri) {
  1321. let mimeType;
  1322. try {
  1323. goog.asserts.assert(
  1324. this.networkingEngine_, 'Need networking engine.');
  1325. mimeType = await shaka.net.NetworkingUtils.getMimeType(uri,
  1326. this.networkingEngine_,
  1327. this.config_.streaming.retryParameters);
  1328. } catch (error) {}
  1329. if (mimeType) {
  1330. return mimeType;
  1331. }
  1332. shaka.log.error(
  1333. 'The mimeType has not been provided and it could not be deduced ' +
  1334. 'from its uri.');
  1335. throw new shaka.util.Error(
  1336. shaka.util.Error.Severity.RECOVERABLE,
  1337. shaka.util.Error.Category.TEXT,
  1338. shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,
  1339. uri);
  1340. }
  1341. /**
  1342. * @param {string} uri
  1343. * @param {!shaka.net.NetworkingEngine} netEngine
  1344. * @param {shaka.extern.RetryParameters} retryParams
  1345. * @return {!Promise<BufferSource>}
  1346. * @private
  1347. */
  1348. async getTextData_(uri, netEngine, retryParams) {
  1349. const type = shaka.net.NetworkingEngine.RequestType.SEGMENT;
  1350. const request = shaka.net.NetworkingEngine.makeRequest([uri], retryParams);
  1351. request.method = 'GET';
  1352. const response = await netEngine.request(type, request).promise;
  1353. return response.data;
  1354. }
  1355. /**
  1356. * This method is public so that it can be override in testing.
  1357. *
  1358. * @param {shaka.extern.Manifest} manifest
  1359. * @param {function(shaka.util.Error)} onError
  1360. * @param {shaka.extern.PlayerConfiguration} config
  1361. * @param {boolean} usePersistentLicense
  1362. * @return {!Promise<!shaka.drm.DrmEngine>}
  1363. */
  1364. async createDrmEngine(manifest, onError, config, usePersistentLicense) {
  1365. goog.asserts.assert(
  1366. this.networkingEngine_,
  1367. 'Cannot call |createDrmEngine| after |destroy|');
  1368. /** @type {!shaka.drm.DrmEngine} */
  1369. const drmEngine = new shaka.drm.DrmEngine({
  1370. netEngine: this.networkingEngine_,
  1371. onError: onError,
  1372. onKeyStatus: () => {},
  1373. onExpirationUpdated: () => {},
  1374. onEvent: () => {},
  1375. });
  1376. drmEngine.configure(config.drm);
  1377. await drmEngine.initForStorage(manifest.variants, usePersistentLicense);
  1378. await drmEngine.createOrLoad();
  1379. return drmEngine;
  1380. }
  1381. /**
  1382. * Converts manifest Streams to database Streams.
  1383. *
  1384. * @param {!shaka.offline.DownloadManager} downloader
  1385. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  1386. * @param {!shaka.drm.DrmEngine} drmEngine
  1387. * @param {shaka.extern.Manifest} manifest
  1388. * @param {shaka.extern.PlayerConfiguration} config
  1389. * @return {{
  1390. * streams: !Array<shaka.extern.StreamDB>,
  1391. * toDownload: !Array<!shaka.offline.DownloadInfo>
  1392. * }}
  1393. * @private
  1394. */
  1395. createStreams_(downloader, estimator, drmEngine, manifest, config) {
  1396. // Download infos are stored based on their refId, to deduplicate them.
  1397. /** @type {!Map<string, !shaka.offline.DownloadInfo>} */
  1398. const toDownload = new Map();
  1399. // Find the streams we want to download and create a stream db instance
  1400. // for each of them.
  1401. const streamSet =
  1402. shaka.offline.Storage.getAllStreamsFromManifest_(manifest);
  1403. const streamDBs = new Map();
  1404. for (const stream of streamSet) {
  1405. const streamDB = this.createStream_(
  1406. downloader, estimator, manifest, stream, config, toDownload);
  1407. streamDBs.set(stream.id, streamDB);
  1408. }
  1409. // Connect streams and variants together.
  1410. for (const variant of manifest.variants) {
  1411. if (variant.audio) {
  1412. streamDBs.get(variant.audio.id).variantIds.push(variant.id);
  1413. }
  1414. if (variant.video) {
  1415. streamDBs.get(variant.video.id).variantIds.push(variant.id);
  1416. }
  1417. }
  1418. return {
  1419. streams: Array.from(streamDBs.values()),
  1420. toDownload: Array.from(toDownload.values()),
  1421. };
  1422. }
  1423. /**
  1424. * Converts a manifest stream to a database stream. This will search the
  1425. * segment index and add all the segments to the download infos.
  1426. *
  1427. * @param {!shaka.offline.DownloadManager} downloader
  1428. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  1429. * @param {shaka.extern.Manifest} manifest
  1430. * @param {shaka.extern.Stream} stream
  1431. * @param {shaka.extern.PlayerConfiguration} config
  1432. * @param {!Map<string, !shaka.offline.DownloadInfo>} toDownload
  1433. * @return {shaka.extern.StreamDB}
  1434. * @private
  1435. */
  1436. createStream_(downloader, estimator, manifest, stream, config, toDownload) {
  1437. /** @type {shaka.extern.StreamDB} */
  1438. const streamDb = {
  1439. id: stream.id,
  1440. originalId: stream.originalId,
  1441. groupId: stream.groupId,
  1442. primary: stream.primary,
  1443. type: stream.type,
  1444. mimeType: stream.mimeType,
  1445. codecs: stream.codecs,
  1446. frameRate: stream.frameRate,
  1447. pixelAspectRatio: stream.pixelAspectRatio,
  1448. hdr: stream.hdr,
  1449. colorGamut: stream.colorGamut,
  1450. videoLayout: stream.videoLayout,
  1451. kind: stream.kind,
  1452. language: stream.language,
  1453. originalLanguage: stream.originalLanguage,
  1454. label: stream.label,
  1455. width: stream.width || null,
  1456. height: stream.height || null,
  1457. encrypted: stream.encrypted,
  1458. keyIds: stream.keyIds,
  1459. segments: [],
  1460. variantIds: [],
  1461. roles: stream.roles,
  1462. forced: stream.forced,
  1463. channelsCount: stream.channelsCount,
  1464. audioSamplingRate: stream.audioSamplingRate,
  1465. spatialAudio: stream.spatialAudio,
  1466. closedCaptions: stream.closedCaptions,
  1467. tilesLayout: stream.tilesLayout,
  1468. mssPrivateData: stream.mssPrivateData,
  1469. external: stream.external,
  1470. fastSwitching: stream.fastSwitching,
  1471. isAudioMuxedInVideo: stream.isAudioMuxedInVideo,
  1472. };
  1473. const startTime =
  1474. manifest.presentationTimeline.getSegmentAvailabilityStart();
  1475. const numberOfParallelDownloads = config.offline.numberOfParallelDownloads;
  1476. let groupId = numberOfParallelDownloads === 0 ? stream.id : 0;
  1477. shaka.offline.Storage.forEachSegment_(stream, startTime, (segment, pos) => {
  1478. const pendingSegmentRefId =
  1479. shaka.offline.DownloadInfo.idForSegmentRef(segment);
  1480. let pendingInitSegmentRefId = undefined;
  1481. // Set up the download for the segment, which will be downloaded later,
  1482. // perhaps in a service worker.
  1483. if (!toDownload.has(pendingSegmentRefId)) {
  1484. const estimateId = downloader.addDownloadEstimate(
  1485. estimator.getSegmentEstimate(stream.id, segment));
  1486. const segmentDownload = new shaka.offline.DownloadInfo(
  1487. segment,
  1488. estimateId,
  1489. groupId,
  1490. /* isInitSegment= */ false,
  1491. pos);
  1492. toDownload.set(pendingSegmentRefId, segmentDownload);
  1493. }
  1494. // Set up the download for the init segment, similarly, if there is one.
  1495. if (segment.initSegmentReference) {
  1496. pendingInitSegmentRefId = shaka.offline.DownloadInfo.idForSegmentRef(
  1497. segment.initSegmentReference);
  1498. if (!toDownload.has(pendingInitSegmentRefId)) {
  1499. const estimateId = downloader.addDownloadEstimate(
  1500. estimator.getInitSegmentEstimate(stream.id));
  1501. const initDownload = new shaka.offline.DownloadInfo(
  1502. segment.initSegmentReference,
  1503. estimateId,
  1504. groupId,
  1505. /* isInitSegment= */ true,
  1506. pos);
  1507. toDownload.set(pendingInitSegmentRefId, initDownload);
  1508. }
  1509. }
  1510. /** @type {!shaka.extern.SegmentDB} */
  1511. const segmentDB = {
  1512. pendingInitSegmentRefId,
  1513. initSegmentKey: pendingInitSegmentRefId ? 0 : null,
  1514. startTime: segment.startTime,
  1515. endTime: segment.endTime,
  1516. appendWindowStart: segment.appendWindowStart,
  1517. appendWindowEnd: segment.appendWindowEnd,
  1518. timestampOffset: segment.timestampOffset,
  1519. tilesLayout: segment.tilesLayout,
  1520. pendingSegmentRefId,
  1521. dataKey: 0,
  1522. mimeType: segment.mimeType,
  1523. codecs: segment.codecs,
  1524. thumbnailSprite: segment.thumbnailSprite,
  1525. };
  1526. streamDb.segments.push(segmentDB);
  1527. if (numberOfParallelDownloads !== 0) {
  1528. groupId = (groupId + 1) % numberOfParallelDownloads;
  1529. }
  1530. });
  1531. return streamDb;
  1532. }
  1533. /**
  1534. * @param {shaka.extern.Stream} stream
  1535. * @param {number} startTime
  1536. * @param {function(!shaka.media.SegmentReference, number)} callback
  1537. * @private
  1538. */
  1539. static forEachSegment_(stream, startTime, callback) {
  1540. /** @type {?number} */
  1541. let i = stream.segmentIndex.find(startTime);
  1542. if (i == null) {
  1543. return;
  1544. }
  1545. /** @type {?shaka.media.SegmentReference} */
  1546. let ref = stream.segmentIndex.get(i);
  1547. while (ref) {
  1548. callback(ref, i);
  1549. ref = stream.segmentIndex.get(++i);
  1550. }
  1551. }
  1552. /**
  1553. * Throws an error if the object is destroyed.
  1554. * @private
  1555. */
  1556. ensureNotDestroyed_() {
  1557. if (this.destroyer_.destroyed()) {
  1558. throw new shaka.util.Error(
  1559. shaka.util.Error.Severity.CRITICAL,
  1560. shaka.util.Error.Category.STORAGE,
  1561. shaka.util.Error.Code.OPERATION_ABORTED);
  1562. }
  1563. }
  1564. /**
  1565. * Used by functions that need storage support to ensure that the current
  1566. * platform has storage support before continuing. This should only be
  1567. * needed to be used at the start of public methods.
  1568. *
  1569. * @private
  1570. */
  1571. requireSupport_() {
  1572. if (!shaka.offline.Storage.support()) {
  1573. throw new shaka.util.Error(
  1574. shaka.util.Error.Severity.CRITICAL,
  1575. shaka.util.Error.Category.STORAGE,
  1576. shaka.util.Error.Code.STORAGE_NOT_SUPPORTED);
  1577. }
  1578. }
  1579. /**
  1580. * Perform an action. Track the action's progress so that when we destroy
  1581. * we will wait until all the actions have completed before allowing destroy
  1582. * to resolve.
  1583. *
  1584. * @param {!Promise<T>} action
  1585. * @return {!Promise<T>}
  1586. * @template T
  1587. * @private
  1588. */
  1589. async startOperation_(action) {
  1590. this.openOperations_.push(action);
  1591. try {
  1592. // Await |action| so we can use the finally statement to remove |action|
  1593. // from |openOperations_| when we still have a reference to |action|.
  1594. return await action;
  1595. } finally {
  1596. shaka.util.ArrayUtils.remove(this.openOperations_, action);
  1597. }
  1598. }
  1599. /**
  1600. * The equivalent of startOperation_, but for abortable operations.
  1601. *
  1602. * @param {!shaka.extern.IAbortableOperation<T>} action
  1603. * @return {!shaka.extern.IAbortableOperation<T>}
  1604. * @template T
  1605. * @private
  1606. */
  1607. startAbortableOperation_(action) {
  1608. const promise = action.promise;
  1609. this.openOperations_.push(promise);
  1610. // Remove the open operation once the action has completed. So that we
  1611. // can still return the AbortableOperation, this is done using a |finally|
  1612. // block, rather than awaiting the result.
  1613. return action.finally(() => {
  1614. shaka.util.ArrayUtils.remove(this.openOperations_, promise);
  1615. });
  1616. }
  1617. /**
  1618. * @param {shaka.extern.ManifestDB} manifest
  1619. * @return {!Array<number>}
  1620. * @private
  1621. */
  1622. static getAllSegmentIds_(manifest) {
  1623. /** @type {!Set<number>} */
  1624. const ids = new Set();
  1625. // Get every segment for every stream in the manifest.
  1626. for (const stream of manifest.streams) {
  1627. for (const segment of stream.segments) {
  1628. if (segment.initSegmentKey != null) {
  1629. ids.add(segment.initSegmentKey);
  1630. }
  1631. ids.add(segment.dataKey);
  1632. }
  1633. }
  1634. return Array.from(ids);
  1635. }
  1636. /**
  1637. * Delete the on-disk storage and all the content it contains. This should not
  1638. * be done in normal circumstances. Only do it when storage is rendered
  1639. * unusable, such as by a version mismatch. No business logic will be run, and
  1640. * licenses will not be released.
  1641. *
  1642. * @return {!Promise}
  1643. * @export
  1644. */
  1645. static async deleteAll() {
  1646. /** @type {!shaka.offline.StorageMuxer} */
  1647. const muxer = new shaka.offline.StorageMuxer();
  1648. try {
  1649. // Wipe all content from all storage mechanisms.
  1650. await muxer.erase();
  1651. } finally {
  1652. // Destroy the muxer, whether or not erase() succeeded.
  1653. await muxer.destroy();
  1654. }
  1655. }
  1656. /**
  1657. * @param {!shaka.net.NetworkingEngine} net
  1658. * @param {!shaka.extern.DrmConfiguration} drmConfig
  1659. * @param {!shaka.offline.StorageMuxer} muxer
  1660. * @param {shaka.extern.ManifestDB} manifestDb
  1661. * @return {!Promise}
  1662. * @private
  1663. */
  1664. static async deleteLicenseFor_(net, drmConfig, muxer, manifestDb) {
  1665. if (!manifestDb.drmInfo) {
  1666. return;
  1667. }
  1668. const sessionIdCell = muxer.getEmeSessionCell();
  1669. /** @type {!Array<shaka.extern.EmeSessionDB>} */
  1670. const sessions = manifestDb.sessionIds.map((sessionId) => {
  1671. return {
  1672. sessionId: sessionId,
  1673. keySystem: manifestDb.drmInfo.keySystem,
  1674. licenseUri: manifestDb.drmInfo.licenseServerUri,
  1675. serverCertificate: manifestDb.drmInfo.serverCertificate,
  1676. audioCapabilities: shaka.offline.Storage.getCapabilities_(
  1677. manifestDb,
  1678. /* isVideo= */ false),
  1679. videoCapabilities: shaka.offline.Storage.getCapabilities_(
  1680. manifestDb,
  1681. /* isVideo= */ true),
  1682. };
  1683. });
  1684. // Try to delete the sessions; any sessions that weren't deleted get stored
  1685. // in the database so we can try to remove them again later. This allows us
  1686. // to still delete the stored content but not "forget" about these sessions.
  1687. // Later, we can remove the sessions to free up space.
  1688. const deleter = new shaka.offline.SessionDeleter();
  1689. const deletedSessionIds = await deleter.delete(drmConfig, net, sessions);
  1690. await sessionIdCell.remove(deletedSessionIds);
  1691. await sessionIdCell.add(sessions.filter(
  1692. (session) => !deletedSessionIds.includes(session.sessionId)));
  1693. }
  1694. /**
  1695. * Get the set of all streams in |manifest|.
  1696. *
  1697. * @param {shaka.extern.Manifest} manifest
  1698. * @return {!Set<shaka.extern.Stream>}
  1699. * @private
  1700. */
  1701. static getAllStreamsFromManifest_(manifest) {
  1702. /** @type {!Set<shaka.extern.Stream>} */
  1703. const set = new Set();
  1704. for (const variant of manifest.variants) {
  1705. if (variant.audio) {
  1706. set.add(variant.audio);
  1707. }
  1708. if (variant.video) {
  1709. set.add(variant.video);
  1710. }
  1711. }
  1712. for (const text of manifest.textStreams) {
  1713. set.add(text);
  1714. }
  1715. for (const image of manifest.imageStreams) {
  1716. set.add(image);
  1717. }
  1718. return set;
  1719. }
  1720. /**
  1721. * Go over a manifest and issue warnings for any suspicious properties.
  1722. *
  1723. * @param {shaka.extern.Manifest} manifest
  1724. * @private
  1725. */
  1726. static validateManifest_(manifest) {
  1727. const videos = new Set(manifest.variants.map((v) => v.video));
  1728. const audios = new Set(manifest.variants.map((v) => v.audio));
  1729. const texts = manifest.textStreams;
  1730. if (videos.size > 1) {
  1731. shaka.log.warning('Multiple video tracks selected to be stored');
  1732. }
  1733. for (const audio1 of audios) {
  1734. for (const audio2 of audios) {
  1735. if (audio1 != audio2 && audio1.language == audio2.language) {
  1736. shaka.log.warning(
  1737. 'Similar audio tracks were selected to be stored',
  1738. audio1.id,
  1739. audio2.id);
  1740. }
  1741. }
  1742. }
  1743. for (const text1 of texts) {
  1744. for (const text2 of texts) {
  1745. if (text1 != text2 && text1.language == text2.language) {
  1746. shaka.log.warning(
  1747. 'Similar text tracks were selected to be stored',
  1748. text1.id,
  1749. text2.id);
  1750. }
  1751. }
  1752. }
  1753. }
  1754. };
  1755. shaka.offline.Storage.defaultSystemIds_ = new Map()
  1756. .set('org.w3.clearkey', '1077efecc0b24d02ace33c1e52e2fb4b')
  1757. .set('com.widevine.alpha', 'edef8ba979d64acea3c827dcd51d21ed')
  1758. .set('com.microsoft.playready', '9a04f07998404286ab92e65be0885f95')
  1759. .set('com.microsoft.playready.recommendation',
  1760. '9a04f07998404286ab92e65be0885f95')
  1761. .set('com.microsoft.playready.software',
  1762. '9a04f07998404286ab92e65be0885f95')
  1763. .set('com.microsoft.playready.hardware',
  1764. '9a04f07998404286ab92e65be0885f95')
  1765. .set('com.huawei.wiseplay', '3d5e6d359b9a41e8b843dd3c6e72c42c');
  1766. shaka.Player.registerSupportPlugin('offline', shaka.offline.Storage.support);