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