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