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