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