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.Deprecate');
  9. goog.require('shaka.Player');
  10. goog.require('shaka.log');
  11. goog.require('shaka.media.DrmEngine');
  12. goog.require('shaka.media.ManifestParser');
  13. goog.require('shaka.net.NetworkingEngine');
  14. goog.require('shaka.offline.DownloadManager');
  15. goog.require('shaka.offline.OfflineUri');
  16. goog.require('shaka.offline.SessionDeleter');
  17. goog.require('shaka.offline.StorageMuxer');
  18. goog.require('shaka.offline.StoredContentUtils');
  19. goog.require('shaka.offline.StreamBandwidthEstimator');
  20. goog.require('shaka.util.AbortableOperation');
  21. goog.require('shaka.util.ArrayUtils');
  22. goog.require('shaka.util.ConfigUtils');
  23. goog.require('shaka.util.Destroyer');
  24. goog.require('shaka.util.Error');
  25. goog.require('shaka.util.Functional');
  26. goog.require('shaka.util.IDestroyable');
  27. goog.require('shaka.util.Iterables');
  28. goog.require('shaka.util.MimeUtils');
  29. goog.require('shaka.util.Networking');
  30. goog.require('shaka.util.Platform');
  31. goog.require('shaka.util.PlayerConfiguration');
  32. goog.require('shaka.util.StreamUtils');
  33. goog.requireType('shaka.media.InitSegmentReference');
  34. goog.requireType('shaka.media.SegmentReference');
  35. goog.requireType('shaka.offline.StorageCellHandle');
  36. /**
  37. * @summary
  38. * This manages persistent offline data including storage, listing, and deleting
  39. * stored manifests. Playback of offline manifests are done through the Player
  40. * using a special URI (see shaka.offline.OfflineUri).
  41. *
  42. * First, check support() to see if offline is supported by the platform.
  43. * Second, configure() the storage object with callbacks to your application.
  44. * Third, call store(), remove(), or list() as needed.
  45. * When done, call destroy().
  46. *
  47. * @implements {shaka.util.IDestroyable}
  48. * @export
  49. */
  50. shaka.offline.Storage = class {
  51. /**
  52. * @param {!shaka.Player=} player
  53. * A player instance to share a networking engine and configuration with.
  54. * When initializing with a player, storage is only valid as long as
  55. * |destroy| has not been called on the player instance. When omitted,
  56. * storage will manage its own networking engine and configuration.
  57. */
  58. constructor(player) {
  59. // It is an easy mistake to make to pass a Player proxy from CastProxy.
  60. // Rather than throw a vague exception later, throw an explicit and clear
  61. // one now.
  62. //
  63. // TODO(vaage): After we decide whether or not we want to support
  64. // initializing storage with a player proxy, we should either remove
  65. // this error or rename the error.
  66. if (player && player.constructor != shaka.Player) {
  67. throw new shaka.util.Error(
  68. shaka.util.Error.Severity.CRITICAL,
  69. shaka.util.Error.Category.STORAGE,
  70. shaka.util.Error.Code.LOCAL_PLAYER_INSTANCE_REQUIRED);
  71. }
  72. /** @private {?shaka.extern.PlayerConfiguration} */
  73. this.config_ = null;
  74. /** @private {shaka.net.NetworkingEngine} */
  75. this.networkingEngine_ = null;
  76. // Initialize |config_| and |networkingEngine_| based on whether or not
  77. // we were given a player instance.
  78. if (player) {
  79. this.config_ = player.getSharedConfiguration();
  80. this.networkingEngine_ = player.getNetworkingEngine();
  81. goog.asserts.assert(
  82. this.networkingEngine_,
  83. 'Storage should not be initialized with a player that had ' +
  84. '|destroy| called on it.');
  85. } else {
  86. this.config_ = shaka.util.PlayerConfiguration.createDefault();
  87. this.networkingEngine_ = new shaka.net.NetworkingEngine();
  88. }
  89. /**
  90. * A list of segment ids for all the segments that were added during the
  91. * current store. If the store fails or is aborted, these need to be
  92. * removed from storage.
  93. * @private {!Array.<number>}
  94. */
  95. this.segmentsFromStore_ = [];
  96. /**
  97. * A list of open operations that are being performed by this instance of
  98. * |shaka.offline.Storage|.
  99. *
  100. * @private {!Array.<!Promise>}
  101. */
  102. this.openOperations_ = [];
  103. /**
  104. * A list of open download managers that are being used to download things.
  105. *
  106. * @private {!Array.<!shaka.offline.DownloadManager>}
  107. */
  108. this.openDownloadManagers_ = [];
  109. /**
  110. * Storage should only destroy the networking engine if it was initialized
  111. * without a player instance. Store this as a flag here to avoid including
  112. * the player object in the destoyer's closure.
  113. *
  114. * @type {boolean}
  115. */
  116. const destroyNetworkingEngine = !player;
  117. /** @private {!shaka.util.Destroyer} */
  118. this.destroyer_ = new shaka.util.Destroyer(async () => {
  119. // Cancel all in-progress store operations.
  120. await Promise.all(this.openDownloadManagers_.map((dl) => dl.abortAll()));
  121. // Wait for all remaining open operations to end. Wrap each operations so
  122. // that a single rejected promise won't cause |Promise.all| to return
  123. // early or to return a rejected Promise.
  124. const noop = () => {};
  125. const awaits = [];
  126. for (const op of this.openOperations_) {
  127. awaits.push(op.then(noop, noop));
  128. }
  129. await Promise.all(awaits);
  130. // Wait until after all the operations have finished before we destroy
  131. // the networking engine to avoid any unexpected errors.
  132. if (destroyNetworkingEngine) {
  133. await this.networkingEngine_.destroy();
  134. }
  135. // Drop all references to internal objects to help with GC.
  136. this.config_ = null;
  137. this.networkingEngine_ = null;
  138. });
  139. }
  140. /**
  141. * Gets whether offline storage is supported. Returns true if offline storage
  142. * is supported for clear content. Support for offline storage of encrypted
  143. * content will not be determined until storage is attempted.
  144. *
  145. * @return {boolean}
  146. * @export
  147. */
  148. static support() {
  149. // Our Storage system is useless without MediaSource. MediaSource allows us
  150. // to pull data from anywhere (including our Storage system) and feed it to
  151. // the video element.
  152. if (!shaka.util.Platform.supportsMediaSource()) {
  153. return false;
  154. }
  155. return shaka.offline.StorageMuxer.support();
  156. }
  157. /**
  158. * @override
  159. * @export
  160. */
  161. destroy() {
  162. return this.destroyer_.destroy();
  163. }
  164. /**
  165. * Sets configuration values for Storage. This is associated with
  166. * Player.configure and will change the player instance given at
  167. * initialization.
  168. *
  169. * @param {string|!Object} config This should either be a field name or an
  170. * object following the form of {@link shaka.extern.PlayerConfiguration},
  171. * where you may omit any field you do not wish to change.
  172. * @param {*=} value This should be provided if the previous parameter
  173. * was a string field name.
  174. * @return {boolean}
  175. * @export
  176. */
  177. configure(config, value) {
  178. goog.asserts.assert(typeof(config) == 'object' || arguments.length == 2,
  179. 'String configs should have values!');
  180. // ('fieldName', value) format
  181. if (arguments.length == 2 && typeof(config) == 'string') {
  182. config = shaka.util.ConfigUtils.convertToConfigObject(config, value);
  183. }
  184. goog.asserts.assert(typeof(config) == 'object', 'Should be an object!');
  185. // Deprecate 'manifest.dash.defaultPresentationDelay' configuration.
  186. if (config['manifest'] && config['manifest']['dash'] &&
  187. 'defaultPresentationDelay' in config['manifest']['dash']) {
  188. shaka.Deprecate.deprecateFeature(4,
  189. 'manifest.dash.defaultPresentationDelay configuration',
  190. 'Please Use manifest.defaultPresentationDelay instead.');
  191. config['manifest']['defaultPresentationDelay'] =
  192. config['manifest']['dash']['defaultPresentationDelay'];
  193. delete config['manifest']['dash']['defaultPresentationDelay'];
  194. }
  195. goog.asserts.assert(
  196. this.config_, 'Cannot reconfigure stroage after calling destroy.');
  197. return shaka.util.PlayerConfiguration.mergeConfigObjects(
  198. /* destination= */ this.config_, /* updates= */ config );
  199. }
  200. /**
  201. * Return a copy of the current configuration. Modifications of the returned
  202. * value will not affect the Storage instance's active configuration. You
  203. * must call storage.configure() to make changes.
  204. *
  205. * @return {shaka.extern.PlayerConfiguration}
  206. * @export
  207. */
  208. getConfiguration() {
  209. goog.asserts.assert(this.config_, 'Config must not be null!');
  210. const ret = shaka.util.PlayerConfiguration.createDefault();
  211. shaka.util.PlayerConfiguration.mergeConfigObjects(
  212. ret, this.config_, shaka.util.PlayerConfiguration.createDefault());
  213. return ret;
  214. }
  215. /**
  216. * Return the networking engine that storage is using. If storage was
  217. * initialized with a player instance, then the networking engine returned
  218. * will be the same as |player.getNetworkingEngine()|.
  219. *
  220. * The returned value will only be null if |destroy| was called before
  221. * |getNetworkingEngine|.
  222. *
  223. * @return {shaka.net.NetworkingEngine}
  224. * @export
  225. */
  226. getNetworkingEngine() {
  227. return this.networkingEngine_;
  228. }
  229. /**
  230. * Stores the given manifest. If the content is encrypted, and encrypted
  231. * content cannot be stored on this platform, the Promise will be rejected
  232. * with error code 6001, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE.
  233. * Multiple assets can be downloaded at the same time, but note that since
  234. * the storage instance has a single networking engine, multiple storage
  235. * objects will be necessary if some assets require unique network filters.
  236. * This snapshots the storage config at the time of the call, so it will not
  237. * honor any changes to config mid-store operation.
  238. *
  239. * @param {string} uri The URI of the manifest to store.
  240. * @param {!Object=} appMetadata An arbitrary object from the application
  241. * that will be stored along-side the offline content. Use this for any
  242. * application-specific metadata you need associated with the stored
  243. * content. For details on the data types that can be stored here, please
  244. * refer to {@link https://bit.ly/StructClone}
  245. * @param {string=} mimeType
  246. * The mime type for the content |manifestUri| points to.
  247. * @return {!shaka.extern.IAbortableOperation.<shaka.extern.StoredContent>}
  248. * An AbortableOperation that resolves with a structure representing what
  249. * was stored. The "offlineUri" member is the URI that should be given to
  250. * Player.load() to play this piece of content offline. The "appMetadata"
  251. * member is the appMetadata argument you passed to store().
  252. * If you want to cancel this download, call the "abort" method on
  253. * AbortableOperation.
  254. * @export
  255. */
  256. store(uri, appMetadata, mimeType) {
  257. goog.asserts.assert(
  258. this.networkingEngine_,
  259. 'Cannot call |downloadManifest_| after calling |destroy|.');
  260. // Get a copy of the current config.
  261. const config = this.getConfiguration();
  262. const getParser = async () => {
  263. goog.asserts.assert(
  264. this.networkingEngine_, 'Should not call |store| after |destroy|');
  265. const factory = await shaka.media.ManifestParser.getFactory(
  266. uri,
  267. this.networkingEngine_,
  268. config.manifest.retryParameters,
  269. mimeType || null);
  270. return shaka.util.Functional.callFactory(factory);
  271. };
  272. /** @type {!shaka.offline.DownloadManager} */
  273. const downloader =
  274. new shaka.offline.DownloadManager(this.networkingEngine_);
  275. this.openDownloadManagers_.push(downloader);
  276. const storeOp = this.store_(
  277. uri, appMetadata || {}, 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. // Provide a temporary shim for "then" for backward compatibility.
  285. /** @type {!Object} */ (abortableStoreOp)['then'] = (onSuccess) => {
  286. shaka.Deprecate.deprecateFeature(4,
  287. 'shaka.offline.Storage.store.then',
  288. 'Storage operations now return a shaka.util.AbortableOperation, ' +
  289. 'rather than a promise. Please update to conform to this new API; ' +
  290. 'you can use the |chain| method instead.');
  291. return abortableStoreOp.promise.then(onSuccess);
  292. };
  293. return this.startAbortableOperation_(abortableStoreOp);
  294. }
  295. /**
  296. * Returns true if an asset is currently downloading.
  297. *
  298. * @return {boolean}
  299. * @deprecated
  300. * @export
  301. */
  302. getStoreInProgress() {
  303. shaka.Deprecate.deprecateFeature(4,
  304. 'shaka.offline.Storage.getStoreInProgress',
  305. 'Multiple concurrent downloads are now supported.');
  306. return false;
  307. }
  308. /**
  309. * See |shaka.offline.Storage.store| for details.
  310. *
  311. * @param {string} uri
  312. * @param {!Object} appMetadata
  313. * @param {function():!Promise.<shaka.extern.ManifestParser>} getParser
  314. * @param {shaka.extern.PlayerConfiguration} config
  315. * @param {!shaka.offline.DownloadManager} downloader
  316. * @return {!Promise.<shaka.extern.StoredContent>}
  317. * @private
  318. */
  319. async store_(uri, appMetadata, getParser, config, downloader) {
  320. this.requireSupport_();
  321. // Since we will need to use |parser|, |drmEngine|, |activeHandle|, and
  322. // |muxer| in the catch/finally blocks, we need to define them out here.
  323. // Since they may not get initialized when we enter the catch/finally block,
  324. // we need to assume that they may be null/undefined when we get there.
  325. /** @type {?shaka.extern.ManifestParser} */
  326. let parser = null;
  327. /** @type {?shaka.media.DrmEngine} */
  328. let drmEngine = null;
  329. /** @type {shaka.offline.StorageMuxer} */
  330. const muxer = new shaka.offline.StorageMuxer();
  331. /** @type {?shaka.offline.StorageCellHandle} */
  332. let activeHandle = null;
  333. // This will be used to store any errors from drm engine. Whenever drm
  334. // engine is passed to another function to do work, we should check if this
  335. // was set.
  336. let drmError = null;
  337. try {
  338. parser = await getParser();
  339. const manifest = await this.parseManifest(uri, parser, config);
  340. // Check if we were asked to destroy ourselves while we were "away"
  341. // downloading the manifest.
  342. this.ensureNotDestroyed_();
  343. // Check if we can even download this type of manifest before trying to
  344. // create the drm engine.
  345. const canDownload = !manifest.presentationTimeline.isLive() &&
  346. !manifest.presentationTimeline.isInProgress();
  347. if (!canDownload) {
  348. throw new shaka.util.Error(
  349. shaka.util.Error.Severity.CRITICAL,
  350. shaka.util.Error.Category.STORAGE,
  351. shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE,
  352. uri);
  353. }
  354. drmEngine = await this.createDrmEngine(
  355. manifest,
  356. (e) => { drmError = drmError || e; },
  357. config);
  358. // We could have been asked to destroy ourselves while we were "away"
  359. // creating the drm engine.
  360. this.ensureNotDestroyed_();
  361. if (drmError) {
  362. throw drmError;
  363. }
  364. await this.filterManifest_(manifest, drmEngine, config);
  365. await muxer.init();
  366. this.ensureNotDestroyed_();
  367. // Get the cell that we are saving the manifest to. Once we get a cell
  368. // we will only reference the cell and not the muxer so that the manifest
  369. // and segments will all be saved to the same cell.
  370. activeHandle = await muxer.getActive();
  371. this.ensureNotDestroyed_();
  372. goog.asserts.assert(drmEngine, 'drmEngine should be non-null here.');
  373. const manifestDB = await this.downloadManifest_(
  374. activeHandle.cell, drmEngine, manifest, uri, appMetadata, config,
  375. downloader);
  376. this.ensureNotDestroyed_();
  377. if (drmError) {
  378. throw drmError;
  379. }
  380. const ids = await activeHandle.cell.addManifests([manifestDB]);
  381. this.ensureNotDestroyed_();
  382. const offlineUri = shaka.offline.OfflineUri.manifest(
  383. activeHandle.path.mechanism, activeHandle.path.cell, ids[0]);
  384. return shaka.offline.StoredContentUtils.fromManifestDB(
  385. offlineUri, manifestDB);
  386. } catch (e) {
  387. // If we did start saving some data, we need to remove it all to avoid
  388. // wasting storage. However if the muxer did not manage to initialize,
  389. // then we won't have an active cell to remove the segments from.
  390. if (activeHandle) {
  391. await activeHandle.cell.removeSegments(
  392. this.segmentsFromStore_, () => {});
  393. }
  394. // If we already had an error, ignore this error to avoid hiding
  395. // the original error.
  396. throw drmError || e;
  397. } finally {
  398. this.segmentsFromStore_ = [];
  399. await muxer.destroy();
  400. if (parser) {
  401. await parser.stop();
  402. }
  403. if (drmEngine) {
  404. await drmEngine.destroy();
  405. }
  406. }
  407. }
  408. /**
  409. * Filter |manifest| such that it will only contain the variants and text
  410. * streams that we want to store and can actually play.
  411. *
  412. * @param {shaka.extern.Manifest} manifest
  413. * @param {!shaka.media.DrmEngine} drmEngine
  414. * @param {shaka.extern.PlayerConfiguration} config
  415. * @return {!Promise}
  416. * @private
  417. */
  418. async filterManifest_(manifest, drmEngine, config) {
  419. // Filter the manifest based on the restrictions given in the player
  420. // configuration.
  421. const maxHwRes = {width: Infinity, height: Infinity};
  422. shaka.util.StreamUtils.filterByRestrictions(
  423. manifest, config.restrictions, maxHwRes);
  424. // Filter the manifest based on what we know MediaCapabilities will be able
  425. // to play later (no point storing something we can't play).
  426. await shaka.util.StreamUtils.filterManifestByMediaCapabilities(
  427. manifest, config.offline.usePersistentLicense);
  428. // Gather all tracks.
  429. const allTracks = [];
  430. // Choose the codec that has the lowest average bandwidth.
  431. const preferredAudioChannelCount = config.preferredAudioChannelCount;
  432. const preferredDecodingAttributes = config.preferredDecodingAttributes;
  433. const preferredVideoCodecs = config.preferredVideoCodecs;
  434. const preferredAudioCodecs = config.preferredAudioCodecs;
  435. shaka.util.StreamUtils.chooseCodecsAndFilterManifest(
  436. manifest, preferredVideoCodecs, preferredAudioCodecs,
  437. preferredAudioChannelCount, preferredDecodingAttributes);
  438. for (const variant of manifest.variants) {
  439. goog.asserts.assert(
  440. shaka.util.StreamUtils.isPlayable(variant),
  441. 'We should have already filtered by "is playable"');
  442. allTracks.push(shaka.util.StreamUtils.variantToTrack(variant));
  443. }
  444. for (const text of manifest.textStreams) {
  445. allTracks.push(shaka.util.StreamUtils.textStreamToTrack(text));
  446. }
  447. for (const image of manifest.imageStreams) {
  448. allTracks.push(shaka.util.StreamUtils.imageStreamToTrack(image));
  449. }
  450. // Let the application choose which tracks to store.
  451. const chosenTracks =
  452. await config.offline.trackSelectionCallback(allTracks);
  453. const duration = manifest.presentationTimeline.getDuration();
  454. let sizeEstimate = 0;
  455. for (const track of chosenTracks) {
  456. const trackSize = track.bandwidth * duration / 8;
  457. sizeEstimate += trackSize;
  458. }
  459. try {
  460. const allowedDownload =
  461. await config.offline.downloadSizeCallback(sizeEstimate);
  462. if (!allowedDownload) {
  463. throw new shaka.util.Error(
  464. shaka.util.Error.Severity.CRITICAL,
  465. shaka.util.Error.Category.STORAGE,
  466. shaka.util.Error.Code.STORAGE_LIMIT_REACHED);
  467. }
  468. } catch (e) {
  469. // It is necessary to be able to catch the STORAGE_LIMIT_REACHED error
  470. if (e instanceof shaka.util.Error) {
  471. throw e;
  472. }
  473. shaka.log.warning(
  474. 'downloadSizeCallback has produced an unexpected error', e);
  475. throw new shaka.util.Error(
  476. shaka.util.Error.Severity.CRITICAL,
  477. shaka.util.Error.Category.STORAGE,
  478. shaka.util.Error.Code.DOWNLOAD_SIZE_CALLBACK_ERROR);
  479. }
  480. /** @type {!Set.<number>} */
  481. const variantIds = new Set();
  482. /** @type {!Set.<number>} */
  483. const textIds = new Set();
  484. /** @type {!Set.<number>} */
  485. const imageIds = new Set();
  486. // Collect the IDs of the chosen tracks.
  487. for (const track of chosenTracks) {
  488. if (track.type == 'variant') {
  489. variantIds.add(track.id);
  490. }
  491. if (track.type == 'text') {
  492. textIds.add(track.id);
  493. }
  494. if (track.type == 'image') {
  495. imageIds.add(track.id);
  496. }
  497. }
  498. // Filter the manifest to keep only what the app chose.
  499. manifest.variants =
  500. manifest.variants.filter((variant) => variantIds.has(variant.id));
  501. manifest.textStreams =
  502. manifest.textStreams.filter((stream) => textIds.has(stream.id));
  503. manifest.imageStreams =
  504. manifest.imageStreams.filter((stream) => imageIds.has(stream.id));
  505. // Check the post-filtered manifest for characteristics that may indicate
  506. // issues with how the app selected tracks.
  507. shaka.offline.Storage.validateManifest_(manifest);
  508. }
  509. /**
  510. * Create a download manager and download the manifest.
  511. *
  512. * @param {shaka.extern.StorageCell} storage
  513. * @param {!shaka.media.DrmEngine} drmEngine
  514. * @param {shaka.extern.Manifest} manifest
  515. * @param {string} uri
  516. * @param {!Object} metadata
  517. * @param {shaka.extern.PlayerConfiguration} config
  518. * @param {!shaka.offline.DownloadManager} downloader
  519. * @return {!Promise.<shaka.extern.ManifestDB>}
  520. * @private
  521. */
  522. async downloadManifest_(
  523. storage, drmEngine, manifest, uri, metadata, config, downloader) {
  524. const pendingContent = shaka.offline.StoredContentUtils.fromManifest(
  525. uri, manifest, /* size= */ 0, metadata);
  526. // In https://github.com/shaka-project/shaka-player/issues/2652, we found
  527. // that this callback would be removed by the compiler if we reference the
  528. // config in the onProgress closure below. Reading it into a local
  529. // variable first seems to work around this apparent compiler bug.
  530. const progressCallback = config.offline.progressCallback;
  531. const onProgress = (progress, size) => {
  532. // Update the size of the stored content before issuing a progress
  533. // update.
  534. pendingContent.size = size;
  535. progressCallback(pendingContent, progress);
  536. };
  537. const onInitData = (initData, systemId) => {
  538. if (needsInitData && config.offline.usePersistentLicense &&
  539. currentSystemId == systemId) {
  540. drmEngine.newInitData('cenc', initData);
  541. }
  542. };
  543. downloader.setCallbacks(onProgress, onInitData);
  544. const isEncrypted = manifest.variants.some((variant) => {
  545. const videoEncrypted = variant.video && variant.video.encrypted;
  546. const audioEncrypted = variant.audio && variant.audio.encrypted;
  547. return videoEncrypted || audioEncrypted;
  548. });
  549. const includesInitData = manifest.variants.some((variant) => {
  550. const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
  551. const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
  552. const drmInfos = videoDrmInfos.concat(audioDrmInfos);
  553. return drmInfos.some((drmInfos) => {
  554. return drmInfos.initData && drmInfos.initData.length;
  555. });
  556. });
  557. const needsInitData = isEncrypted && !includesInitData;
  558. let currentSystemId = null;
  559. if (needsInitData) {
  560. const drmInfo = drmEngine.getDrmInfo();
  561. currentSystemId =
  562. shaka.offline.Storage.defaultSystemIds_.get(drmInfo.keySystem);
  563. }
  564. try {
  565. const manifestDB = this.createOfflineManifest_(
  566. downloader, storage, drmEngine, manifest, uri, metadata, config);
  567. manifestDB.size = await downloader.waitToFinish();
  568. manifestDB.expiration = drmEngine.getExpiration();
  569. const sessions = drmEngine.getSessionIds();
  570. manifestDB.sessionIds = config.offline.usePersistentLicense ?
  571. sessions : [];
  572. if (isEncrypted && config.offline.usePersistentLicense &&
  573. !sessions.length) {
  574. throw new shaka.util.Error(
  575. shaka.util.Error.Severity.CRITICAL,
  576. shaka.util.Error.Category.STORAGE,
  577. shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);
  578. }
  579. return manifestDB;
  580. } finally {
  581. await downloader.destroy();
  582. }
  583. }
  584. /**
  585. * Removes the given stored content. This will also attempt to release the
  586. * licenses, if any.
  587. *
  588. * @param {string} contentUri
  589. * @return {!Promise}
  590. * @export
  591. */
  592. remove(contentUri) {
  593. return this.startOperation_(this.remove_(contentUri));
  594. }
  595. /**
  596. * See |shaka.offline.Storage.remove| for details.
  597. *
  598. * @param {string} contentUri
  599. * @return {!Promise}
  600. * @private
  601. */
  602. async remove_(contentUri) {
  603. this.requireSupport_();
  604. const nullableUri = shaka.offline.OfflineUri.parse(contentUri);
  605. if (nullableUri == null || !nullableUri.isManifest()) {
  606. throw new shaka.util.Error(
  607. shaka.util.Error.Severity.CRITICAL,
  608. shaka.util.Error.Category.STORAGE,
  609. shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
  610. contentUri);
  611. }
  612. /** @type {!shaka.offline.OfflineUri} */
  613. const uri = nullableUri;
  614. /** @type {!shaka.offline.StorageMuxer} */
  615. const muxer = new shaka.offline.StorageMuxer();
  616. try {
  617. await muxer.init();
  618. const cell = await muxer.getCell(uri.mechanism(), uri.cell());
  619. const manifests = await cell.getManifests([uri.key()]);
  620. const manifest = manifests[0];
  621. await Promise.all([
  622. this.removeFromDRM_(uri, manifest, muxer),
  623. this.removeFromStorage_(cell, uri, manifest),
  624. ]);
  625. } finally {
  626. await muxer.destroy();
  627. }
  628. }
  629. /**
  630. * @param {shaka.extern.ManifestDB} manifestDb
  631. * @param {boolean} isVideo
  632. * @return {!Array.<MediaKeySystemMediaCapability>}
  633. * @private
  634. */
  635. static getCapabilities_(manifestDb, isVideo) {
  636. const MimeUtils = shaka.util.MimeUtils;
  637. const ret = [];
  638. for (const stream of manifestDb.streams) {
  639. if (isVideo && stream.type == 'video') {
  640. ret.push({
  641. contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
  642. robustness: manifestDb.drmInfo.videoRobustness,
  643. });
  644. } else if (!isVideo && stream.type == 'audio') {
  645. ret.push({
  646. contentType: MimeUtils.getFullType(stream.mimeType, stream.codecs),
  647. robustness: manifestDb.drmInfo.audioRobustness,
  648. });
  649. }
  650. }
  651. return ret;
  652. }
  653. /**
  654. * @param {!shaka.offline.OfflineUri} uri
  655. * @param {shaka.extern.ManifestDB} manifestDb
  656. * @param {!shaka.offline.StorageMuxer} muxer
  657. * @return {!Promise}
  658. * @private
  659. */
  660. async removeFromDRM_(uri, manifestDb, muxer) {
  661. goog.asserts.assert(this.networkingEngine_, 'Cannot be destroyed');
  662. await shaka.offline.Storage.deleteLicenseFor_(
  663. this.networkingEngine_, this.config_.drm, muxer, manifestDb);
  664. }
  665. /**
  666. * @param {shaka.extern.StorageCell} storage
  667. * @param {!shaka.offline.OfflineUri} uri
  668. * @param {shaka.extern.ManifestDB} manifest
  669. * @return {!Promise}
  670. * @private
  671. */
  672. removeFromStorage_( storage, uri, manifest) {
  673. /** @type {!Array.<number>} */
  674. const segmentIds = shaka.offline.Storage.getAllSegmentIds_(manifest);
  675. // Count(segments) + Count(manifests)
  676. const toRemove = segmentIds.length + 1;
  677. let removed = 0;
  678. const pendingContent = shaka.offline.StoredContentUtils.fromManifestDB(
  679. uri, manifest);
  680. const onRemove = (key) => {
  681. removed += 1;
  682. this.config_.offline.progressCallback(pendingContent, removed / toRemove);
  683. };
  684. return Promise.all([
  685. storage.removeSegments(segmentIds, onRemove),
  686. storage.removeManifests([uri.key()], onRemove),
  687. ]);
  688. }
  689. /**
  690. * Removes any EME sessions that were not successfully removed before. This
  691. * returns whether all the sessions were successfully removed.
  692. *
  693. * @return {!Promise.<boolean>}
  694. * @export
  695. */
  696. removeEmeSessions() {
  697. return this.startOperation_(this.removeEmeSessions_());
  698. }
  699. /**
  700. * @return {!Promise.<boolean>}
  701. * @private
  702. */
  703. async removeEmeSessions_() {
  704. this.requireSupport_();
  705. goog.asserts.assert(this.networkingEngine_, 'Cannot be destroyed');
  706. const net = this.networkingEngine_;
  707. const config = this.config_.drm;
  708. /** @type {!shaka.offline.StorageMuxer} */
  709. const muxer = new shaka.offline.StorageMuxer();
  710. /** @type {!shaka.offline.SessionDeleter} */
  711. const deleter = new shaka.offline.SessionDeleter();
  712. let hasRemaining = false;
  713. try {
  714. await muxer.init();
  715. /** @type {!Array.<shaka.extern.EmeSessionStorageCell>} */
  716. const cells = [];
  717. muxer.forEachEmeSessionCell((c) => cells.push(c));
  718. // Run these sequentially to avoid creating too many DrmEngine instances
  719. // and having multiple CDMs alive at once. Some embedded platforms may
  720. // not support that.
  721. for (const sessionIdCell of cells) {
  722. /* eslint-disable no-await-in-loop */
  723. const sessions = await sessionIdCell.getAll();
  724. const deletedSessionIds = await deleter.delete(config, net, sessions);
  725. await sessionIdCell.remove(deletedSessionIds);
  726. if (deletedSessionIds.length != sessions.length) {
  727. hasRemaining = true;
  728. }
  729. /* eslint-enable no-await-in-loop */
  730. }
  731. } finally {
  732. await muxer.destroy();
  733. }
  734. return !hasRemaining;
  735. }
  736. /**
  737. * Lists all the stored content available.
  738. *
  739. * @return {!Promise.<!Array.<shaka.extern.StoredContent>>} A Promise to an
  740. * array of structures representing all stored content. The "offlineUri"
  741. * member of the structure is the URI that should be given to Player.load()
  742. * to play this piece of content offline. The "appMetadata" member is the
  743. * appMetadata argument you passed to store().
  744. * @export
  745. */
  746. list() {
  747. return this.startOperation_(this.list_());
  748. }
  749. /**
  750. * See |shaka.offline.Storage.list| for details.
  751. *
  752. * @return {!Promise.<!Array.<shaka.extern.StoredContent>>}
  753. * @private
  754. */
  755. async list_() {
  756. this.requireSupport_();
  757. /** @type {!Array.<shaka.extern.StoredContent>} */
  758. const result = [];
  759. /** @type {!shaka.offline.StorageMuxer} */
  760. const muxer = new shaka.offline.StorageMuxer();
  761. try {
  762. await muxer.init();
  763. let p = Promise.resolve();
  764. muxer.forEachCell((path, cell) => {
  765. p = p.then(async () => {
  766. const manifests = await cell.getAllManifests();
  767. manifests.forEach((manifest, key) => {
  768. const uri = shaka.offline.OfflineUri.manifest(
  769. path.mechanism,
  770. path.cell,
  771. key);
  772. const content = shaka.offline.StoredContentUtils.fromManifestDB(
  773. uri,
  774. manifest);
  775. result.push(content);
  776. });
  777. });
  778. });
  779. await p;
  780. } finally {
  781. await muxer.destroy();
  782. }
  783. return result;
  784. }
  785. /**
  786. * This method is public so that it can be overridden in testing.
  787. *
  788. * @param {string} uri
  789. * @param {shaka.extern.ManifestParser} parser
  790. * @param {shaka.extern.PlayerConfiguration} config
  791. * @return {!Promise.<shaka.extern.Manifest>}
  792. */
  793. async parseManifest(uri, parser, config) {
  794. let error = null;
  795. const networkingEngine = this.networkingEngine_;
  796. goog.asserts.assert(networkingEngine, 'Should be initialized!');
  797. /** @type {shaka.extern.ManifestParser.PlayerInterface} */
  798. const playerInterface = {
  799. networkingEngine: networkingEngine,
  800. // Don't bother filtering now. We will do that later when we have all the
  801. // information we need to filter.
  802. filter: () => Promise.resolve(),
  803. // The responsibility for making mock text streams for closed captions is
  804. // handled inside shaka.offline.OfflineManifestParser, before playback.
  805. makeTextStreamsForClosedCaptions: (manifest) => {},
  806. onTimelineRegionAdded: () => {},
  807. onEvent: () => {},
  808. // Used to capture an error from the manifest parser. We will check the
  809. // error before returning.
  810. onError: (e) => {
  811. error = e;
  812. },
  813. isLowLatencyMode: () => false,
  814. isAutoLowLatencyMode: () => false,
  815. enableLowLatencyMode: () => {},
  816. };
  817. parser.configure(config.manifest);
  818. // We may have been destroyed while we were waiting on |getParser| to
  819. // resolve.
  820. this.ensureNotDestroyed_();
  821. const manifest = await parser.start(uri, playerInterface);
  822. // We may have been destroyed while we were waiting on |start| to
  823. // resolve.
  824. this.ensureNotDestroyed_();
  825. // Get all the streams that are used in the manifest.
  826. const streams =
  827. shaka.offline.Storage.getAllStreamsFromManifest_(manifest);
  828. // Wait for each stream to create their segment indexes.
  829. await Promise.all(shaka.util.Iterables.map(streams, (stream) => {
  830. return stream.createSegmentIndex();
  831. }));
  832. // We may have been destroyed while we were waiting on
  833. // |createSegmentIndex| to resolve for each stream.
  834. this.ensureNotDestroyed_();
  835. // If we saw an error while parsing, surface the error.
  836. if (error) {
  837. throw error;
  838. }
  839. return manifest;
  840. }
  841. /**
  842. * This method is public so that it can be override in testing.
  843. *
  844. * @param {shaka.extern.Manifest} manifest
  845. * @param {function(shaka.util.Error)} onError
  846. * @param {shaka.extern.PlayerConfiguration} config
  847. * @return {!Promise.<!shaka.media.DrmEngine>}
  848. */
  849. async createDrmEngine(manifest, onError, config) {
  850. goog.asserts.assert(
  851. this.networkingEngine_,
  852. 'Cannot call |createDrmEngine| after |destroy|');
  853. /** @type {!shaka.media.DrmEngine} */
  854. const drmEngine = new shaka.media.DrmEngine({
  855. netEngine: this.networkingEngine_,
  856. onError: onError,
  857. onKeyStatus: () => {},
  858. onExpirationUpdated: () => {},
  859. onEvent: () => {},
  860. });
  861. drmEngine.configure(config.drm);
  862. await drmEngine.initForStorage(
  863. manifest.variants, config.offline.usePersistentLicense);
  864. await drmEngine.setServerCertificate();
  865. await drmEngine.createOrLoad();
  866. return drmEngine;
  867. }
  868. /**
  869. * Creates an offline 'manifest' for the real manifest. This does not store
  870. * the segments yet, only adds them to the download manager through
  871. * createStreams_.
  872. *
  873. * @param {!shaka.offline.DownloadManager} downloader
  874. * @param {shaka.extern.StorageCell} storage
  875. * @param {!shaka.media.DrmEngine} drmEngine
  876. * @param {shaka.extern.Manifest} manifest
  877. * @param {string} originalManifestUri
  878. * @param {!Object} metadata
  879. * @param {shaka.extern.PlayerConfiguration} config
  880. * @return {shaka.extern.ManifestDB}
  881. * @private
  882. */
  883. createOfflineManifest_(
  884. downloader, storage, drmEngine, manifest, originalManifestUri, metadata,
  885. config) {
  886. const estimator = new shaka.offline.StreamBandwidthEstimator();
  887. const streams = this.createStreams_(
  888. downloader, storage, estimator, drmEngine, manifest, config);
  889. const usePersistentLicense = config.offline.usePersistentLicense;
  890. const drmInfo = drmEngine.getDrmInfo();
  891. if (drmInfo && usePersistentLicense) {
  892. // Don't store init data, since we have stored sessions.
  893. drmInfo.initData = [];
  894. }
  895. return {
  896. creationTime: Date.now(),
  897. originalManifestUri: originalManifestUri,
  898. duration: manifest.presentationTimeline.getDuration(),
  899. size: 0,
  900. expiration: drmEngine.getExpiration(),
  901. streams: streams,
  902. sessionIds: usePersistentLicense ? drmEngine.getSessionIds() : [],
  903. drmInfo: drmInfo,
  904. appMetadata: metadata,
  905. };
  906. }
  907. /**
  908. * Converts manifest Streams to database Streams. This will use the current
  909. * configuration to get the tracks to use, then it will search each segment
  910. * index and add all the segments to the download manager through
  911. * createStream_.
  912. *
  913. * @param {!shaka.offline.DownloadManager} downloader
  914. * @param {shaka.extern.StorageCell} storage
  915. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  916. * @param {!shaka.media.DrmEngine} drmEngine
  917. * @param {shaka.extern.Manifest} manifest
  918. * @param {shaka.extern.PlayerConfiguration} config
  919. * @return {!Array.<shaka.extern.StreamDB>}
  920. * @private
  921. */
  922. createStreams_(downloader, storage, estimator, drmEngine, manifest, config) {
  923. // Pass all variants and text streams to the estimator so that we can
  924. // get the best estimate for each stream later.
  925. for (const variant of manifest.variants) {
  926. estimator.addVariant(variant);
  927. }
  928. for (const text of manifest.textStreams) {
  929. estimator.addText(text);
  930. }
  931. for (const image of manifest.imageStreams) {
  932. estimator.addImage(image);
  933. }
  934. // TODO(joeyparrish): Break out stack-based state and method params into a
  935. // separate class to clean up. See:
  936. // https://github.com/google/shaka-player/issues/2781#issuecomment-678438039
  937. /**
  938. * A cache mapping init segment references to Promises to their DB key.
  939. *
  940. * @type {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
  941. */
  942. const initSegmentDbKeyCache = new Map();
  943. // A null init segment reference always maps to a null DB key.
  944. initSegmentDbKeyCache.set(
  945. null, /** @type {!Promise.<?number>} */(Promise.resolve(null)));
  946. /**
  947. * A cache mapping equivalent segment references to Promises to their DB
  948. * key. The key in this map is a string of the form
  949. * "<URI>-<startByte>-<endByte>".
  950. *
  951. * @type {!Map.<string, !Promise.<number>>}
  952. */
  953. const segmentDbKeyCache = new Map();
  954. // Find the streams we want to download and create a stream db instance
  955. // for each of them.
  956. const streamSet =
  957. shaka.offline.Storage.getAllStreamsFromManifest_(manifest);
  958. const streamDBs = new Map();
  959. for (const stream of streamSet) {
  960. const streamDB = this.createStream_(
  961. downloader, storage, estimator, manifest, stream, config,
  962. initSegmentDbKeyCache, segmentDbKeyCache);
  963. streamDBs.set(stream.id, streamDB);
  964. }
  965. // Connect streams and variants together.
  966. for (const variant of manifest.variants) {
  967. if (variant.audio) {
  968. streamDBs.get(variant.audio.id).variantIds.push(variant.id);
  969. }
  970. if (variant.video) {
  971. streamDBs.get(variant.video.id).variantIds.push(variant.id);
  972. }
  973. }
  974. return Array.from(streamDBs.values());
  975. }
  976. /**
  977. * Converts a manifest stream to a database stream. This will search the
  978. * segment index and add all the segments to the download manager.
  979. *
  980. * @param {!shaka.offline.DownloadManager} downloader
  981. * @param {shaka.extern.StorageCell} storage
  982. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  983. * @param {shaka.extern.Manifest} manifest
  984. * @param {shaka.extern.Stream} stream
  985. * @param {shaka.extern.PlayerConfiguration} config
  986. * @param {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
  987. * initSegmentDbKeyCache
  988. * @param {!Map.<string, !Promise.<number>>} segmentDbKeyCache
  989. * @return {shaka.extern.StreamDB}
  990. * @private
  991. */
  992. createStream_(downloader, storage, estimator, manifest, stream, config,
  993. initSegmentDbKeyCache, segmentDbKeyCache) {
  994. /** @type {shaka.extern.StreamDB} */
  995. const streamDb = {
  996. id: stream.id,
  997. originalId: stream.originalId,
  998. primary: stream.primary,
  999. type: stream.type,
  1000. mimeType: stream.mimeType,
  1001. codecs: stream.codecs,
  1002. frameRate: stream.frameRate,
  1003. pixelAspectRatio: stream.pixelAspectRatio,
  1004. hdr: stream.hdr,
  1005. kind: stream.kind,
  1006. language: stream.language,
  1007. label: stream.label,
  1008. width: stream.width || null,
  1009. height: stream.height || null,
  1010. encrypted: stream.encrypted,
  1011. keyIds: stream.keyIds,
  1012. segments: [],
  1013. variantIds: [],
  1014. roles: stream.roles,
  1015. forced: stream.forced,
  1016. channelsCount: stream.channelsCount,
  1017. audioSamplingRate: stream.audioSamplingRate,
  1018. spatialAudio: stream.spatialAudio,
  1019. closedCaptions: stream.closedCaptions,
  1020. tilesLayout: stream.tilesLayout,
  1021. };
  1022. // Download each stream in parallel.
  1023. const downloadGroup = stream.id;
  1024. const startTime =
  1025. manifest.presentationTimeline.getSegmentAvailabilityStart();
  1026. shaka.offline.Storage.forEachSegment_(stream, startTime, (segment) => {
  1027. const initSegmentKeyPromise = this.getInitSegmentDbKey_(
  1028. downloader, downloadGroup, stream.id, storage, estimator,
  1029. segment.initSegmentReference, config, initSegmentDbKeyCache);
  1030. const segmentKeyPromise = this.getSegmentDbKey_(
  1031. downloader, downloadGroup, stream.id, storage, estimator, segment,
  1032. config, segmentDbKeyCache);
  1033. downloader.queueWork(downloadGroup, async () => {
  1034. const initSegmentKey = await initSegmentKeyPromise;
  1035. const dataKey = await segmentKeyPromise;
  1036. streamDb.segments.push({
  1037. initSegmentKey,
  1038. startTime: segment.startTime,
  1039. endTime: segment.endTime,
  1040. appendWindowStart: segment.appendWindowStart,
  1041. appendWindowEnd: segment.appendWindowEnd,
  1042. timestampOffset: segment.timestampOffset,
  1043. tilesLayout: segment.tilesLayout,
  1044. dataKey,
  1045. });
  1046. });
  1047. });
  1048. return streamDb;
  1049. }
  1050. /**
  1051. * Get a Promise to the DB key for a given init segment reference.
  1052. *
  1053. * The return values will be cached so that multiple calls with the same init
  1054. * segment reference will only trigger one request.
  1055. *
  1056. * @param {!shaka.offline.DownloadManager} downloader
  1057. * @param {number} downloadGroup
  1058. * @param {number} streamId
  1059. * @param {shaka.extern.StorageCell} storage
  1060. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  1061. * @param {shaka.media.InitSegmentReference} initSegmentReference
  1062. * @param {shaka.extern.PlayerConfiguration} config
  1063. * @param {!Map.<shaka.media.InitSegmentReference, !Promise.<?number>>}
  1064. * initSegmentDbKeyCache
  1065. * @return {!Promise.<?number>}
  1066. * @private
  1067. */
  1068. getInitSegmentDbKey_(
  1069. downloader, downloadGroup, streamId, storage, estimator,
  1070. initSegmentReference, config, initSegmentDbKeyCache) {
  1071. if (initSegmentDbKeyCache.has(initSegmentReference)) {
  1072. return initSegmentDbKeyCache.get(initSegmentReference);
  1073. }
  1074. const request = shaka.util.Networking.createSegmentRequest(
  1075. initSegmentReference.getUris(),
  1076. initSegmentReference.startByte,
  1077. initSegmentReference.endByte,
  1078. config.streaming.retryParameters);
  1079. const promise = downloader.queue(
  1080. downloadGroup,
  1081. request,
  1082. estimator.getInitSegmentEstimate(streamId),
  1083. /* isInitSegment= */ true,
  1084. async (data) => {
  1085. /** @type {!Array.<number>} */
  1086. const ids = await storage.addSegments([{data: data}]);
  1087. this.segmentsFromStore_.push(ids[0]);
  1088. return ids[0];
  1089. });
  1090. initSegmentDbKeyCache.set(initSegmentReference, promise);
  1091. return promise;
  1092. }
  1093. /**
  1094. * Get a Promise to the DB key for a given segment reference.
  1095. *
  1096. * The return values will be cached so that multiple calls with the same
  1097. * segment reference will only trigger one request.
  1098. *
  1099. * @param {!shaka.offline.DownloadManager} downloader
  1100. * @param {number} downloadGroup
  1101. * @param {number} streamId
  1102. * @param {shaka.extern.StorageCell} storage
  1103. * @param {shaka.offline.StreamBandwidthEstimator} estimator
  1104. * @param {shaka.media.SegmentReference} segmentReference
  1105. * @param {shaka.extern.PlayerConfiguration} config
  1106. * @param {!Map.<string, !Promise.<number>>} segmentDbKeyCache
  1107. * @return {!Promise.<number>}
  1108. * @private
  1109. */
  1110. getSegmentDbKey_(
  1111. downloader, downloadGroup, streamId, storage, estimator,
  1112. segmentReference, config, segmentDbKeyCache) {
  1113. const mapKey = [
  1114. segmentReference.getUris()[0],
  1115. segmentReference.startByte,
  1116. segmentReference.endByte,
  1117. ].join('-');
  1118. if (segmentDbKeyCache.has(mapKey)) {
  1119. return segmentDbKeyCache.get(mapKey);
  1120. }
  1121. const request = shaka.util.Networking.createSegmentRequest(
  1122. segmentReference.getUris(),
  1123. segmentReference.startByte,
  1124. segmentReference.endByte,
  1125. config.streaming.retryParameters);
  1126. const promise = downloader.queue(
  1127. downloadGroup,
  1128. request,
  1129. estimator.getSegmentEstimate(streamId, segmentReference),
  1130. /* isInitSegment= */ false,
  1131. async (data) => {
  1132. /** @type {!Array.<number>} */
  1133. const ids = await storage.addSegments([{data: data}]);
  1134. this.segmentsFromStore_.push(ids[0]);
  1135. return ids[0];
  1136. });
  1137. segmentDbKeyCache.set(mapKey, promise);
  1138. return promise;
  1139. }
  1140. /**
  1141. * @param {shaka.extern.Stream} stream
  1142. * @param {number} startTime
  1143. * @param {function(!shaka.media.SegmentReference)} callback
  1144. * @private
  1145. */
  1146. static forEachSegment_(stream, startTime, callback) {
  1147. /** @type {?number} */
  1148. let i = stream.segmentIndex.find(startTime);
  1149. if (i == null) {
  1150. return;
  1151. }
  1152. /** @type {?shaka.media.SegmentReference} */
  1153. let ref = stream.segmentIndex.get(i);
  1154. while (ref) {
  1155. callback(ref);
  1156. ref = stream.segmentIndex.get(++i);
  1157. }
  1158. }
  1159. /**
  1160. * Throws an error if the object is destroyed.
  1161. * @private
  1162. */
  1163. ensureNotDestroyed_() {
  1164. if (this.destroyer_.destroyed()) {
  1165. throw new shaka.util.Error(
  1166. shaka.util.Error.Severity.CRITICAL,
  1167. shaka.util.Error.Category.STORAGE,
  1168. shaka.util.Error.Code.OPERATION_ABORTED);
  1169. }
  1170. }
  1171. /**
  1172. * Used by functions that need storage support to ensure that the current
  1173. * platform has storage support before continuing. This should only be
  1174. * needed to be used at the start of public methods.
  1175. *
  1176. * @private
  1177. */
  1178. requireSupport_() {
  1179. if (!shaka.offline.Storage.support()) {
  1180. throw new shaka.util.Error(
  1181. shaka.util.Error.Severity.CRITICAL,
  1182. shaka.util.Error.Category.STORAGE,
  1183. shaka.util.Error.Code.STORAGE_NOT_SUPPORTED);
  1184. }
  1185. }
  1186. /**
  1187. * Perform an action. Track the action's progress so that when we destroy
  1188. * we will wait until all the actions have completed before allowing destroy
  1189. * to resolve.
  1190. *
  1191. * @param {!Promise<T>} action
  1192. * @return {!Promise<T>}
  1193. * @template T
  1194. * @private
  1195. */
  1196. async startOperation_(action) {
  1197. this.openOperations_.push(action);
  1198. try {
  1199. // Await |action| so we can use the finally statement to remove |action|
  1200. // from |openOperations_| when we still have a reference to |action|.
  1201. return await action;
  1202. } finally {
  1203. shaka.util.ArrayUtils.remove(this.openOperations_, action);
  1204. }
  1205. }
  1206. /**
  1207. * The equivalent of startOperation_, but for abortable operations.
  1208. *
  1209. * @param {!shaka.extern.IAbortableOperation<T>} action
  1210. * @return {!shaka.extern.IAbortableOperation<T>}
  1211. * @template T
  1212. * @private
  1213. */
  1214. startAbortableOperation_(action) {
  1215. const promise = action.promise;
  1216. this.openOperations_.push(promise);
  1217. // Remove the open operation once the action has completed. So that we
  1218. // can still return the AbortableOperation, this is done using a |finally|
  1219. // block, rather than awaiting the result.
  1220. return action.finally(() => {
  1221. shaka.util.ArrayUtils.remove(this.openOperations_, promise);
  1222. });
  1223. }
  1224. /**
  1225. * @param {shaka.extern.ManifestDB} manifest
  1226. * @return {!Array.<number>}
  1227. * @private
  1228. */
  1229. static getAllSegmentIds_(manifest) {
  1230. /** @type {!Array.<number>} */
  1231. const ids = [];
  1232. // Get every segment for every stream in the manifest.
  1233. for (const stream of manifest.streams) {
  1234. for (const segment of stream.segments) {
  1235. if (segment.initSegmentKey != null) {
  1236. ids.push(segment.initSegmentKey);
  1237. }
  1238. ids.push(segment.dataKey);
  1239. }
  1240. }
  1241. return ids;
  1242. }
  1243. /**
  1244. * Delete the on-disk storage and all the content it contains. This should not
  1245. * be done in normal circumstances. Only do it when storage is rendered
  1246. * unusable, such as by a version mismatch. No business logic will be run, and
  1247. * licenses will not be released.
  1248. *
  1249. * @return {!Promise}
  1250. * @export
  1251. */
  1252. static async deleteAll() {
  1253. /** @type {!shaka.offline.StorageMuxer} */
  1254. const muxer = new shaka.offline.StorageMuxer();
  1255. try {
  1256. // Wipe all content from all storage mechanisms.
  1257. await muxer.erase();
  1258. } finally {
  1259. // Destroy the muxer, whether or not erase() succeeded.
  1260. await muxer.destroy();
  1261. }
  1262. }
  1263. /**
  1264. * @param {!shaka.net.NetworkingEngine} net
  1265. * @param {!shaka.extern.DrmConfiguration} drmConfig
  1266. * @param {!shaka.offline.StorageMuxer} muxer
  1267. * @param {shaka.extern.ManifestDB} manifestDb
  1268. * @return {!Promise}
  1269. * @private
  1270. */
  1271. static async deleteLicenseFor_(net, drmConfig, muxer, manifestDb) {
  1272. if (!manifestDb.drmInfo) {
  1273. return;
  1274. }
  1275. const sessionIdCell = muxer.getEmeSessionCell();
  1276. /** @type {!Array.<shaka.extern.EmeSessionDB>} */
  1277. const sessions = manifestDb.sessionIds.map((sessionId) => {
  1278. return {
  1279. sessionId: sessionId,
  1280. keySystem: manifestDb.drmInfo.keySystem,
  1281. licenseUri: manifestDb.drmInfo.licenseServerUri,
  1282. serverCertificate: manifestDb.drmInfo.serverCertificate,
  1283. audioCapabilities: shaka.offline.Storage.getCapabilities_(
  1284. manifestDb,
  1285. /* isVideo= */ false),
  1286. videoCapabilities: shaka.offline.Storage.getCapabilities_(
  1287. manifestDb,
  1288. /* isVideo= */ true),
  1289. };
  1290. });
  1291. // Try to delete the sessions; any sessions that weren't deleted get stored
  1292. // in the database so we can try to remove them again later. This allows us
  1293. // to still delete the stored content but not "forget" about these sessions.
  1294. // Later, we can remove the sessions to free up space.
  1295. const deleter = new shaka.offline.SessionDeleter();
  1296. const deletedSessionIds = await deleter.delete(drmConfig, net, sessions);
  1297. await sessionIdCell.remove(deletedSessionIds);
  1298. await sessionIdCell.add(sessions.filter(
  1299. (session) => !deletedSessionIds.includes(session.sessionId)));
  1300. }
  1301. /**
  1302. * Get the set of all streams in |manifest|.
  1303. *
  1304. * @param {shaka.extern.Manifest} manifest
  1305. * @return {!Set.<shaka.extern.Stream>}
  1306. * @private
  1307. */
  1308. static getAllStreamsFromManifest_(manifest) {
  1309. /** @type {!Set.<shaka.extern.Stream>} */
  1310. const set = new Set();
  1311. for (const text of manifest.textStreams) {
  1312. set.add(text);
  1313. }
  1314. for (const image of manifest.imageStreams) {
  1315. set.add(image);
  1316. }
  1317. for (const variant of manifest.variants) {
  1318. if (variant.audio) {
  1319. set.add(variant.audio);
  1320. }
  1321. if (variant.video) {
  1322. set.add(variant.video);
  1323. }
  1324. }
  1325. return set;
  1326. }
  1327. /**
  1328. * Go over a manifest and issue warnings for any suspicious properties.
  1329. *
  1330. * @param {shaka.extern.Manifest} manifest
  1331. * @private
  1332. */
  1333. static validateManifest_(manifest) {
  1334. const videos = new Set(manifest.variants.map((v) => v.video));
  1335. const audios = new Set(manifest.variants.map((v) => v.audio));
  1336. const texts = manifest.textStreams;
  1337. if (videos.size > 1) {
  1338. shaka.log.warning('Multiple video tracks selected to be stored');
  1339. }
  1340. for (const audio1 of audios) {
  1341. for (const audio2 of audios) {
  1342. if (audio1 != audio2 && audio1.language == audio2.language) {
  1343. shaka.log.warning(
  1344. 'Similar audio tracks were selected to be stored',
  1345. audio1.id,
  1346. audio2.id);
  1347. }
  1348. }
  1349. }
  1350. for (const text1 of texts) {
  1351. for (const text2 of texts) {
  1352. if (text1 != text2 && text1.language == text2.language) {
  1353. shaka.log.warning(
  1354. 'Similar text tracks were selected to be stored',
  1355. text1.id,
  1356. text2.id);
  1357. }
  1358. }
  1359. }
  1360. }
  1361. };
  1362. shaka.offline.Storage.defaultSystemIds_ = new Map()
  1363. .set('org.w3.clearkey', '1077efecc0b24d02ace33c1e52e2fb4b')
  1364. .set('com.widevine.alpha', 'edef8ba979d64acea3c827dcd51d21ed')
  1365. .set('com.microsoft.playready', '9a04f07998404286ab92e65be0885f95')
  1366. .set('com.microsoft.playready.recommendation',
  1367. '9a04f07998404286ab92e65be0885f95')
  1368. .set('com.microsoft.playready.software',
  1369. '9a04f07998404286ab92e65be0885f95')
  1370. .set('com.microsoft.playready.hardware',
  1371. '9a04f07998404286ab92e65be0885f95')
  1372. .set('com.adobe.primetime', 'f239e769efa348509c16a903c6932efb');
  1373. shaka.Player.registerSupportPlugin('offline', shaka.offline.Storage.support);