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