Source: lib/media/drm_engine.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.DrmEngine');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.net.NetworkingEngine');
  10. goog.require('shaka.transmuxer.TransmuxerEngine');
  11. goog.require('shaka.util.BufferUtils');
  12. goog.require('shaka.util.Destroyer');
  13. goog.require('shaka.util.DrmUtils');
  14. goog.require('shaka.util.Error');
  15. goog.require('shaka.util.EventManager');
  16. goog.require('shaka.util.FakeEvent');
  17. goog.require('shaka.util.IDestroyable');
  18. goog.require('shaka.util.Iterables');
  19. goog.require('shaka.util.ManifestParserUtils');
  20. goog.require('shaka.util.MapUtils');
  21. goog.require('shaka.util.MimeUtils');
  22. goog.require('shaka.util.ObjectUtils');
  23. goog.require('shaka.util.Platform');
  24. goog.require('shaka.util.Pssh');
  25. goog.require('shaka.util.PublicPromise');
  26. goog.require('shaka.util.StreamUtils');
  27. goog.require('shaka.util.StringUtils');
  28. goog.require('shaka.util.Timer');
  29. goog.require('shaka.util.TXml');
  30. goog.require('shaka.util.Uint8ArrayUtils');
  31. /** @implements {shaka.util.IDestroyable} */
  32. shaka.media.DrmEngine = class {
  33. /**
  34. * @param {shaka.media.DrmEngine.PlayerInterface} playerInterface
  35. */
  36. constructor(playerInterface) {
  37. /** @private {?shaka.media.DrmEngine.PlayerInterface} */
  38. this.playerInterface_ = playerInterface;
  39. /** @private {!Set.<string>} */
  40. this.supportedTypes_ = new Set();
  41. /** @private {MediaKeys} */
  42. this.mediaKeys_ = null;
  43. /** @private {HTMLMediaElement} */
  44. this.video_ = null;
  45. /** @private {boolean} */
  46. this.initialized_ = false;
  47. /** @private {boolean} */
  48. this.initializedForStorage_ = false;
  49. /** @private {number} */
  50. this.licenseTimeSeconds_ = 0;
  51. /** @private {?shaka.extern.DrmInfo} */
  52. this.currentDrmInfo_ = null;
  53. /** @private {shaka.util.EventManager} */
  54. this.eventManager_ = new shaka.util.EventManager();
  55. /**
  56. * @private {!Map.<MediaKeySession,
  57. * shaka.media.DrmEngine.SessionMetaData>}
  58. */
  59. this.activeSessions_ = new Map();
  60. /**
  61. * @private {!Map<string,
  62. * {initData: ?Uint8Array, initDataType: ?string}>}
  63. */
  64. this.storedPersistentSessions_ = new Map();
  65. /** @private {!shaka.util.PublicPromise} */
  66. this.allSessionsLoaded_ = new shaka.util.PublicPromise();
  67. /** @private {?shaka.extern.DrmConfiguration} */
  68. this.config_ = null;
  69. /** @private {function(!shaka.util.Error)} */
  70. this.onError_ = (err) => {
  71. if (err.severity == shaka.util.Error.Severity.CRITICAL) {
  72. this.allSessionsLoaded_.reject(err);
  73. }
  74. playerInterface.onError(err);
  75. };
  76. /**
  77. * The most recent key status information we have.
  78. * We may not have announced this information to the outside world yet,
  79. * which we delay to batch up changes and avoid spurious "missing key"
  80. * errors.
  81. * @private {!Map.<string, string>}
  82. */
  83. this.keyStatusByKeyId_ = new Map();
  84. /**
  85. * The key statuses most recently announced to other classes.
  86. * We may have more up-to-date information being collected in
  87. * this.keyStatusByKeyId_, which has not been batched up and released yet.
  88. * @private {!Map.<string, string>}
  89. */
  90. this.announcedKeyStatusByKeyId_ = new Map();
  91. /** @private {shaka.util.Timer} */
  92. this.keyStatusTimer_ =
  93. new shaka.util.Timer(() => this.processKeyStatusChanges_());
  94. /** @private {boolean} */
  95. this.usePersistentLicenses_ = false;
  96. /** @private {!Array.<!MediaKeyMessageEvent>} */
  97. this.mediaKeyMessageEvents_ = [];
  98. /** @private {boolean} */
  99. this.initialRequestsSent_ = false;
  100. /** @private {?shaka.util.Timer} */
  101. this.expirationTimer_ = new shaka.util.Timer(() => {
  102. this.pollExpiration_();
  103. });
  104. // Add a catch to the Promise to avoid console logs about uncaught errors.
  105. const noop = () => {};
  106. this.allSessionsLoaded_.catch(noop);
  107. /** @const {!shaka.util.Destroyer} */
  108. this.destroyer_ = new shaka.util.Destroyer(() => this.destroyNow_());
  109. /** @private {boolean} */
  110. this.srcEquals_ = false;
  111. /** @private {Promise} */
  112. this.mediaKeysAttached_ = null;
  113. /** @private {?shaka.extern.InitDataOverride} */
  114. this.manifestInitData_ = null;
  115. }
  116. /** @override */
  117. destroy() {
  118. return this.destroyer_.destroy();
  119. }
  120. /**
  121. * Destroy this instance of DrmEngine. This assumes that all other checks
  122. * about "if it should" have passed.
  123. *
  124. * @private
  125. */
  126. async destroyNow_() {
  127. // |eventManager_| should only be |null| after we call |destroy|. Destroy it
  128. // first so that we will stop responding to events.
  129. this.eventManager_.release();
  130. this.eventManager_ = null;
  131. // Since we are destroying ourselves, we don't want to react to the "all
  132. // sessions loaded" event.
  133. this.allSessionsLoaded_.reject();
  134. // Stop all timers. This will ensure that they do not start any new work
  135. // while we are destroying ourselves.
  136. this.expirationTimer_.stop();
  137. this.expirationTimer_ = null;
  138. this.keyStatusTimer_.stop();
  139. this.keyStatusTimer_ = null;
  140. // Close all open sessions.
  141. await this.closeOpenSessions_();
  142. // |video_| will be |null| if we never attached to a video element.
  143. if (this.video_) {
  144. // Webkit EME implementation requires the src to be defined to clear
  145. // the MediaKeys.
  146. if (!shaka.util.Platform.isMediaKeysPolyfilled('webkit')) {
  147. goog.asserts.assert(!this.video_.src,
  148. 'video src must be removed first!');
  149. }
  150. try {
  151. await this.video_.setMediaKeys(null);
  152. } catch (error) {
  153. // Ignore any failures while removing media keys from the video element.
  154. shaka.log.debug(`DrmEngine.destroyNow_ exception`, error);
  155. }
  156. this.video_ = null;
  157. }
  158. // Break references to everything else we hold internally.
  159. this.currentDrmInfo_ = null;
  160. this.supportedTypes_.clear();
  161. this.mediaKeys_ = null;
  162. this.storedPersistentSessions_ = new Map();
  163. this.config_ = null;
  164. this.onError_ = () => {};
  165. this.playerInterface_ = null;
  166. this.srcEquals_ = false;
  167. this.mediaKeysAttached_ = null;
  168. }
  169. /**
  170. * Called by the Player to provide an updated configuration any time it
  171. * changes.
  172. * Must be called at least once before init().
  173. *
  174. * @param {shaka.extern.DrmConfiguration} config
  175. */
  176. configure(config) {
  177. this.config_ = config;
  178. if (this.expirationTimer_) {
  179. this.expirationTimer_.tickEvery(
  180. /* seconds= */ this.config_.updateExpirationTime);
  181. }
  182. }
  183. /**
  184. * @param {!boolean} value
  185. */
  186. setSrcEquals(value) {
  187. this.srcEquals_ = value;
  188. }
  189. /**
  190. * Initialize the drm engine for storing and deleting stored content.
  191. *
  192. * @param {!Array.<shaka.extern.Variant>} variants
  193. * The variants that are going to be stored.
  194. * @param {boolean} usePersistentLicenses
  195. * Whether or not persistent licenses should be requested and stored for
  196. * |manifest|.
  197. * @return {!Promise}
  198. */
  199. initForStorage(variants, usePersistentLicenses) {
  200. this.initializedForStorage_ = true;
  201. // There are two cases for this call:
  202. // 1. We are about to store a manifest - in that case, there are no offline
  203. // sessions and therefore no offline session ids.
  204. // 2. We are about to remove the offline sessions for this manifest - in
  205. // that case, we don't need to know about them right now either as
  206. // we will be told which ones to remove later.
  207. this.storedPersistentSessions_ = new Map();
  208. // What we really need to know is whether or not they are expecting to use
  209. // persistent licenses.
  210. this.usePersistentLicenses_ = usePersistentLicenses;
  211. return this.init_(variants);
  212. }
  213. /**
  214. * Initialize the drm engine for playback operations.
  215. *
  216. * @param {!Array.<shaka.extern.Variant>} variants
  217. * The variants that we want to support playing.
  218. * @param {!Array.<string>} offlineSessionIds
  219. * @return {!Promise}
  220. */
  221. initForPlayback(variants, offlineSessionIds) {
  222. this.storedPersistentSessions_ = new Map();
  223. for (const sessionId of offlineSessionIds) {
  224. this.storedPersistentSessions_.set(
  225. sessionId, {initData: null, initDataType: null});
  226. }
  227. for (const metadata of this.config_.persistentSessionsMetadata) {
  228. this.storedPersistentSessions_.set(
  229. metadata.sessionId,
  230. {initData: metadata.initData, initDataType: metadata.initDataType});
  231. }
  232. this.usePersistentLicenses_ = this.storedPersistentSessions_.size > 0;
  233. return this.init_(variants);
  234. }
  235. /**
  236. * Initializes the drm engine for removing persistent sessions. Only the
  237. * removeSession(s) methods will work correctly, creating new sessions may not
  238. * work as desired.
  239. *
  240. * @param {string} keySystem
  241. * @param {string} licenseServerUri
  242. * @param {Uint8Array} serverCertificate
  243. * @param {!Array.<MediaKeySystemMediaCapability>} audioCapabilities
  244. * @param {!Array.<MediaKeySystemMediaCapability>} videoCapabilities
  245. * @return {!Promise}
  246. */
  247. initForRemoval(keySystem, licenseServerUri, serverCertificate,
  248. audioCapabilities, videoCapabilities) {
  249. /** @type {!Map.<string, MediaKeySystemConfiguration>} */
  250. const configsByKeySystem = new Map();
  251. /** @type {MediaKeySystemConfiguration} */
  252. const config = {
  253. audioCapabilities: audioCapabilities,
  254. videoCapabilities: videoCapabilities,
  255. distinctiveIdentifier: 'optional',
  256. persistentState: 'required',
  257. sessionTypes: ['persistent-license'],
  258. label: keySystem, // Tracked by us, ignored by EME.
  259. };
  260. // TODO: refactor, don't stick drmInfos onto MediaKeySystemConfiguration
  261. config['drmInfos'] = [{ // Non-standard attribute, ignored by EME.
  262. keySystem: keySystem,
  263. licenseServerUri: licenseServerUri,
  264. distinctiveIdentifierRequired: false,
  265. persistentStateRequired: true,
  266. audioRobustness: '', // Not required by queryMediaKeys_
  267. videoRobustness: '', // Same
  268. serverCertificate: serverCertificate,
  269. serverCertificateUri: '',
  270. initData: null,
  271. keyIds: null,
  272. }];
  273. configsByKeySystem.set(keySystem, config);
  274. return this.queryMediaKeys_(configsByKeySystem,
  275. /* variants= */ []);
  276. }
  277. /**
  278. * Negotiate for a key system and set up MediaKeys.
  279. * This will assume that both |usePersistentLicences_| and
  280. * |storedPersistentSessions_| have been properly set.
  281. *
  282. * @param {!Array.<shaka.extern.Variant>} variants
  283. * The variants that we expect to operate with during the drm engine's
  284. * lifespan of the drm engine.
  285. * @return {!Promise} Resolved if/when a key system has been chosen.
  286. * @private
  287. */
  288. async init_(variants) {
  289. goog.asserts.assert(this.config_,
  290. 'DrmEngine configure() must be called before init()!');
  291. // ClearKey config overrides the manifest DrmInfo if present. The variants
  292. // are modified so that filtering in Player still works.
  293. // This comes before hadDrmInfo because it influences the value of that.
  294. /** @type {?shaka.extern.DrmInfo} */
  295. const clearKeyDrmInfo = this.configureClearKey_();
  296. if (clearKeyDrmInfo) {
  297. for (const variant of variants) {
  298. if (variant.video) {
  299. variant.video.drmInfos = [clearKeyDrmInfo];
  300. }
  301. if (variant.audio) {
  302. variant.audio.drmInfos = [clearKeyDrmInfo];
  303. }
  304. }
  305. }
  306. const hadDrmInfo = variants.some((variant) => {
  307. if (variant.video && variant.video.drmInfos.length) {
  308. return true;
  309. }
  310. if (variant.audio && variant.audio.drmInfos.length) {
  311. return true;
  312. }
  313. return false;
  314. });
  315. // When preparing to play live streams, it is possible that we won't know
  316. // about some upcoming encrypted content. If we initialize the drm engine
  317. // with no key systems, we won't be able to play when the encrypted content
  318. // comes.
  319. //
  320. // To avoid this, we will set the drm engine up to work with as many key
  321. // systems as possible so that we will be ready.
  322. if (!hadDrmInfo) {
  323. const servers = shaka.util.MapUtils.asMap(this.config_.servers);
  324. shaka.media.DrmEngine.replaceDrmInfo_(variants, servers);
  325. }
  326. /** @type {!Set<shaka.extern.DrmInfo>} */
  327. const drmInfos = new Set();
  328. for (const variant of variants) {
  329. const variantDrmInfos = this.getVariantDrmInfos_(variant);
  330. for (const info of variantDrmInfos) {
  331. drmInfos.add(info);
  332. }
  333. }
  334. for (const info of drmInfos) {
  335. shaka.media.DrmEngine.fillInDrmInfoDefaults_(
  336. info,
  337. shaka.util.MapUtils.asMap(this.config_.servers),
  338. shaka.util.MapUtils.asMap(this.config_.advanced || {}),
  339. this.config_.keySystemsMapping);
  340. }
  341. /** @type {!Map.<string, MediaKeySystemConfiguration>} */
  342. let configsByKeySystem;
  343. // We should get the decodingInfo results for the variants after we filling
  344. // in the drm infos, and before queryMediaKeys_().
  345. await shaka.util.StreamUtils.getDecodingInfosForVariants(variants,
  346. this.usePersistentLicenses_, this.srcEquals_,
  347. this.config_.preferredKeySystems);
  348. this.destroyer_.ensureNotDestroyed();
  349. const hasDrmInfo = hadDrmInfo || Object.keys(this.config_.servers).length;
  350. // An unencrypted content is initialized.
  351. if (!hasDrmInfo) {
  352. this.initialized_ = true;
  353. return Promise.resolve();
  354. }
  355. const p = this.queryMediaKeys_(configsByKeySystem, variants);
  356. // TODO(vaage): Look into the assertion below. If we do not have any drm
  357. // info, we create drm info so that content can play if it has drm info
  358. // later.
  359. // However it is okay if we fail to initialize? If we fail to initialize,
  360. // it means we won't be able to play the later-encrypted content, which is
  361. // not okay.
  362. // If the content did not originally have any drm info, then it doesn't
  363. // matter if we fail to initialize the drm engine, because we won't need it
  364. // anyway.
  365. return hadDrmInfo ? p : p.catch(() => {});
  366. }
  367. /**
  368. * Attach MediaKeys to the video element
  369. * @return {Promise}
  370. * @private
  371. */
  372. async attachMediaKeys_() {
  373. if (this.video_.mediaKeys) {
  374. return;
  375. }
  376. // An attach process has already started, let's wait it out
  377. if (this.mediaKeysAttached_) {
  378. await this.mediaKeysAttached_;
  379. this.destroyer_.ensureNotDestroyed();
  380. return;
  381. }
  382. try {
  383. this.mediaKeysAttached_ = this.video_.setMediaKeys(this.mediaKeys_);
  384. await this.mediaKeysAttached_;
  385. } catch (exception) {
  386. goog.asserts.assert(exception instanceof Error, 'Wrong error type!');
  387. this.onError_(new shaka.util.Error(
  388. shaka.util.Error.Severity.CRITICAL,
  389. shaka.util.Error.Category.DRM,
  390. shaka.util.Error.Code.FAILED_TO_ATTACH_TO_VIDEO,
  391. exception.message));
  392. }
  393. this.destroyer_.ensureNotDestroyed();
  394. }
  395. /**
  396. * Processes encrypted event and start licence challenging
  397. * @return {!Promise}
  398. * @private
  399. */
  400. async onEncryptedEvent_(event) {
  401. /**
  402. * MediaKeys should be added when receiving an encrypted event. Setting
  403. * mediaKeys before could result into encrypted event not being fired on
  404. * some browsers
  405. */
  406. await this.attachMediaKeys_();
  407. this.newInitData(
  408. event.initDataType,
  409. shaka.util.BufferUtils.toUint8(event.initData));
  410. }
  411. /**
  412. * Start processing events.
  413. * @param {HTMLMediaElement} video
  414. * @return {!Promise}
  415. */
  416. async attach(video) {
  417. if (!this.mediaKeys_) {
  418. // Unencrypted, or so we think. We listen for encrypted events in order
  419. // to warn when the stream is encrypted, even though the manifest does
  420. // not know it.
  421. // Don't complain about this twice, so just listenOnce().
  422. // FIXME: This is ineffective when a prefixed event is translated by our
  423. // polyfills, since those events are only caught and translated by a
  424. // MediaKeys instance. With clear content and no polyfilled MediaKeys
  425. // instance attached, you'll never see the 'encrypted' event on those
  426. // platforms (Safari).
  427. this.eventManager_.listenOnce(video, 'encrypted', (event) => {
  428. this.onError_(new shaka.util.Error(
  429. shaka.util.Error.Severity.CRITICAL,
  430. shaka.util.Error.Category.DRM,
  431. shaka.util.Error.Code.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO));
  432. });
  433. return;
  434. }
  435. this.video_ = video;
  436. this.eventManager_.listenOnce(this.video_, 'play', () => this.onPlay_());
  437. if ('webkitCurrentPlaybackTargetIsWireless' in this.video_) {
  438. this.eventManager_.listen(this.video_,
  439. 'webkitcurrentplaybacktargetiswirelesschanged',
  440. () => this.closeOpenSessions_());
  441. }
  442. this.manifestInitData_ = this.currentDrmInfo_ ?
  443. (this.currentDrmInfo_.initData.find(
  444. (initDataOverride) => initDataOverride.initData.length > 0,
  445. ) || null) : null;
  446. /**
  447. * We can attach media keys before the playback actually begins when:
  448. * - If we are not using FairPlay Modern EME
  449. * - Some initData already has been generated (through the manifest)
  450. * - In case of an offline session
  451. */
  452. if (this.manifestInitData_ ||
  453. this.currentDrmInfo_.keySystem !== 'com.apple.fps' ||
  454. this.storedPersistentSessions_.size) {
  455. await this.attachMediaKeys_();
  456. }
  457. this.createOrLoad().catch(() => {
  458. // Silence errors
  459. // createOrLoad will run async, errors are triggered through onError_
  460. });
  461. // Explicit init data for any one stream or an offline session is
  462. // sufficient to suppress 'encrypted' events for all streams.
  463. // Also suppress 'encrypted' events when parsing in-band ppsh
  464. // from media segments because that serves the same purpose as the
  465. // 'encrypted' events.
  466. if (!this.manifestInitData_ && !this.storedPersistentSessions_.size &&
  467. !this.config_.parseInbandPsshEnabled) {
  468. this.eventManager_.listen(
  469. this.video_, 'encrypted', (e) => this.onEncryptedEvent_(e));
  470. }
  471. }
  472. /**
  473. * Returns true if the manifest has init data.
  474. *
  475. * @return {boolean}
  476. */
  477. hasManifestInitData() {
  478. return !!this.manifestInitData_;
  479. }
  480. /**
  481. * Sets the server certificate based on the current DrmInfo.
  482. *
  483. * @return {!Promise}
  484. */
  485. async setServerCertificate() {
  486. goog.asserts.assert(this.initialized_,
  487. 'Must call init() before setServerCertificate');
  488. if (!this.mediaKeys_ || !this.currentDrmInfo_) {
  489. return;
  490. }
  491. if (this.currentDrmInfo_.serverCertificateUri &&
  492. (!this.currentDrmInfo_.serverCertificate ||
  493. !this.currentDrmInfo_.serverCertificate.length)) {
  494. const request = shaka.net.NetworkingEngine.makeRequest(
  495. [this.currentDrmInfo_.serverCertificateUri],
  496. this.config_.retryParameters);
  497. try {
  498. const operation = this.playerInterface_.netEngine.request(
  499. shaka.net.NetworkingEngine.RequestType.SERVER_CERTIFICATE,
  500. request);
  501. const response = await operation.promise;
  502. this.currentDrmInfo_.serverCertificate =
  503. shaka.util.BufferUtils.toUint8(response.data);
  504. } catch (error) {
  505. // Request failed!
  506. goog.asserts.assert(error instanceof shaka.util.Error,
  507. 'Wrong NetworkingEngine error type!');
  508. throw new shaka.util.Error(
  509. shaka.util.Error.Severity.CRITICAL,
  510. shaka.util.Error.Category.DRM,
  511. shaka.util.Error.Code.SERVER_CERTIFICATE_REQUEST_FAILED,
  512. error);
  513. }
  514. if (this.destroyer_.destroyed()) {
  515. return;
  516. }
  517. }
  518. if (!this.currentDrmInfo_.serverCertificate ||
  519. !this.currentDrmInfo_.serverCertificate.length) {
  520. return;
  521. }
  522. try {
  523. const supported = await this.mediaKeys_.setServerCertificate(
  524. this.currentDrmInfo_.serverCertificate);
  525. if (!supported) {
  526. shaka.log.warning('Server certificates are not supported by the ' +
  527. 'key system. The server certificate has been ' +
  528. 'ignored.');
  529. }
  530. } catch (exception) {
  531. throw new shaka.util.Error(
  532. shaka.util.Error.Severity.CRITICAL,
  533. shaka.util.Error.Category.DRM,
  534. shaka.util.Error.Code.INVALID_SERVER_CERTIFICATE,
  535. exception.message);
  536. }
  537. }
  538. /**
  539. * Remove an offline session and delete it's data. This can only be called
  540. * after a successful call to |init|. This will wait until the
  541. * 'license-release' message is handled. The returned Promise will be rejected
  542. * if there is an error releasing the license.
  543. *
  544. * @param {string} sessionId
  545. * @return {!Promise}
  546. */
  547. async removeSession(sessionId) {
  548. goog.asserts.assert(this.mediaKeys_,
  549. 'Must call init() before removeSession');
  550. const session = await this.loadOfflineSession_(
  551. sessionId, {initData: null, initDataType: null});
  552. // This will be null on error, such as session not found.
  553. if (!session) {
  554. shaka.log.v2('Ignoring attempt to remove missing session', sessionId);
  555. return;
  556. }
  557. // TODO: Consider adding a timeout to get the 'message' event.
  558. // Note that the 'message' event will get raised after the remove()
  559. // promise resolves.
  560. const tasks = [];
  561. const found = this.activeSessions_.get(session);
  562. if (found) {
  563. // This will force us to wait until the 'license-release' message has been
  564. // handled.
  565. found.updatePromise = new shaka.util.PublicPromise();
  566. tasks.push(found.updatePromise);
  567. }
  568. shaka.log.v2('Attempting to remove session', sessionId);
  569. tasks.push(session.remove());
  570. await Promise.all(tasks);
  571. this.activeSessions_.delete(session);
  572. }
  573. /**
  574. * Creates the sessions for the init data and waits for them to become ready.
  575. *
  576. * @return {!Promise}
  577. */
  578. async createOrLoad() {
  579. if (this.storedPersistentSessions_.size) {
  580. this.storedPersistentSessions_.forEach((metadata, sessionId) => {
  581. this.loadOfflineSession_(sessionId, metadata);
  582. });
  583. await this.allSessionsLoaded_;
  584. const keyIds = (this.currentDrmInfo_ && this.currentDrmInfo_.keyIds) ||
  585. new Set([]);
  586. // All the needed keys are already loaded, we don't need another license
  587. // Therefore we prevent starting a new session
  588. if (keyIds.size > 0 && this.areAllKeysUsable_()) {
  589. return this.allSessionsLoaded_;
  590. }
  591. // Reset the promise for the next sessions to come if key needs aren't
  592. // satisfied with persistent sessions
  593. this.allSessionsLoaded_ = new shaka.util.PublicPromise();
  594. this.allSessionsLoaded_.catch(() => {});
  595. }
  596. // Create sessions.
  597. const initDatas =
  598. (this.currentDrmInfo_ ? this.currentDrmInfo_.initData : []) || [];
  599. for (const initDataOverride of initDatas) {
  600. this.newInitData(
  601. initDataOverride.initDataType, initDataOverride.initData);
  602. }
  603. // If there were no sessions to load, we need to resolve the promise right
  604. // now or else it will never get resolved.
  605. // We determine this by checking areAllSessionsLoaded_, rather than checking
  606. // the number of initDatas, since the newInitData method can reject init
  607. // datas in some circumstances.
  608. if (this.areAllSessionsLoaded_()) {
  609. this.allSessionsLoaded_.resolve();
  610. }
  611. return this.allSessionsLoaded_;
  612. }
  613. /**
  614. * Called when new initialization data is encountered. If this data hasn't
  615. * been seen yet, this will create a new session for it.
  616. *
  617. * @param {string} initDataType
  618. * @param {!Uint8Array} initData
  619. */
  620. newInitData(initDataType, initData) {
  621. if (!initData.length) {
  622. return;
  623. }
  624. // Suppress duplicate init data.
  625. // Note that some init data are extremely large and can't portably be used
  626. // as keys in a dictionary.
  627. if (this.config_.ignoreDuplicateInitData) {
  628. const metadatas = this.activeSessions_.values();
  629. for (const metadata of metadatas) {
  630. if (shaka.util.BufferUtils.equal(initData, metadata.initData)) {
  631. shaka.log.debug('Ignoring duplicate init data.');
  632. return;
  633. }
  634. }
  635. }
  636. // If there are pre-existing sessions that have all been loaded
  637. // then reset the allSessionsLoaded_ promise, which can now be
  638. // used to wait for new sesssions to be loaded
  639. if (this.activeSessions_.size > 0 && this.areAllSessionsLoaded_()) {
  640. this.allSessionsLoaded_.resolve();
  641. this.allSessionsLoaded_ = new shaka.util.PublicPromise();
  642. this.allSessionsLoaded_.catch(() => {});
  643. }
  644. this.createSession(initDataType, initData,
  645. this.currentDrmInfo_.sessionType);
  646. }
  647. /** @return {boolean} */
  648. initialized() {
  649. return this.initialized_;
  650. }
  651. /**
  652. * Check if DrmEngine (as initialized) will likely be able to support the
  653. * given content type.
  654. *
  655. * @param {string} contentType
  656. * @return {boolean}
  657. */
  658. willSupport(contentType) {
  659. // Edge 14 does not report correct capabilities. It will only report the
  660. // first MIME type even if the others are supported. To work around this,
  661. // we say that Edge supports everything.
  662. //
  663. // See https://github.com/shaka-project/shaka-player/issues/1495 for details.
  664. if (shaka.util.Platform.isLegacyEdge()) {
  665. return true;
  666. }
  667. contentType = contentType.toLowerCase();
  668. if (shaka.util.Platform.isTizen() &&
  669. contentType.includes('codecs="ac-3"')) {
  670. // Some Tizen devices seem to misreport AC-3 support. This works around
  671. // the issue, by falling back to EC-3, which seems to be supported on the
  672. // same devices and be correctly reported in all cases we have observed.
  673. // See https://github.com/shaka-project/shaka-player/issues/2989 for
  674. // details.
  675. const fallback = contentType.replace('ac-3', 'ec-3');
  676. return this.supportedTypes_.has(contentType) ||
  677. this.supportedTypes_.has(fallback);
  678. }
  679. return this.supportedTypes_.has(contentType);
  680. }
  681. /**
  682. * Returns the ID of the sessions currently active.
  683. *
  684. * @return {!Array.<string>}
  685. */
  686. getSessionIds() {
  687. const sessions = this.activeSessions_.keys();
  688. const ids = shaka.util.Iterables.map(sessions, (s) => s.sessionId);
  689. // TODO: Make |getSessionIds| return |Iterable| instead of |Array|.
  690. return Array.from(ids);
  691. }
  692. /**
  693. * Returns the active sessions metadata
  694. *
  695. * @return {!Array.<shaka.extern.DrmSessionMetadata>}
  696. */
  697. getActiveSessionsMetadata() {
  698. const sessions = this.activeSessions_.keys();
  699. const metadata = shaka.util.Iterables.map(sessions, (session) => {
  700. const metadata = this.activeSessions_.get(session);
  701. return {
  702. sessionId: session.sessionId,
  703. sessionType: metadata.type,
  704. initData: metadata.initData,
  705. initDataType: metadata.initDataType,
  706. };
  707. });
  708. return Array.from(metadata);
  709. }
  710. /**
  711. * Returns the next expiration time, or Infinity.
  712. * @return {number}
  713. */
  714. getExpiration() {
  715. // This will equal Infinity if there are no entries.
  716. let min = Infinity;
  717. const sessions = this.activeSessions_.keys();
  718. for (const session of sessions) {
  719. if (!isNaN(session.expiration)) {
  720. min = Math.min(min, session.expiration);
  721. }
  722. }
  723. return min;
  724. }
  725. /**
  726. * Returns the time spent on license requests during this session, or NaN.
  727. *
  728. * @return {number}
  729. */
  730. getLicenseTime() {
  731. if (this.licenseTimeSeconds_) {
  732. return this.licenseTimeSeconds_;
  733. }
  734. return NaN;
  735. }
  736. /**
  737. * Returns the DrmInfo that was used to initialize the current key system.
  738. *
  739. * @return {?shaka.extern.DrmInfo}
  740. */
  741. getDrmInfo() {
  742. return this.currentDrmInfo_;
  743. }
  744. /**
  745. * Return the media keys created from the current mediaKeySystemAccess.
  746. * @return {MediaKeys}
  747. */
  748. getMediaKeys() {
  749. return this.mediaKeys_;
  750. }
  751. /**
  752. * Returns the current key statuses.
  753. *
  754. * @return {!Object.<string, string>}
  755. */
  756. getKeyStatuses() {
  757. return shaka.util.MapUtils.asObject(this.announcedKeyStatusByKeyId_);
  758. }
  759. /**
  760. * Returns the current media key sessions.
  761. *
  762. * @return {!Array.<MediaKeySession>}
  763. */
  764. getMediaKeySessions() {
  765. return Array.from(this.activeSessions_.keys());
  766. }
  767. /**
  768. * @param {shaka.extern.Stream} stream
  769. * @param {string=} codecOverride
  770. * @return {string}
  771. * @private
  772. */
  773. static computeMimeType_(stream, codecOverride) {
  774. const realMimeType = shaka.util.MimeUtils.getFullType(stream.mimeType,
  775. codecOverride || stream.codecs);
  776. const TransmuxerEngine = shaka.transmuxer.TransmuxerEngine;
  777. if (TransmuxerEngine.isSupported(realMimeType, stream.type)) {
  778. // This will be handled by the Transmuxer, so use the MIME type that the
  779. // Transmuxer will produce.
  780. return TransmuxerEngine.convertCodecs(stream.type, realMimeType);
  781. }
  782. return realMimeType;
  783. }
  784. /**
  785. * @param {!Map.<string, MediaKeySystemConfiguration>} configsByKeySystem
  786. * A dictionary of configs, indexed by key system, with an iteration order
  787. * (insertion order) that reflects the preference for the application.
  788. * @param {!Array.<shaka.extern.Variant>} variants
  789. * @return {!Promise} Resolved if/when a key system has been chosen.
  790. * @private
  791. */
  792. async queryMediaKeys_(configsByKeySystem, variants) {
  793. const drmInfosByKeySystem = new Map();
  794. const mediaKeySystemAccess = variants.length ?
  795. this.getKeySystemAccessFromVariants_(variants, drmInfosByKeySystem) :
  796. await this.getKeySystemAccessByConfigs_(configsByKeySystem);
  797. if (!mediaKeySystemAccess) {
  798. throw new shaka.util.Error(
  799. shaka.util.Error.Severity.CRITICAL,
  800. shaka.util.Error.Category.DRM,
  801. shaka.util.Error.Code.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE);
  802. }
  803. this.destroyer_.ensureNotDestroyed();
  804. try {
  805. // Get the set of supported content types from the audio and video
  806. // capabilities. Avoid duplicates so that it is easier to read what is
  807. // supported.
  808. this.supportedTypes_.clear();
  809. // Store the capabilities of the key system.
  810. const realConfig = mediaKeySystemAccess.getConfiguration();
  811. shaka.log.v2(
  812. 'Got MediaKeySystemAccess with configuration',
  813. realConfig);
  814. const audioCaps = realConfig.audioCapabilities || [];
  815. const videoCaps = realConfig.videoCapabilities || [];
  816. for (const cap of audioCaps) {
  817. this.supportedTypes_.add(cap.contentType.toLowerCase());
  818. }
  819. for (const cap of videoCaps) {
  820. this.supportedTypes_.add(cap.contentType.toLowerCase());
  821. }
  822. goog.asserts.assert(this.supportedTypes_.size,
  823. 'We should get at least one supported MIME type');
  824. if (variants.length) {
  825. this.currentDrmInfo_ = this.createDrmInfoByInfos_(
  826. mediaKeySystemAccess.keySystem,
  827. drmInfosByKeySystem.get(mediaKeySystemAccess.keySystem));
  828. } else {
  829. this.currentDrmInfo_ = shaka.media.DrmEngine.createDrmInfoByConfigs_(
  830. mediaKeySystemAccess.keySystem,
  831. configsByKeySystem.get(mediaKeySystemAccess.keySystem));
  832. }
  833. if (!this.currentDrmInfo_.licenseServerUri) {
  834. throw new shaka.util.Error(
  835. shaka.util.Error.Severity.CRITICAL,
  836. shaka.util.Error.Category.DRM,
  837. shaka.util.Error.Code.NO_LICENSE_SERVER_GIVEN,
  838. this.currentDrmInfo_.keySystem);
  839. }
  840. const mediaKeys = await mediaKeySystemAccess.createMediaKeys();
  841. this.destroyer_.ensureNotDestroyed();
  842. shaka.log.info('Created MediaKeys object for key system',
  843. this.currentDrmInfo_.keySystem);
  844. this.mediaKeys_ = mediaKeys;
  845. if (this.config_.minHdcpVersion != '' &&
  846. 'getStatusForPolicy' in this.mediaKeys_) {
  847. try {
  848. const status = await this.mediaKeys_.getStatusForPolicy({
  849. minHdcpVersion: this.config_.minHdcpVersion,
  850. });
  851. if (status != 'usable') {
  852. throw new shaka.util.Error(
  853. shaka.util.Error.Severity.CRITICAL,
  854. shaka.util.Error.Category.DRM,
  855. shaka.util.Error.Code.MIN_HDCP_VERSION_NOT_MATCH);
  856. }
  857. this.destroyer_.ensureNotDestroyed();
  858. } catch (e) {
  859. if (e instanceof shaka.util.Error) {
  860. throw e;
  861. }
  862. throw new shaka.util.Error(
  863. shaka.util.Error.Severity.CRITICAL,
  864. shaka.util.Error.Category.DRM,
  865. shaka.util.Error.Code.ERROR_CHECKING_HDCP_VERSION,
  866. e.message);
  867. }
  868. }
  869. this.initialized_ = true;
  870. await this.setServerCertificate();
  871. this.destroyer_.ensureNotDestroyed();
  872. } catch (exception) {
  873. this.destroyer_.ensureNotDestroyed(exception);
  874. // Don't rewrap a shaka.util.Error from earlier in the chain:
  875. this.currentDrmInfo_ = null;
  876. this.supportedTypes_.clear();
  877. if (exception instanceof shaka.util.Error) {
  878. throw exception;
  879. }
  880. // We failed to create MediaKeys. This generally shouldn't happen.
  881. throw new shaka.util.Error(
  882. shaka.util.Error.Severity.CRITICAL,
  883. shaka.util.Error.Category.DRM,
  884. shaka.util.Error.Code.FAILED_TO_CREATE_CDM,
  885. exception.message);
  886. }
  887. }
  888. /**
  889. * Get the MediaKeySystemAccess from the decodingInfos of the variants.
  890. * @param {!Array.<shaka.extern.Variant>} variants
  891. * @param {!Map.<string, !Array.<shaka.extern.DrmInfo>>} drmInfosByKeySystem
  892. * A dictionary of drmInfos, indexed by key system.
  893. * @return {MediaKeySystemAccess}
  894. * @private
  895. */
  896. getKeySystemAccessFromVariants_(variants, drmInfosByKeySystem) {
  897. for (const variant of variants) {
  898. // Get all the key systems in the variant that shouldHaveLicenseServer.
  899. const drmInfos = this.getVariantDrmInfos_(variant);
  900. for (const info of drmInfos) {
  901. if (!drmInfosByKeySystem.has(info.keySystem)) {
  902. drmInfosByKeySystem.set(info.keySystem, []);
  903. }
  904. drmInfosByKeySystem.get(info.keySystem).push(info);
  905. }
  906. }
  907. if (drmInfosByKeySystem.size == 1 && drmInfosByKeySystem.has('')) {
  908. throw new shaka.util.Error(
  909. shaka.util.Error.Severity.CRITICAL,
  910. shaka.util.Error.Category.DRM,
  911. shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);
  912. }
  913. // If we have configured preferredKeySystems, choose a preferred keySystem
  914. // if available.
  915. for (const preferredKeySystem of this.config_.preferredKeySystems) {
  916. for (const variant of variants) {
  917. const decodingInfo = variant.decodingInfos.find((decodingInfo) => {
  918. return decodingInfo.supported &&
  919. decodingInfo.keySystemAccess != null &&
  920. decodingInfo.keySystemAccess.keySystem == preferredKeySystem;
  921. });
  922. if (decodingInfo) {
  923. return decodingInfo.keySystemAccess;
  924. }
  925. }
  926. }
  927. // Try key systems with configured license servers first. We only have to
  928. // try key systems without configured license servers for diagnostic
  929. // reasons, so that we can differentiate between "none of these key
  930. // systems are available" and "some are available, but you did not
  931. // configure them properly." The former takes precedence.
  932. for (const shouldHaveLicenseServer of [true, false]) {
  933. for (const variant of variants) {
  934. for (const decodingInfo of variant.decodingInfos) {
  935. if (!decodingInfo.supported || !decodingInfo.keySystemAccess) {
  936. continue;
  937. }
  938. const drmInfos =
  939. drmInfosByKeySystem.get(decodingInfo.keySystemAccess.keySystem);
  940. for (const info of drmInfos) {
  941. if (!!info.licenseServerUri == shouldHaveLicenseServer) {
  942. return decodingInfo.keySystemAccess;
  943. }
  944. }
  945. }
  946. }
  947. }
  948. return null;
  949. }
  950. /**
  951. * Get the MediaKeySystemAccess by querying requestMediaKeySystemAccess.
  952. * @param {!Map.<string, MediaKeySystemConfiguration>} configsByKeySystem
  953. * A dictionary of configs, indexed by key system, with an iteration order
  954. * (insertion order) that reflects the preference for the application.
  955. * @return {!Promise.<MediaKeySystemAccess>} Resolved if/when a
  956. * mediaKeySystemAccess has been chosen.
  957. * @private
  958. */
  959. async getKeySystemAccessByConfigs_(configsByKeySystem) {
  960. /** @type {MediaKeySystemAccess} */
  961. let mediaKeySystemAccess;
  962. if (configsByKeySystem.size == 1 && configsByKeySystem.has('')) {
  963. throw new shaka.util.Error(
  964. shaka.util.Error.Severity.CRITICAL,
  965. shaka.util.Error.Category.DRM,
  966. shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);
  967. }
  968. // If there are no tracks of a type, these should be not present.
  969. // Otherwise the query will fail.
  970. for (const config of configsByKeySystem.values()) {
  971. if (config.audioCapabilities.length == 0) {
  972. delete config.audioCapabilities;
  973. }
  974. if (config.videoCapabilities.length == 0) {
  975. delete config.videoCapabilities;
  976. }
  977. }
  978. // If we have configured preferredKeySystems, choose the preferred one if
  979. // available.
  980. for (const keySystem of this.config_.preferredKeySystems) {
  981. if (configsByKeySystem.has(keySystem)) {
  982. const config = configsByKeySystem.get(keySystem);
  983. try {
  984. mediaKeySystemAccess = // eslint-disable-next-line no-await-in-loop
  985. await navigator.requestMediaKeySystemAccess(keySystem, [config]);
  986. return mediaKeySystemAccess;
  987. } catch (error) {
  988. // Suppress errors.
  989. shaka.log.v2(
  990. 'Requesting', keySystem, 'failed with config', config, error);
  991. }
  992. this.destroyer_.ensureNotDestroyed();
  993. }
  994. }
  995. // Try key systems with configured license servers first. We only have to
  996. // try key systems without configured license servers for diagnostic
  997. // reasons, so that we can differentiate between "none of these key
  998. // systems are available" and "some are available, but you did not
  999. // configure them properly." The former takes precedence.
  1000. // TODO: once MediaCap implementation is complete, this part can be
  1001. // simplified or removed.
  1002. for (const shouldHaveLicenseServer of [true, false]) {
  1003. for (const keySystem of configsByKeySystem.keys()) {
  1004. const config = configsByKeySystem.get(keySystem);
  1005. // TODO: refactor, don't stick drmInfos onto
  1006. // MediaKeySystemConfiguration
  1007. const hasLicenseServer = config['drmInfos'].some((info) => {
  1008. return !!info.licenseServerUri;
  1009. });
  1010. if (hasLicenseServer != shouldHaveLicenseServer) {
  1011. continue;
  1012. }
  1013. try {
  1014. mediaKeySystemAccess = // eslint-disable-next-line no-await-in-loop
  1015. await navigator.requestMediaKeySystemAccess(keySystem, [config]);
  1016. return mediaKeySystemAccess;
  1017. } catch (error) {
  1018. // Suppress errors.
  1019. shaka.log.v2(
  1020. 'Requesting', keySystem, 'failed with config', config, error);
  1021. }
  1022. this.destroyer_.ensureNotDestroyed();
  1023. }
  1024. }
  1025. return mediaKeySystemAccess;
  1026. }
  1027. /**
  1028. * Create a DrmInfo using configured clear keys.
  1029. * The server URI will be a data URI which decodes to a clearkey license.
  1030. * @return {?shaka.extern.DrmInfo} or null if clear keys are not configured.
  1031. * @private
  1032. * @see https://bit.ly/2K8gOnv for the spec on the clearkey license format.
  1033. */
  1034. configureClearKey_() {
  1035. const clearKeys = shaka.util.MapUtils.asMap(this.config_.clearKeys);
  1036. if (clearKeys.size == 0) {
  1037. return null;
  1038. }
  1039. const ManifestParserUtils = shaka.util.ManifestParserUtils;
  1040. return ManifestParserUtils.createDrmInfoFromClearKeys(clearKeys);
  1041. }
  1042. /**
  1043. * Resolves the allSessionsLoaded_ promise when all the sessions are loaded
  1044. *
  1045. * @private
  1046. */
  1047. checkSessionsLoaded_() {
  1048. if (this.areAllSessionsLoaded_()) {
  1049. this.allSessionsLoaded_.resolve();
  1050. }
  1051. }
  1052. /**
  1053. * In case there are no key statuses, consider this session loaded
  1054. * after a reasonable timeout. It should definitely not take 5
  1055. * seconds to process a license.
  1056. * @param {!shaka.media.DrmEngine.SessionMetaData} metadata
  1057. * @private
  1058. */
  1059. setLoadSessionTimeoutTimer_(metadata) {
  1060. const timer = new shaka.util.Timer(() => {
  1061. metadata.loaded = true;
  1062. this.checkSessionsLoaded_();
  1063. });
  1064. timer.tickAfter(
  1065. /* seconds= */ shaka.media.DrmEngine.SESSION_LOAD_TIMEOUT_);
  1066. }
  1067. /**
  1068. * @param {string} sessionId
  1069. * @param {{initData: ?Uint8Array, initDataType: ?string}} sessionMetadata
  1070. * @return {!Promise.<MediaKeySession>}
  1071. * @private
  1072. */
  1073. async loadOfflineSession_(sessionId, sessionMetadata) {
  1074. let session;
  1075. const sessionType = 'persistent-license';
  1076. try {
  1077. shaka.log.v1('Attempting to load an offline session', sessionId);
  1078. session = this.mediaKeys_.createSession(sessionType);
  1079. } catch (exception) {
  1080. const error = new shaka.util.Error(
  1081. shaka.util.Error.Severity.CRITICAL,
  1082. shaka.util.Error.Category.DRM,
  1083. shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
  1084. exception.message);
  1085. this.onError_(error);
  1086. return Promise.reject(error);
  1087. }
  1088. this.eventManager_.listen(session, 'message',
  1089. /** @type {shaka.util.EventManager.ListenerType} */(
  1090. (event) => this.onSessionMessage_(event)));
  1091. this.eventManager_.listen(session, 'keystatuseschange',
  1092. (event) => this.onKeyStatusesChange_(event));
  1093. const metadata = {
  1094. initData: sessionMetadata.initData,
  1095. initDataType: sessionMetadata.initDataType,
  1096. loaded: false,
  1097. oldExpiration: Infinity,
  1098. updatePromise: null,
  1099. type: sessionType,
  1100. };
  1101. this.activeSessions_.set(session, metadata);
  1102. try {
  1103. const present = await session.load(sessionId);
  1104. this.destroyer_.ensureNotDestroyed();
  1105. shaka.log.v2('Loaded offline session', sessionId, present);
  1106. if (!present) {
  1107. this.activeSessions_.delete(session);
  1108. const severity = this.config_.persistentSessionOnlinePlayback ?
  1109. shaka.util.Error.Severity.RECOVERABLE :
  1110. shaka.util.Error.Severity.CRITICAL;
  1111. this.onError_(new shaka.util.Error(
  1112. severity,
  1113. shaka.util.Error.Category.DRM,
  1114. shaka.util.Error.Code.OFFLINE_SESSION_REMOVED));
  1115. metadata.loaded = true;
  1116. }
  1117. this.setLoadSessionTimeoutTimer_(metadata);
  1118. this.checkSessionsLoaded_();
  1119. return session;
  1120. } catch (error) {
  1121. this.destroyer_.ensureNotDestroyed(error);
  1122. this.activeSessions_.delete(session);
  1123. const severity = this.config_.persistentSessionOnlinePlayback ?
  1124. shaka.util.Error.Severity.RECOVERABLE :
  1125. shaka.util.Error.Severity.CRITICAL;
  1126. this.onError_(new shaka.util.Error(
  1127. severity,
  1128. shaka.util.Error.Category.DRM,
  1129. shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
  1130. error.message));
  1131. metadata.loaded = true;
  1132. this.checkSessionsLoaded_();
  1133. }
  1134. return Promise.resolve();
  1135. }
  1136. /**
  1137. * @param {string} initDataType
  1138. * @param {!Uint8Array} initData
  1139. * @param {string} sessionType
  1140. */
  1141. createSession(initDataType, initData, sessionType) {
  1142. goog.asserts.assert(this.mediaKeys_,
  1143. 'mediaKeys_ should be valid when creating temporary session.');
  1144. let session;
  1145. try {
  1146. shaka.log.info('Creating new', sessionType, 'session');
  1147. session = this.mediaKeys_.createSession(sessionType);
  1148. } catch (exception) {
  1149. this.onError_(new shaka.util.Error(
  1150. shaka.util.Error.Severity.CRITICAL,
  1151. shaka.util.Error.Category.DRM,
  1152. shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,
  1153. exception.message));
  1154. return;
  1155. }
  1156. this.eventManager_.listen(session, 'message',
  1157. /** @type {shaka.util.EventManager.ListenerType} */(
  1158. (event) => this.onSessionMessage_(event)));
  1159. this.eventManager_.listen(session, 'keystatuseschange',
  1160. (event) => this.onKeyStatusesChange_(event));
  1161. const metadata = {
  1162. initData: initData,
  1163. initDataType: initDataType,
  1164. loaded: false,
  1165. oldExpiration: Infinity,
  1166. updatePromise: null,
  1167. type: sessionType,
  1168. };
  1169. this.activeSessions_.set(session, metadata);
  1170. try {
  1171. initData = this.config_.initDataTransform(
  1172. initData, initDataType, this.currentDrmInfo_);
  1173. } catch (error) {
  1174. let shakaError = error;
  1175. if (!(error instanceof shaka.util.Error)) {
  1176. shakaError = new shaka.util.Error(
  1177. shaka.util.Error.Severity.CRITICAL,
  1178. shaka.util.Error.Category.DRM,
  1179. shaka.util.Error.Code.INIT_DATA_TRANSFORM_ERROR,
  1180. error);
  1181. }
  1182. this.onError_(shakaError);
  1183. return;
  1184. }
  1185. if (this.config_.logLicenseExchange) {
  1186. const str = shaka.util.Uint8ArrayUtils.toBase64(initData);
  1187. shaka.log.info('EME init data: type=', initDataType, 'data=', str);
  1188. }
  1189. session.generateRequest(initDataType, initData).catch((error) => {
  1190. if (this.destroyer_.destroyed()) {
  1191. return;
  1192. }
  1193. goog.asserts.assert(error instanceof Error, 'Wrong error type!');
  1194. this.activeSessions_.delete(session);
  1195. // This may be supplied by some polyfills.
  1196. /** @type {MediaKeyError} */
  1197. const errorCode = error['errorCode'];
  1198. let extended;
  1199. if (errorCode && errorCode.systemCode) {
  1200. extended = errorCode.systemCode;
  1201. if (extended < 0) {
  1202. extended += Math.pow(2, 32);
  1203. }
  1204. extended = '0x' + extended.toString(16);
  1205. }
  1206. this.onError_(new shaka.util.Error(
  1207. shaka.util.Error.Severity.CRITICAL,
  1208. shaka.util.Error.Category.DRM,
  1209. shaka.util.Error.Code.FAILED_TO_GENERATE_LICENSE_REQUEST,
  1210. error.message, error, extended));
  1211. });
  1212. }
  1213. /**
  1214. * @param {!MediaKeyMessageEvent} event
  1215. * @private
  1216. */
  1217. onSessionMessage_(event) {
  1218. if (this.delayLicenseRequest_()) {
  1219. this.mediaKeyMessageEvents_.push(event);
  1220. } else {
  1221. this.sendLicenseRequest_(event);
  1222. }
  1223. }
  1224. /**
  1225. * @return {boolean}
  1226. * @private
  1227. */
  1228. delayLicenseRequest_() {
  1229. if (!this.video_) {
  1230. // If there's no video, don't delay the license request; i.e., in the case
  1231. // of offline storage.
  1232. return false;
  1233. }
  1234. return (this.config_.delayLicenseRequestUntilPlayed &&
  1235. this.video_.paused && !this.initialRequestsSent_);
  1236. }
  1237. /**
  1238. * Sends a license request.
  1239. * @param {!MediaKeyMessageEvent} event
  1240. * @private
  1241. */
  1242. async sendLicenseRequest_(event) {
  1243. /** @type {!MediaKeySession} */
  1244. const session = event.target;
  1245. shaka.log.v1(
  1246. 'Sending license request for session', session.sessionId, 'of type',
  1247. event.messageType);
  1248. if (this.config_.logLicenseExchange) {
  1249. const str = shaka.util.Uint8ArrayUtils.toBase64(event.message);
  1250. shaka.log.info('EME license request', str);
  1251. }
  1252. const metadata = this.activeSessions_.get(session);
  1253. let url = this.currentDrmInfo_.licenseServerUri;
  1254. const advancedConfig =
  1255. this.config_.advanced[this.currentDrmInfo_.keySystem];
  1256. if (event.messageType == 'individualization-request' && advancedConfig &&
  1257. advancedConfig.individualizationServer) {
  1258. url = advancedConfig.individualizationServer;
  1259. }
  1260. const requestType = shaka.net.NetworkingEngine.RequestType.LICENSE;
  1261. const request = shaka.net.NetworkingEngine.makeRequest(
  1262. [url], this.config_.retryParameters);
  1263. request.body = event.message;
  1264. request.method = 'POST';
  1265. request.licenseRequestType = event.messageType;
  1266. request.sessionId = session.sessionId;
  1267. request.drmInfo = this.currentDrmInfo_;
  1268. if (metadata) {
  1269. request.initData = metadata.initData;
  1270. request.initDataType = metadata.initDataType;
  1271. }
  1272. if (advancedConfig && advancedConfig.headers) {
  1273. // Add these to the existing headers. Do not clobber them!
  1274. // For PlayReady, there will already be headers in the request.
  1275. for (const header in advancedConfig.headers) {
  1276. request.headers[header] = advancedConfig.headers[header];
  1277. }
  1278. }
  1279. // NOTE: allowCrossSiteCredentials can be set in a request filter.
  1280. if (shaka.util.DrmUtils.isPlayReadyKeySystem(
  1281. this.currentDrmInfo_.keySystem)) {
  1282. this.unpackPlayReadyRequest_(request);
  1283. }
  1284. const startTimeRequest = Date.now();
  1285. let response;
  1286. try {
  1287. const req = this.playerInterface_.netEngine.request(requestType, request);
  1288. response = await req.promise;
  1289. } catch (error) {
  1290. if (this.destroyer_.destroyed()) {
  1291. return;
  1292. }
  1293. // Request failed!
  1294. goog.asserts.assert(error instanceof shaka.util.Error,
  1295. 'Wrong NetworkingEngine error type!');
  1296. const shakaErr = new shaka.util.Error(
  1297. shaka.util.Error.Severity.CRITICAL,
  1298. shaka.util.Error.Category.DRM,
  1299. shaka.util.Error.Code.LICENSE_REQUEST_FAILED,
  1300. error);
  1301. if (this.activeSessions_.size == 1) {
  1302. this.onError_(shakaErr);
  1303. if (metadata && metadata.updatePromise) {
  1304. metadata.updatePromise.reject(shakaErr);
  1305. }
  1306. } else {
  1307. if (metadata && metadata.updatePromise) {
  1308. metadata.updatePromise.reject(shakaErr);
  1309. }
  1310. this.activeSessions_.delete(session);
  1311. if (this.areAllSessionsLoaded_()) {
  1312. this.allSessionsLoaded_.resolve();
  1313. this.keyStatusTimer_.tickAfter(/* seconds= */ 0.1);
  1314. }
  1315. }
  1316. return;
  1317. }
  1318. if (this.destroyer_.destroyed()) {
  1319. return;
  1320. }
  1321. this.licenseTimeSeconds_ += (Date.now() - startTimeRequest) / 1000;
  1322. if (this.config_.logLicenseExchange) {
  1323. const str = shaka.util.Uint8ArrayUtils.toBase64(response.data);
  1324. shaka.log.info('EME license response', str);
  1325. }
  1326. // Request succeeded, now pass the response to the CDM.
  1327. try {
  1328. shaka.log.v1('Updating session', session.sessionId);
  1329. await session.update(response.data);
  1330. } catch (error) {
  1331. // Session update failed!
  1332. const shakaErr = new shaka.util.Error(
  1333. shaka.util.Error.Severity.CRITICAL,
  1334. shaka.util.Error.Category.DRM,
  1335. shaka.util.Error.Code.LICENSE_RESPONSE_REJECTED,
  1336. error.message);
  1337. this.onError_(shakaErr);
  1338. if (metadata && metadata.updatePromise) {
  1339. metadata.updatePromise.reject(shakaErr);
  1340. }
  1341. return;
  1342. }
  1343. if (this.destroyer_.destroyed()) {
  1344. return;
  1345. }
  1346. const updateEvent = new shaka.util.FakeEvent('drmsessionupdate');
  1347. this.playerInterface_.onEvent(updateEvent);
  1348. if (metadata) {
  1349. if (metadata.updatePromise) {
  1350. metadata.updatePromise.resolve();
  1351. }
  1352. this.setLoadSessionTimeoutTimer_(metadata);
  1353. }
  1354. }
  1355. /**
  1356. * Unpacks PlayReady license requests. Modifies the request object.
  1357. * @param {shaka.extern.Request} request
  1358. * @private
  1359. */
  1360. unpackPlayReadyRequest_(request) {
  1361. // On Edge, the raw license message is UTF-16-encoded XML. We need
  1362. // to unpack the Challenge element (base64-encoded string containing the
  1363. // actual license request) and any HttpHeader elements (sent as request
  1364. // headers).
  1365. // Example XML:
  1366. // <PlayReadyKeyMessage type="LicenseAcquisition">
  1367. // <LicenseAcquisition Version="1">
  1368. // <Challenge encoding="base64encoded">{Base64Data}</Challenge>
  1369. // <HttpHeaders>
  1370. // <HttpHeader>
  1371. // <name>Content-Type</name>
  1372. // <value>text/xml; charset=utf-8</value>
  1373. // </HttpHeader>
  1374. // <HttpHeader>
  1375. // <name>SOAPAction</name>
  1376. // <value>http://schemas.microsoft.com/DRM/etc/etc</value>
  1377. // </HttpHeader>
  1378. // </HttpHeaders>
  1379. // </LicenseAcquisition>
  1380. // </PlayReadyKeyMessage>
  1381. const TXml = shaka.util.TXml;
  1382. const xml = shaka.util.StringUtils.fromUTF16(
  1383. request.body, /* littleEndian= */ true, /* noThrow= */ true);
  1384. if (!xml.includes('PlayReadyKeyMessage')) {
  1385. // This does not appear to be a wrapped message as on Edge. Some
  1386. // clients do not need this unwrapping, so we will assume this is one of
  1387. // them. Note that "xml" at this point probably looks like random
  1388. // garbage, since we interpreted UTF-8 as UTF-16.
  1389. shaka.log.debug('PlayReady request is already unwrapped.');
  1390. request.headers['Content-Type'] = 'text/xml; charset=utf-8';
  1391. return;
  1392. }
  1393. shaka.log.debug('Unwrapping PlayReady request.');
  1394. const dom = TXml.parseXmlString(xml, 'PlayReadyKeyMessage');
  1395. goog.asserts.assert(dom, 'Failed to parse PlayReady XML!');
  1396. // Set request headers.
  1397. const headers = TXml.getElementsByTagName(dom, 'HttpHeader');
  1398. for (const header of headers) {
  1399. const name = TXml.getElementsByTagName(header, 'name')[0];
  1400. const value = TXml.getElementsByTagName(header, 'value')[0];
  1401. goog.asserts.assert(name && value, 'Malformed PlayReady headers!');
  1402. request.headers[
  1403. /** @type {string} */(shaka.util.TXml.getTextContents(name))] =
  1404. /** @type {string} */(shaka.util.TXml.getTextContents(value));
  1405. }
  1406. // Unpack the base64-encoded challenge.
  1407. const challenge = TXml.getElementsByTagName(dom, 'Challenge')[0];
  1408. goog.asserts.assert(challenge,
  1409. 'Malformed PlayReady challenge!');
  1410. goog.asserts.assert(challenge.attributes['encoding'] == 'base64encoded',
  1411. 'Unexpected PlayReady challenge encoding!');
  1412. request.body = shaka.util.Uint8ArrayUtils.fromBase64(
  1413. /** @type{string} */(shaka.util.TXml.getTextContents(challenge)));
  1414. }
  1415. /**
  1416. * @param {!Event} event
  1417. * @private
  1418. * @suppress {invalidCasts} to swap keyId and status
  1419. */
  1420. onKeyStatusesChange_(event) {
  1421. const session = /** @type {!MediaKeySession} */(event.target);
  1422. shaka.log.v2('Key status changed for session', session.sessionId);
  1423. const found = this.activeSessions_.get(session);
  1424. const keyStatusMap = session.keyStatuses;
  1425. let hasExpiredKeys = false;
  1426. keyStatusMap.forEach((status, keyId) => {
  1427. // The spec has changed a few times on the exact order of arguments here.
  1428. // As of 2016-06-30, Edge has the order reversed compared to the current
  1429. // EME spec. Given the back and forth in the spec, it may not be the only
  1430. // one. Try to detect this and compensate:
  1431. if (typeof keyId == 'string') {
  1432. const tmp = keyId;
  1433. keyId = /** @type {!ArrayBuffer} */(status);
  1434. status = /** @type {string} */(tmp);
  1435. }
  1436. // Microsoft's implementation in Edge seems to present key IDs as
  1437. // little-endian UUIDs, rather than big-endian or just plain array of
  1438. // bytes.
  1439. // standard: 6e 5a 1d 26 - 27 57 - 47 d7 - 80 46 ea a5 d1 d3 4b 5a
  1440. // on Edge: 26 1d 5a 6e - 57 27 - d7 47 - 80 46 ea a5 d1 d3 4b 5a
  1441. // Bug filed: https://bit.ly/2thuzXu
  1442. // NOTE that we skip this if byteLength != 16. This is used for Edge
  1443. // which uses single-byte dummy key IDs.
  1444. // However, unlike Edge and Chromecast, Tizen doesn't have this problem.
  1445. if (shaka.util.DrmUtils.isPlayReadyKeySystem(
  1446. this.currentDrmInfo_.keySystem) &&
  1447. keyId.byteLength == 16 &&
  1448. (shaka.util.Platform.isEdge() || shaka.util.Platform.isPS4())) {
  1449. // Read out some fields in little-endian:
  1450. const dataView = shaka.util.BufferUtils.toDataView(keyId);
  1451. const part0 = dataView.getUint32(0, /* LE= */ true);
  1452. const part1 = dataView.getUint16(4, /* LE= */ true);
  1453. const part2 = dataView.getUint16(6, /* LE= */ true);
  1454. // Write it back in big-endian:
  1455. dataView.setUint32(0, part0, /* BE= */ false);
  1456. dataView.setUint16(4, part1, /* BE= */ false);
  1457. dataView.setUint16(6, part2, /* BE= */ false);
  1458. }
  1459. if (status != 'status-pending') {
  1460. found.loaded = true;
  1461. }
  1462. if (!found) {
  1463. // We can get a key status changed for a closed session after it has
  1464. // been removed from |activeSessions_|. If it is closed, none of its
  1465. // keys should be usable.
  1466. goog.asserts.assert(
  1467. status != 'usable', 'Usable keys found in closed session');
  1468. }
  1469. if (status == 'expired') {
  1470. hasExpiredKeys = true;
  1471. }
  1472. const keyIdHex = shaka.util.Uint8ArrayUtils.toHex(keyId).slice(0, 32);
  1473. this.keyStatusByKeyId_.set(keyIdHex, status);
  1474. });
  1475. // If the session has expired, close it.
  1476. // Some CDMs do not have sub-second time resolution, so the key status may
  1477. // fire with hundreds of milliseconds left until the stated expiration time.
  1478. const msUntilExpiration = session.expiration - Date.now();
  1479. if (msUntilExpiration < 0 || (hasExpiredKeys && msUntilExpiration < 1000)) {
  1480. // If this is part of a remove(), we don't want to close the session until
  1481. // the update is complete. Otherwise, we will orphan the session.
  1482. if (found && !found.updatePromise) {
  1483. shaka.log.debug('Session has expired', session.sessionId);
  1484. this.activeSessions_.delete(session);
  1485. session.close().catch(() => {}); // Silence uncaught rejection errors
  1486. }
  1487. }
  1488. if (!this.areAllSessionsLoaded_()) {
  1489. // Don't announce key statuses or resolve the "all loaded" promise until
  1490. // everything is loaded.
  1491. return;
  1492. }
  1493. this.allSessionsLoaded_.resolve();
  1494. // Batch up key status changes before checking them or notifying Player.
  1495. // This handles cases where the statuses of multiple sessions are set
  1496. // simultaneously by the browser before dispatching key status changes for
  1497. // each of them. By batching these up, we only send one status change event
  1498. // and at most one EXPIRED error on expiration.
  1499. this.keyStatusTimer_.tickAfter(
  1500. /* seconds= */ shaka.media.DrmEngine.KEY_STATUS_BATCH_TIME);
  1501. }
  1502. /** @private */
  1503. processKeyStatusChanges_() {
  1504. const privateMap = this.keyStatusByKeyId_;
  1505. const publicMap = this.announcedKeyStatusByKeyId_;
  1506. // Copy the latest key statuses into the publicly-accessible map.
  1507. publicMap.clear();
  1508. privateMap.forEach((status, keyId) => publicMap.set(keyId, status));
  1509. // If all keys are expired, fire an error. |every| is always true for an
  1510. // empty array but we shouldn't fire an error for a lack of key status info.
  1511. const statuses = Array.from(publicMap.values());
  1512. const allExpired = statuses.length &&
  1513. statuses.every((status) => status == 'expired');
  1514. if (allExpired) {
  1515. this.onError_(new shaka.util.Error(
  1516. shaka.util.Error.Severity.CRITICAL,
  1517. shaka.util.Error.Category.DRM,
  1518. shaka.util.Error.Code.EXPIRED));
  1519. }
  1520. this.playerInterface_.onKeyStatus(shaka.util.MapUtils.asObject(publicMap));
  1521. }
  1522. /**
  1523. * Returns a Promise to a map of EME support for well-known key systems.
  1524. *
  1525. * @return {!Promise.<!Object.<string, ?shaka.extern.DrmSupportType>>}
  1526. */
  1527. static async probeSupport() {
  1528. goog.asserts.assert(shaka.util.DrmUtils.isBrowserSupported(),
  1529. 'Must have basic EME support');
  1530. const testKeySystems = [
  1531. 'org.w3.clearkey',
  1532. 'com.widevine.alpha',
  1533. 'com.microsoft.playready',
  1534. 'com.microsoft.playready.hardware',
  1535. 'com.microsoft.playready.recommendation',
  1536. 'com.chromecast.playready',
  1537. 'com.apple.fps.1_0',
  1538. 'com.apple.fps',
  1539. ];
  1540. const widevineRobustness = [
  1541. 'SW_SECURE_CRYPTO',
  1542. 'SW_SECURE_DECODE',
  1543. 'HW_SECURE_CRYPTO',
  1544. 'HW_SECURE_DECODE',
  1545. 'HW_SECURE_ALL',
  1546. ];
  1547. const playreadyRobustness = [
  1548. '150',
  1549. '2000',
  1550. '3000',
  1551. ];
  1552. const testRobustness = {
  1553. 'com.widevine.alpha': widevineRobustness,
  1554. 'com.microsoft.playready.recommendation': playreadyRobustness,
  1555. };
  1556. const basicVideoCapabilities = [
  1557. {contentType: 'video/mp4; codecs="avc1.42E01E"'},
  1558. {contentType: 'video/webm; codecs="vp8"'},
  1559. ];
  1560. const basicAudioCapabilities = [
  1561. {contentType: 'audio/mp4; codecs="mp4a.40.2"'},
  1562. {contentType: 'audio/webm; codecs="opus"'},
  1563. ];
  1564. const basicConfigTemplate = {
  1565. videoCapabilities: basicVideoCapabilities,
  1566. audioCapabilities: basicAudioCapabilities,
  1567. initDataTypes: ['cenc', 'sinf', 'skd', 'keyids'],
  1568. };
  1569. const testEncryptionSchemes = [
  1570. null,
  1571. 'cenc',
  1572. 'cbcs',
  1573. 'cbcs-1-9',
  1574. ];
  1575. /** @type {!Map.<string, ?shaka.extern.DrmSupportType>} */
  1576. const support = new Map();
  1577. /**
  1578. * @param {string} keySystem
  1579. * @param {MediaKeySystemAccess} access
  1580. * @return {!Promise}
  1581. */
  1582. const processMediaKeySystemAccess = async (keySystem, access) => {
  1583. try {
  1584. await access.createMediaKeys();
  1585. } catch (error) {
  1586. // In some cases, we can get a successful access object but fail to
  1587. // create a MediaKeys instance. When this happens, don't update the
  1588. // support structure. If a previous test succeeded, we won't overwrite
  1589. // any of the results.
  1590. return;
  1591. }
  1592. // If sessionTypes is missing, assume no support for persistent-license.
  1593. const sessionTypes = access.getConfiguration().sessionTypes;
  1594. let persistentState = sessionTypes ?
  1595. sessionTypes.includes('persistent-license') : false;
  1596. // Tizen 3.0 doesn't support persistent licenses, but reports that it
  1597. // does. It doesn't fail until you call update() with a license
  1598. // response, which is way too late.
  1599. // This is a work-around for #894.
  1600. if (shaka.util.Platform.isTizen3()) {
  1601. persistentState = false;
  1602. }
  1603. const videoCapabilities = access.getConfiguration().videoCapabilities;
  1604. const audioCapabilities = access.getConfiguration().audioCapabilities;
  1605. let supportValue = {
  1606. persistentState,
  1607. encryptionSchemes: [],
  1608. videoRobustnessLevels: [],
  1609. audioRobustnessLevels: [],
  1610. };
  1611. if (support.has(keySystem) && support.get(keySystem)) {
  1612. // Update the existing non-null value.
  1613. supportValue = support.get(keySystem);
  1614. } else {
  1615. // Set a new one.
  1616. support.set(keySystem, supportValue);
  1617. }
  1618. // If the returned config doesn't mention encryptionScheme, the field
  1619. // is not supported. If installed, our polyfills should make sure this
  1620. // doesn't happen.
  1621. const returnedScheme = videoCapabilities[0].encryptionScheme;
  1622. if (returnedScheme &&
  1623. !supportValue.encryptionSchemes.includes(returnedScheme)) {
  1624. supportValue.encryptionSchemes.push(returnedScheme);
  1625. }
  1626. const videoRobustness = videoCapabilities[0].robustness;
  1627. if (videoRobustness &&
  1628. !supportValue.videoRobustnessLevels.includes(videoRobustness)) {
  1629. supportValue.videoRobustnessLevels.push(videoRobustness);
  1630. }
  1631. const audioRobustness = audioCapabilities[0].robustness;
  1632. if (audioRobustness &&
  1633. !supportValue.audioRobustnessLevels.includes(audioRobustness)) {
  1634. supportValue.audioRobustnessLevels.push(audioRobustness);
  1635. }
  1636. };
  1637. const testSystemEme = async (keySystem, encryptionScheme,
  1638. videoRobustness, audioRobustness) => {
  1639. try {
  1640. const basicConfig =
  1641. shaka.util.ObjectUtils.cloneObject(basicConfigTemplate);
  1642. for (const cap of basicConfig.videoCapabilities) {
  1643. cap.encryptionScheme = encryptionScheme;
  1644. cap.robustness = videoRobustness;
  1645. }
  1646. for (const cap of basicConfig.audioCapabilities) {
  1647. cap.encryptionScheme = encryptionScheme;
  1648. cap.robustness = audioRobustness;
  1649. }
  1650. const offlineConfig = shaka.util.ObjectUtils.cloneObject(basicConfig);
  1651. offlineConfig.persistentState = 'required';
  1652. offlineConfig.sessionTypes = ['persistent-license'];
  1653. const configs = [offlineConfig, basicConfig];
  1654. const access = await navigator.requestMediaKeySystemAccess(
  1655. keySystem, configs);
  1656. await processMediaKeySystemAccess(keySystem, access);
  1657. } catch (error) {} // Ignore errors.
  1658. };
  1659. const testSystemMcap = async (keySystem, encryptionScheme,
  1660. videoRobustness, audioRobustness) => {
  1661. try {
  1662. const decodingConfig = {
  1663. type: 'media-source',
  1664. video: {
  1665. contentType: basicVideoCapabilities[0].contentType,
  1666. width: 640,
  1667. height: 480,
  1668. bitrate: 1,
  1669. framerate: 1,
  1670. },
  1671. audio: {
  1672. contentType: basicAudioCapabilities[0].contentType,
  1673. channels: 2,
  1674. bitrate: 1,
  1675. samplerate: 1,
  1676. },
  1677. keySystemConfiguration: {
  1678. keySystem,
  1679. video: {
  1680. encryptionScheme,
  1681. robustness: videoRobustness,
  1682. },
  1683. audio: {
  1684. encryptionScheme,
  1685. robustness: audioRobustness,
  1686. },
  1687. },
  1688. };
  1689. const decodingInfo =
  1690. await navigator.mediaCapabilities.decodingInfo(decodingConfig);
  1691. const access = decodingInfo.keySystemAccess;
  1692. await processMediaKeySystemAccess(keySystem, access);
  1693. } catch (error) {} // Ignore errors.
  1694. };
  1695. // Initialize the support structure for each key system.
  1696. for (const keySystem of testKeySystems) {
  1697. support.set(keySystem, null);
  1698. }
  1699. // Test each key system and encryption scheme.
  1700. const tests = [];
  1701. for (const encryptionScheme of testEncryptionSchemes) {
  1702. for (const keySystem of testKeySystems) {
  1703. // Our Polyfill will reject anything apart com.apple.fps key systems.
  1704. // It seems the Safari modern EME API will allow to request a
  1705. // MediaKeySystemAccess for the ClearKey CDM, create and update a key
  1706. // session but playback will never start
  1707. // Safari bug: https://bugs.webkit.org/show_bug.cgi?id=231006
  1708. if (keySystem === 'org.w3.clearkey' &&
  1709. shaka.util.Platform.isSafari()) {
  1710. continue;
  1711. }
  1712. tests.push(testSystemEme(keySystem, encryptionScheme, '', ''));
  1713. tests.push(testSystemMcap(keySystem, encryptionScheme, '', ''));
  1714. }
  1715. }
  1716. for (const keySystem of testKeySystems) {
  1717. for (const robustness of (testRobustness[keySystem] || [])) {
  1718. tests.push(testSystemEme(keySystem, null, robustness, ''));
  1719. tests.push(testSystemEme(keySystem, null, '', robustness));
  1720. tests.push(testSystemMcap(keySystem, null, robustness, ''));
  1721. tests.push(testSystemMcap(keySystem, null, '', robustness));
  1722. }
  1723. }
  1724. await Promise.all(tests);
  1725. return shaka.util.MapUtils.asObject(support);
  1726. }
  1727. /** @private */
  1728. onPlay_() {
  1729. for (const event of this.mediaKeyMessageEvents_) {
  1730. this.sendLicenseRequest_(event);
  1731. }
  1732. this.initialRequestsSent_ = true;
  1733. this.mediaKeyMessageEvents_ = [];
  1734. }
  1735. /**
  1736. * Close a drm session while accounting for a bug in Chrome. Sometimes the
  1737. * Promise returned by close() never resolves.
  1738. *
  1739. * See issue #2741 and http://crbug.com/1108158.
  1740. * @param {!MediaKeySession} session
  1741. * @return {!Promise}
  1742. * @private
  1743. */
  1744. async closeSession_(session) {
  1745. const DrmEngine = shaka.media.DrmEngine;
  1746. const timeout = new Promise((resolve, reject) => {
  1747. const timer = new shaka.util.Timer(reject);
  1748. timer.tickAfter(DrmEngine.CLOSE_TIMEOUT_);
  1749. });
  1750. try {
  1751. await Promise.race([
  1752. Promise.all([session.close(), session.closed]),
  1753. timeout,
  1754. ]);
  1755. } catch (e) {
  1756. shaka.log.warning('Timeout waiting for session close');
  1757. }
  1758. }
  1759. /** @private */
  1760. async closeOpenSessions_() {
  1761. // Close all open sessions.
  1762. const openSessions = Array.from(this.activeSessions_.entries());
  1763. this.activeSessions_.clear();
  1764. // Close all sessions before we remove media keys from the video element.
  1765. await Promise.all(openSessions.map(async ([session, metadata]) => {
  1766. try {
  1767. /**
  1768. * Special case when a persistent-license session has been initiated,
  1769. * without being registered in the offline sessions at start-up.
  1770. * We should remove the session to prevent it from being orphaned after
  1771. * the playback session ends
  1772. */
  1773. if (!this.initializedForStorage_ &&
  1774. !this.storedPersistentSessions_.has(session.sessionId) &&
  1775. metadata.type === 'persistent-license' &&
  1776. !this.config_.persistentSessionOnlinePlayback) {
  1777. shaka.log.v1('Removing session', session.sessionId);
  1778. await session.remove();
  1779. } else {
  1780. shaka.log.v1('Closing session', session.sessionId, metadata);
  1781. await this.closeSession_(session);
  1782. }
  1783. } catch (error) {
  1784. // Ignore errors when closing the sessions. Closing a session that
  1785. // generated no key requests will throw an error.
  1786. shaka.log.error('Failed to close or remove the session', error);
  1787. }
  1788. }));
  1789. }
  1790. /**
  1791. * Check if a variant is likely to be supported by DrmEngine. This will err on
  1792. * the side of being too accepting and may not reject a variant that it will
  1793. * later fail to play.
  1794. *
  1795. * @param {!shaka.extern.Variant} variant
  1796. * @return {boolean}
  1797. */
  1798. supportsVariant(variant) {
  1799. /** @type {?shaka.extern.Stream} */
  1800. const audio = variant.audio;
  1801. /** @type {?shaka.extern.Stream} */
  1802. const video = variant.video;
  1803. if (audio && audio.encrypted) {
  1804. const audioContentType = shaka.media.DrmEngine.computeMimeType_(audio);
  1805. if (!this.willSupport(audioContentType)) {
  1806. return false;
  1807. }
  1808. }
  1809. if (video && video.encrypted) {
  1810. const videoContentType = shaka.media.DrmEngine.computeMimeType_(video);
  1811. if (!this.willSupport(videoContentType)) {
  1812. return false;
  1813. }
  1814. }
  1815. const keySystem = shaka.util.DrmUtils.keySystem(this.currentDrmInfo_);
  1816. const drmInfos = this.getVariantDrmInfos_(variant);
  1817. return drmInfos.length == 0 ||
  1818. drmInfos.some((drmInfo) => drmInfo.keySystem == keySystem);
  1819. }
  1820. /**
  1821. * Concat the audio and video drmInfos in a variant.
  1822. * @param {shaka.extern.Variant} variant
  1823. * @return {!Array.<!shaka.extern.DrmInfo>}
  1824. * @private
  1825. */
  1826. getVariantDrmInfos_(variant) {
  1827. const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
  1828. const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
  1829. return videoDrmInfos.concat(audioDrmInfos);
  1830. }
  1831. /**
  1832. * Called in an interval timer to poll the expiration times of the sessions.
  1833. * We don't get an event from EME when the expiration updates, so we poll it
  1834. * so we can fire an event when it happens.
  1835. * @private
  1836. */
  1837. pollExpiration_() {
  1838. this.activeSessions_.forEach((metadata, session) => {
  1839. const oldTime = metadata.oldExpiration;
  1840. let newTime = session.expiration;
  1841. if (isNaN(newTime)) {
  1842. newTime = Infinity;
  1843. }
  1844. if (newTime != oldTime) {
  1845. this.playerInterface_.onExpirationUpdated(session.sessionId, newTime);
  1846. metadata.oldExpiration = newTime;
  1847. }
  1848. });
  1849. }
  1850. /**
  1851. * @return {boolean}
  1852. * @private
  1853. */
  1854. areAllSessionsLoaded_() {
  1855. const metadatas = this.activeSessions_.values();
  1856. return shaka.util.Iterables.every(metadatas, (data) => data.loaded);
  1857. }
  1858. /**
  1859. * @return {boolean}
  1860. * @private
  1861. */
  1862. areAllKeysUsable_() {
  1863. const keyIds = (this.currentDrmInfo_ && this.currentDrmInfo_.keyIds) ||
  1864. new Set([]);
  1865. for (const keyId of keyIds) {
  1866. const status = this.keyStatusByKeyId_.get(keyId);
  1867. if (status !== 'usable') {
  1868. return false;
  1869. }
  1870. }
  1871. return true;
  1872. }
  1873. /**
  1874. * Replace the drm info used in each variant in |variants| to reflect each
  1875. * key service in |keySystems|.
  1876. *
  1877. * @param {!Array.<shaka.extern.Variant>} variants
  1878. * @param {!Map.<string, string>} keySystems
  1879. * @private
  1880. */
  1881. static replaceDrmInfo_(variants, keySystems) {
  1882. const drmInfos = [];
  1883. keySystems.forEach((uri, keySystem) => {
  1884. drmInfos.push({
  1885. keySystem: keySystem,
  1886. licenseServerUri: uri,
  1887. distinctiveIdentifierRequired: false,
  1888. persistentStateRequired: false,
  1889. audioRobustness: '',
  1890. videoRobustness: '',
  1891. serverCertificate: null,
  1892. serverCertificateUri: '',
  1893. initData: [],
  1894. keyIds: new Set(),
  1895. });
  1896. });
  1897. for (const variant of variants) {
  1898. if (variant.video) {
  1899. variant.video.drmInfos = drmInfos;
  1900. }
  1901. if (variant.audio) {
  1902. variant.audio.drmInfos = drmInfos;
  1903. }
  1904. }
  1905. }
  1906. /**
  1907. * Creates a DrmInfo object describing the settings used to initialize the
  1908. * engine.
  1909. *
  1910. * @param {string} keySystem
  1911. * @param {!Array.<shaka.extern.DrmInfo>} drmInfos
  1912. * @return {shaka.extern.DrmInfo}
  1913. *
  1914. * @private
  1915. */
  1916. createDrmInfoByInfos_(keySystem, drmInfos) {
  1917. /** @type {!Array.<string>} */
  1918. const encryptionSchemes = [];
  1919. /** @type {!Array.<string>} */
  1920. const licenseServers = [];
  1921. /** @type {!Array.<string>} */
  1922. const serverCertificateUris = [];
  1923. /** @type {!Array.<!Uint8Array>} */
  1924. const serverCerts = [];
  1925. /** @type {!Array.<!shaka.extern.InitDataOverride>} */
  1926. const initDatas = [];
  1927. /** @type {!Set.<string>} */
  1928. const keyIds = new Set();
  1929. /** @type {!Set.<string>} */
  1930. const keySystemUris = new Set();
  1931. shaka.media.DrmEngine.processDrmInfos_(
  1932. drmInfos, encryptionSchemes, licenseServers, serverCerts,
  1933. serverCertificateUris, initDatas, keyIds, keySystemUris);
  1934. if (encryptionSchemes.length > 1) {
  1935. shaka.log.warning('Multiple unique encryption schemes found! ' +
  1936. 'Only the first will be used.');
  1937. }
  1938. if (serverCerts.length > 1) {
  1939. shaka.log.warning('Multiple unique server certificates found! ' +
  1940. 'Only the first will be used.');
  1941. }
  1942. if (licenseServers.length > 1) {
  1943. shaka.log.warning('Multiple unique license server URIs found! ' +
  1944. 'Only the first will be used.');
  1945. }
  1946. if (serverCertificateUris.length > 1) {
  1947. shaka.log.warning('Multiple unique server certificate URIs found! ' +
  1948. 'Only the first will be used.');
  1949. }
  1950. const defaultSessionType =
  1951. this.usePersistentLicenses_ ? 'persistent-license' : 'temporary';
  1952. /** @type {shaka.extern.DrmInfo} */
  1953. const res = {
  1954. keySystem,
  1955. encryptionScheme: encryptionSchemes[0],
  1956. licenseServerUri: licenseServers[0],
  1957. distinctiveIdentifierRequired: drmInfos[0].distinctiveIdentifierRequired,
  1958. persistentStateRequired: drmInfos[0].persistentStateRequired,
  1959. sessionType: drmInfos[0].sessionType || defaultSessionType,
  1960. audioRobustness: drmInfos[0].audioRobustness || '',
  1961. videoRobustness: drmInfos[0].videoRobustness || '',
  1962. serverCertificate: serverCerts[0],
  1963. serverCertificateUri: serverCertificateUris[0],
  1964. initData: initDatas,
  1965. keyIds,
  1966. };
  1967. if (keySystemUris.size > 0) {
  1968. res.keySystemUris = keySystemUris;
  1969. }
  1970. for (const info of drmInfos) {
  1971. if (info.distinctiveIdentifierRequired) {
  1972. res.distinctiveIdentifierRequired = info.distinctiveIdentifierRequired;
  1973. }
  1974. if (info.persistentStateRequired) {
  1975. res.persistentStateRequired = info.persistentStateRequired;
  1976. }
  1977. }
  1978. return res;
  1979. }
  1980. /**
  1981. * Creates a DrmInfo object describing the settings used to initialize the
  1982. * engine.
  1983. *
  1984. * @param {string} keySystem
  1985. * @param {MediaKeySystemConfiguration} config
  1986. * @return {shaka.extern.DrmInfo}
  1987. *
  1988. * @private
  1989. */
  1990. static createDrmInfoByConfigs_(keySystem, config) {
  1991. /** @type {!Array.<string>} */
  1992. const encryptionSchemes = [];
  1993. /** @type {!Array.<string>} */
  1994. const licenseServers = [];
  1995. /** @type {!Array.<string>} */
  1996. const serverCertificateUris = [];
  1997. /** @type {!Array.<!Uint8Array>} */
  1998. const serverCerts = [];
  1999. /** @type {!Array.<!shaka.extern.InitDataOverride>} */
  2000. const initDatas = [];
  2001. /** @type {!Set.<string>} */
  2002. const keyIds = new Set();
  2003. // TODO: refactor, don't stick drmInfos onto MediaKeySystemConfiguration
  2004. shaka.media.DrmEngine.processDrmInfos_(
  2005. config['drmInfos'], encryptionSchemes, licenseServers, serverCerts,
  2006. serverCertificateUris, initDatas, keyIds);
  2007. if (encryptionSchemes.length > 1) {
  2008. shaka.log.warning('Multiple unique encryption schemes found! ' +
  2009. 'Only the first will be used.');
  2010. }
  2011. if (serverCerts.length > 1) {
  2012. shaka.log.warning('Multiple unique server certificates found! ' +
  2013. 'Only the first will be used.');
  2014. }
  2015. if (serverCertificateUris.length > 1) {
  2016. shaka.log.warning('Multiple unique server certificate URIs found! ' +
  2017. 'Only the first will be used.');
  2018. }
  2019. if (licenseServers.length > 1) {
  2020. shaka.log.warning('Multiple unique license server URIs found! ' +
  2021. 'Only the first will be used.');
  2022. }
  2023. // TODO: This only works when all DrmInfo have the same robustness.
  2024. const audioRobustness =
  2025. config.audioCapabilities ? config.audioCapabilities[0].robustness : '';
  2026. const videoRobustness =
  2027. config.videoCapabilities ? config.videoCapabilities[0].robustness : '';
  2028. const distinctiveIdentifier = config.distinctiveIdentifier;
  2029. return {
  2030. keySystem,
  2031. encryptionScheme: encryptionSchemes[0],
  2032. licenseServerUri: licenseServers[0],
  2033. distinctiveIdentifierRequired: (distinctiveIdentifier == 'required'),
  2034. persistentStateRequired: (config.persistentState == 'required'),
  2035. sessionType: config.sessionTypes[0] || 'temporary',
  2036. audioRobustness: audioRobustness || '',
  2037. videoRobustness: videoRobustness || '',
  2038. serverCertificate: serverCerts[0],
  2039. serverCertificateUri: serverCertificateUris[0],
  2040. initData: initDatas,
  2041. keyIds,
  2042. };
  2043. }
  2044. /**
  2045. * Extract license server, server cert, and init data from |drmInfos|, taking
  2046. * care to eliminate duplicates.
  2047. *
  2048. * @param {!Array.<shaka.extern.DrmInfo>} drmInfos
  2049. * @param {!Array.<string>} licenseServers
  2050. * @param {!Array.<string>} encryptionSchemes
  2051. * @param {!Array.<!Uint8Array>} serverCerts
  2052. * @param {!Array.<string>} serverCertificateUris
  2053. * @param {!Array.<!shaka.extern.InitDataOverride>} initDatas
  2054. * @param {!Set.<string>} keyIds
  2055. * @param {!Set.<string>} [keySystemUris]
  2056. * @private
  2057. */
  2058. static processDrmInfos_(
  2059. drmInfos, encryptionSchemes, licenseServers, serverCerts,
  2060. serverCertificateUris, initDatas, keyIds, keySystemUris) {
  2061. /** @type {function(shaka.extern.InitDataOverride,
  2062. * shaka.extern.InitDataOverride):boolean} */
  2063. const initDataOverrideEqual = (a, b) => {
  2064. if (a.keyId && a.keyId == b.keyId) {
  2065. // Two initDatas with the same keyId are considered to be the same,
  2066. // unless that "same keyId" is null.
  2067. return true;
  2068. }
  2069. return a.initDataType == b.initDataType &&
  2070. shaka.util.BufferUtils.equal(a.initData, b.initData);
  2071. };
  2072. const clearkeyDataStart = 'data:application/json;base64,';
  2073. const clearKeyLicenseServers = [];
  2074. for (const drmInfo of drmInfos) {
  2075. // Build an array of unique encryption schemes.
  2076. if (!encryptionSchemes.includes(drmInfo.encryptionScheme)) {
  2077. encryptionSchemes.push(drmInfo.encryptionScheme);
  2078. }
  2079. // Build an array of unique license servers.
  2080. if (drmInfo.keySystem == 'org.w3.clearkey' &&
  2081. drmInfo.licenseServerUri.startsWith(clearkeyDataStart)) {
  2082. if (!clearKeyLicenseServers.includes(drmInfo.licenseServerUri)) {
  2083. clearKeyLicenseServers.push(drmInfo.licenseServerUri);
  2084. }
  2085. } else if (!licenseServers.includes(drmInfo.licenseServerUri)) {
  2086. licenseServers.push(drmInfo.licenseServerUri);
  2087. }
  2088. // Build an array of unique license servers.
  2089. if (!serverCertificateUris.includes(drmInfo.serverCertificateUri)) {
  2090. serverCertificateUris.push(drmInfo.serverCertificateUri);
  2091. }
  2092. // Build an array of unique server certs.
  2093. if (drmInfo.serverCertificate) {
  2094. const found = serverCerts.some(
  2095. (cert) => shaka.util.BufferUtils.equal(
  2096. cert, drmInfo.serverCertificate));
  2097. if (!found) {
  2098. serverCerts.push(drmInfo.serverCertificate);
  2099. }
  2100. }
  2101. // Build an array of unique init datas.
  2102. if (drmInfo.initData) {
  2103. for (const initDataOverride of drmInfo.initData) {
  2104. const found = initDatas.some(
  2105. (initData) =>
  2106. initDataOverrideEqual(initData, initDataOverride));
  2107. if (!found) {
  2108. initDatas.push(initDataOverride);
  2109. }
  2110. }
  2111. }
  2112. if (drmInfo.keyIds) {
  2113. for (const keyId of drmInfo.keyIds) {
  2114. keyIds.add(keyId);
  2115. }
  2116. }
  2117. if (drmInfo.keySystemUris && keySystemUris) {
  2118. for (const keySystemUri of drmInfo.keySystemUris) {
  2119. keySystemUris.add(keySystemUri);
  2120. }
  2121. }
  2122. }
  2123. if (clearKeyLicenseServers.length == 1) {
  2124. licenseServers.push(clearKeyLicenseServers[0]);
  2125. } else if (clearKeyLicenseServers.length > 0) {
  2126. const keys = [];
  2127. for (const clearKeyLicenseServer of clearKeyLicenseServers) {
  2128. const license = window.atob(
  2129. clearKeyLicenseServer.split(clearkeyDataStart).pop());
  2130. const jwkSet = /** @type {{keys: !Array}} */(JSON.parse(license));
  2131. keys.push(...jwkSet.keys);
  2132. }
  2133. const newJwkSet = {keys: keys};
  2134. const newLicense = JSON.stringify(newJwkSet);
  2135. licenseServers.push(clearkeyDataStart + window.btoa(newLicense));
  2136. }
  2137. }
  2138. /**
  2139. * Use |servers| and |advancedConfigs| to fill in missing values in drmInfo
  2140. * that the parser left blank. Before working with any drmInfo, it should be
  2141. * passed through here as it is uncommon for drmInfo to be complete when
  2142. * fetched from a manifest because most manifest formats do not have the
  2143. * required information. Also applies the key systems mapping.
  2144. *
  2145. * @param {shaka.extern.DrmInfo} drmInfo
  2146. * @param {!Map.<string, string>} servers
  2147. * @param {!Map.<string, shaka.extern.AdvancedDrmConfiguration>}
  2148. * advancedConfigs
  2149. * @param {!Object.<string, string>} keySystemsMapping
  2150. * @private
  2151. */
  2152. static fillInDrmInfoDefaults_(drmInfo, servers, advancedConfigs,
  2153. keySystemsMapping) {
  2154. const originalKeySystem = drmInfo.keySystem;
  2155. if (!originalKeySystem) {
  2156. // This is a placeholder from the manifest parser for an unrecognized key
  2157. // system. Skip this entry, to avoid logging nonsensical errors.
  2158. return;
  2159. }
  2160. // The order of preference for drmInfo:
  2161. // 1. Clear Key config, used for debugging, should override everything else.
  2162. // (The application can still specify a clearkey license server.)
  2163. // 2. Application-configured servers, if any are present, should override
  2164. // anything from the manifest. Nuance: if key system A is in the
  2165. // manifest and key system B is in the player config, only B will be
  2166. // used, not A.
  2167. // 3. Manifest-provided license servers are only used if nothing else is
  2168. // specified.
  2169. // This is important because it allows the application a clear way to
  2170. // indicate which DRM systems should be used on platforms with multiple DRM
  2171. // systems.
  2172. // The only way to get license servers from the manifest is not to specify
  2173. // any in your player config.
  2174. if (originalKeySystem == 'org.w3.clearkey' && drmInfo.licenseServerUri) {
  2175. // Preference 1: Clear Key with pre-configured keys will have a data URI
  2176. // assigned as its license server. Don't change anything.
  2177. return;
  2178. } else if (servers.size) {
  2179. // Preference 2: If anything is configured at the application level,
  2180. // override whatever was in the manifest.
  2181. const server = servers.get(originalKeySystem) || '';
  2182. drmInfo.licenseServerUri = server;
  2183. } else {
  2184. // Preference 3: Keep whatever we had in drmInfo.licenseServerUri, which
  2185. // comes from the manifest.
  2186. }
  2187. if (!drmInfo.keyIds) {
  2188. drmInfo.keyIds = new Set();
  2189. }
  2190. const advancedConfig = advancedConfigs.get(originalKeySystem);
  2191. if (advancedConfig) {
  2192. if (!drmInfo.distinctiveIdentifierRequired) {
  2193. drmInfo.distinctiveIdentifierRequired =
  2194. advancedConfig.distinctiveIdentifierRequired;
  2195. }
  2196. if (!drmInfo.persistentStateRequired) {
  2197. drmInfo.persistentStateRequired =
  2198. advancedConfig.persistentStateRequired;
  2199. }
  2200. if (!drmInfo.videoRobustness) {
  2201. drmInfo.videoRobustness = advancedConfig.videoRobustness;
  2202. }
  2203. if (!drmInfo.audioRobustness) {
  2204. drmInfo.audioRobustness = advancedConfig.audioRobustness;
  2205. }
  2206. if (!drmInfo.serverCertificate) {
  2207. drmInfo.serverCertificate = advancedConfig.serverCertificate;
  2208. }
  2209. if (advancedConfig.sessionType) {
  2210. drmInfo.sessionType = advancedConfig.sessionType;
  2211. }
  2212. if (!drmInfo.serverCertificateUri) {
  2213. drmInfo.serverCertificateUri = advancedConfig.serverCertificateUri;
  2214. }
  2215. }
  2216. if (keySystemsMapping[originalKeySystem]) {
  2217. drmInfo.keySystem = keySystemsMapping[originalKeySystem];
  2218. }
  2219. // Chromecast has a variant of PlayReady that uses a different key
  2220. // system ID. Since manifest parsers convert the standard PlayReady
  2221. // UUID to the standard PlayReady key system ID, here we will switch
  2222. // to the Chromecast version if we are running on that platform.
  2223. // Note that this must come after fillInDrmInfoDefaults_, since the
  2224. // player config uses the standard PlayReady ID for license server
  2225. // configuration.
  2226. if (window.cast && window.cast.__platform__) {
  2227. if (originalKeySystem == 'com.microsoft.playready') {
  2228. drmInfo.keySystem = 'com.chromecast.playready';
  2229. }
  2230. }
  2231. }
  2232. /**
  2233. * Parse pssh from a media segment and announce new initData
  2234. *
  2235. * @param {shaka.util.ManifestParserUtils.ContentType} contentType
  2236. * @param {!BufferSource} mediaSegment
  2237. * @return {!Promise<void>}
  2238. */
  2239. parseInbandPssh(contentType, mediaSegment) {
  2240. if (!this.config_.parseInbandPsshEnabled || this.manifestInitData_) {
  2241. return Promise.resolve();
  2242. }
  2243. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  2244. if (![ContentType.AUDIO, ContentType.VIDEO].includes(contentType)) {
  2245. return Promise.resolve();
  2246. }
  2247. const pssh = new shaka.util.Pssh(
  2248. shaka.util.BufferUtils.toUint8(mediaSegment));
  2249. let totalLength = 0;
  2250. for (const data of pssh.data) {
  2251. totalLength += data.length;
  2252. }
  2253. if (totalLength == 0) {
  2254. return Promise.resolve();
  2255. }
  2256. const combinedData = new Uint8Array(totalLength);
  2257. let pos = 0;
  2258. for (const data of pssh.data) {
  2259. combinedData.set(data, pos);
  2260. pos += data.length;
  2261. }
  2262. this.newInitData('cenc', combinedData);
  2263. return this.allSessionsLoaded_;
  2264. }
  2265. };
  2266. /**
  2267. * @typedef {{
  2268. * loaded: boolean,
  2269. * initData: Uint8Array,
  2270. * initDataType: ?string,
  2271. * oldExpiration: number,
  2272. * type: string,
  2273. * updatePromise: shaka.util.PublicPromise
  2274. * }}
  2275. *
  2276. * @description A record to track sessions and suppress duplicate init data.
  2277. * @property {boolean} loaded
  2278. * True once the key status has been updated (to a non-pending state). This
  2279. * does not mean the session is 'usable'.
  2280. * @property {Uint8Array} initData
  2281. * The init data used to create the session.
  2282. * @property {?string} initDataType
  2283. * The init data type used to create the session.
  2284. * @property {!MediaKeySession} session
  2285. * The session object.
  2286. * @property {number} oldExpiration
  2287. * The expiration of the session on the last check. This is used to fire
  2288. * an event when it changes.
  2289. * @property {string} type
  2290. * The session type
  2291. * @property {shaka.util.PublicPromise} updatePromise
  2292. * An optional Promise that will be resolved/rejected on the next update()
  2293. * call. This is used to track the 'license-release' message when calling
  2294. * remove().
  2295. */
  2296. shaka.media.DrmEngine.SessionMetaData;
  2297. /**
  2298. * @typedef {{
  2299. * netEngine: !shaka.net.NetworkingEngine,
  2300. * onError: function(!shaka.util.Error),
  2301. * onKeyStatus: function(!Object.<string,string>),
  2302. * onExpirationUpdated: function(string,number),
  2303. * onEvent: function(!Event)
  2304. * }}
  2305. *
  2306. * @property {shaka.net.NetworkingEngine} netEngine
  2307. * The NetworkingEngine instance to use. The caller retains ownership.
  2308. * @property {function(!shaka.util.Error)} onError
  2309. * Called when an error occurs. If the error is recoverable (see
  2310. * {@link shaka.util.Error}) then the caller may invoke either
  2311. * StreamingEngine.switch*() or StreamingEngine.seeked() to attempt recovery.
  2312. * @property {function(!Object.<string,string>)} onKeyStatus
  2313. * Called when key status changes. The argument is a map of hex key IDs to
  2314. * statuses.
  2315. * @property {function(string,number)} onExpirationUpdated
  2316. * Called when the session expiration value changes.
  2317. * @property {function(!Event)} onEvent
  2318. * Called when an event occurs that should be sent to the app.
  2319. */
  2320. shaka.media.DrmEngine.PlayerInterface;
  2321. /**
  2322. * The amount of time, in seconds, we wait to consider a session closed.
  2323. * This allows us to work around Chrome bug https://crbug.com/1108158.
  2324. * @private {number}
  2325. */
  2326. shaka.media.DrmEngine.CLOSE_TIMEOUT_ = 1;
  2327. /**
  2328. * The amount of time, in seconds, we wait to consider session loaded even if no
  2329. * key status information is available. This allows us to support browsers/CDMs
  2330. * without key statuses.
  2331. * @private {number}
  2332. */
  2333. shaka.media.DrmEngine.SESSION_LOAD_TIMEOUT_ = 5;
  2334. /**
  2335. * The amount of time, in seconds, we wait to batch up rapid key status changes.
  2336. * This allows us to avoid multiple expiration events in most cases.
  2337. * @type {number}
  2338. */
  2339. shaka.media.DrmEngine.KEY_STATUS_BATCH_TIME = 0.5;