Home Reference Source

src/controller/eme-controller.ts

  1. /**
  2. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  3. *
  4. * DRM support for Hls.js
  5. */
  6. import { Events } from '../events';
  7. import { ErrorTypes, ErrorDetails } from '../errors';
  8.  
  9. import { logger } from '../utils/logger';
  10. import type { DRMSystemOptions, EMEControllerConfig } from '../config';
  11. import type { MediaKeyFunc } from '../utils/mediakeys-helper';
  12. import { KeySystems } from '../utils/mediakeys-helper';
  13. import type Hls from '../hls';
  14. import type { ComponentAPI } from '../types/component-api';
  15. import type { MediaAttachedData, ManifestParsedData } from '../types/events';
  16.  
  17. const MAX_LICENSE_REQUEST_FAILURES = 3;
  18.  
  19. /**
  20. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  21. * @param {Array<string>} audioCodecs List of required audio codecs to support
  22. * @param {Array<string>} videoCodecs List of required video codecs to support
  23. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  24. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  25. */
  26.  
  27. const createWidevineMediaKeySystemConfigurations = function (
  28. audioCodecs: string[],
  29. videoCodecs: string[],
  30. drmSystemOptions: DRMSystemOptions
  31. ): MediaKeySystemConfiguration[] {
  32. /* jshint ignore:line */
  33. const baseConfig: MediaKeySystemConfiguration = {
  34. // initDataTypes: ['keyids', 'mp4'],
  35. // label: "",
  36. // persistentState: "not-allowed", // or "required" ?
  37. // distinctiveIdentifier: "not-allowed", // or "required" ?
  38. // sessionTypes: ['temporary'],
  39. audioCapabilities: [], // { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
  40. videoCapabilities: [], // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
  41. };
  42.  
  43. audioCodecs.forEach((codec) => {
  44. baseConfig.audioCapabilities!.push({
  45. contentType: `audio/mp4; codecs="${codec}"`,
  46. robustness: drmSystemOptions.audioRobustness || '',
  47. });
  48. });
  49. videoCodecs.forEach((codec) => {
  50. baseConfig.videoCapabilities!.push({
  51. contentType: `video/mp4; codecs="${codec}"`,
  52. robustness: drmSystemOptions.videoRobustness || '',
  53. });
  54. });
  55.  
  56. return [baseConfig];
  57. };
  58.  
  59. /**
  60. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  61. * in order to work with the local requestMediaKeySystemAccess method.
  62. *
  63. * We can also rule-out platform-related key-system support at this point by throwing an error.
  64. *
  65. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  66. * @param {Array<string>} audioCodecs List of required audio codecs to support
  67. * @param {Array<string>} videoCodecs List of required video codecs to support
  68. * @throws will throw an error if a unknown key system is passed
  69. * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
  70. */
  71. const getSupportedMediaKeySystemConfigurations = function (
  72. keySystem: KeySystems,
  73. audioCodecs: string[],
  74. videoCodecs: string[],
  75. drmSystemOptions: DRMSystemOptions
  76. ): MediaKeySystemConfiguration[] {
  77. switch (keySystem) {
  78. case KeySystems.WIDEVINE:
  79. return createWidevineMediaKeySystemConfigurations(
  80. audioCodecs,
  81. videoCodecs,
  82. drmSystemOptions
  83. );
  84. default:
  85. throw new Error(`Unknown key-system: ${keySystem}`);
  86. }
  87. };
  88.  
  89. interface MediaKeysListItem {
  90. mediaKeys?: MediaKeys;
  91. mediaKeysSession?: MediaKeySession;
  92. mediaKeysSessionInitialized: boolean;
  93. mediaKeySystemAccess: MediaKeySystemAccess;
  94. mediaKeySystemDomain: KeySystems;
  95. }
  96.  
  97. /**
  98. * Controller to deal with encrypted media extensions (EME)
  99. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  100. *
  101. * @class
  102. * @constructor
  103. */
  104. class EMEController implements ComponentAPI {
  105. private hls: Hls;
  106. private _widevineLicenseUrl?: string;
  107. private _licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;
  108. private _licenseResponseCallback?: (
  109. xhr: XMLHttpRequest,
  110. url: string
  111. ) => ArrayBuffer;
  112. private _emeEnabled: boolean;
  113. private _requestMediaKeySystemAccess: MediaKeyFunc | null;
  114. private _drmSystemOptions: DRMSystemOptions;
  115.  
  116. private _config: EMEControllerConfig;
  117. private _mediaKeysList: MediaKeysListItem[] = [];
  118. private _media: HTMLMediaElement | null = null;
  119. private _hasSetMediaKeys: boolean = false;
  120. private _requestLicenseFailureCount: number = 0;
  121.  
  122. private mediaKeysPromise: Promise<MediaKeys> | null = null;
  123. private _onMediaEncrypted = this.onMediaEncrypted.bind(this);
  124.  
  125. /**
  126. * @constructs
  127. * @param {Hls} hls Our Hls.js instance
  128. */
  129. constructor(hls: Hls) {
  130. this.hls = hls;
  131. this._config = hls.config;
  132.  
  133. this._widevineLicenseUrl = this._config.widevineLicenseUrl;
  134. this._licenseXhrSetup = this._config.licenseXhrSetup;
  135. this._licenseResponseCallback = this._config.licenseResponseCallback;
  136. this._emeEnabled = this._config.emeEnabled;
  137. this._requestMediaKeySystemAccess =
  138. this._config.requestMediaKeySystemAccessFunc;
  139. this._drmSystemOptions = this._config.drmSystemOptions;
  140.  
  141. this._registerListeners();
  142. }
  143.  
  144. public destroy() {
  145. this._unregisterListeners();
  146. // @ts-ignore
  147. this.hls = this._onMediaEncrypted = null;
  148. this._requestMediaKeySystemAccess = null;
  149. }
  150.  
  151. private _registerListeners() {
  152. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  153. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  154. this.hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  155. }
  156.  
  157. private _unregisterListeners() {
  158. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  159. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  160. this.hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  161. }
  162.  
  163. /**
  164. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  165. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  166. * @throws if a unsupported keysystem is passed
  167. */
  168. getLicenseServerUrl(keySystem: KeySystems): string {
  169. switch (keySystem) {
  170. case KeySystems.WIDEVINE:
  171. if (!this._widevineLicenseUrl) {
  172. break;
  173. }
  174. return this._widevineLicenseUrl;
  175. }
  176.  
  177. throw new Error(
  178. `no license server URL configured for key-system "${keySystem}"`
  179. );
  180. }
  181.  
  182. /**
  183. * Requests access object and adds it to our list upon success
  184. * @private
  185. * @param {string} keySystem System ID (see `KeySystems`)
  186. * @param {Array<string>} audioCodecs List of required audio codecs to support
  187. * @param {Array<string>} videoCodecs List of required video codecs to support
  188. * @throws When a unsupported KeySystem is passed
  189. */
  190. private _attemptKeySystemAccess(
  191. keySystem: KeySystems,
  192. audioCodecs: string[],
  193. videoCodecs: string[]
  194. ) {
  195. // This can throw, but is caught in event handler callpath
  196. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(
  197. keySystem,
  198. audioCodecs,
  199. videoCodecs,
  200. this._drmSystemOptions
  201. );
  202.  
  203. logger.log('Requesting encrypted media key-system access');
  204.  
  205. // expecting interface like window.navigator.requestMediaKeySystemAccess
  206. const keySystemAccessPromise = this.requestMediaKeySystemAccess(
  207. keySystem,
  208. mediaKeySystemConfigs
  209. );
  210.  
  211. this.mediaKeysPromise = keySystemAccessPromise.then(
  212. (mediaKeySystemAccess) =>
  213. this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess)
  214. );
  215.  
  216. keySystemAccessPromise.catch((err) => {
  217. logger.error(`Failed to obtain key-system "${keySystem}" access:`, err);
  218. });
  219. }
  220.  
  221. get requestMediaKeySystemAccess() {
  222. if (!this._requestMediaKeySystemAccess) {
  223. throw new Error('No requestMediaKeySystemAccess function configured');
  224. }
  225.  
  226. return this._requestMediaKeySystemAccess;
  227. }
  228.  
  229. /**
  230. * Handles obtaining access to a key-system
  231. * @private
  232. * @param {string} keySystem
  233. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  234. */
  235. private _onMediaKeySystemAccessObtained(
  236. keySystem: KeySystems,
  237. mediaKeySystemAccess: MediaKeySystemAccess
  238. ): Promise<MediaKeys> {
  239. logger.log(`Access for key-system "${keySystem}" obtained`);
  240.  
  241. const mediaKeysListItem: MediaKeysListItem = {
  242. mediaKeysSessionInitialized: false,
  243. mediaKeySystemAccess: mediaKeySystemAccess,
  244. mediaKeySystemDomain: keySystem,
  245. };
  246.  
  247. this._mediaKeysList.push(mediaKeysListItem);
  248.  
  249. const mediaKeysPromise = Promise.resolve()
  250. .then(() => mediaKeySystemAccess.createMediaKeys())
  251. .then((mediaKeys) => {
  252. mediaKeysListItem.mediaKeys = mediaKeys;
  253.  
  254. logger.log(`Media-keys created for key-system "${keySystem}"`);
  255.  
  256. this._onMediaKeysCreated();
  257.  
  258. return mediaKeys;
  259. });
  260.  
  261. mediaKeysPromise.catch((err) => {
  262. logger.error('Failed to create media-keys:', err);
  263. });
  264.  
  265. return mediaKeysPromise;
  266. }
  267.  
  268. /**
  269. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  270. * for all existing keys where no session exists yet.
  271. *
  272. * @private
  273. */
  274. private _onMediaKeysCreated() {
  275. // check for all key-list items if a session exists, otherwise, create one
  276. this._mediaKeysList.forEach((mediaKeysListItem) => {
  277. if (!mediaKeysListItem.mediaKeysSession) {
  278. // mediaKeys is definitely initialized here
  279. mediaKeysListItem.mediaKeysSession =
  280. mediaKeysListItem.mediaKeys!.createSession();
  281. this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  282. }
  283. });
  284. }
  285.  
  286. /**
  287. * @private
  288. * @param {*} keySession
  289. */
  290. private _onNewMediaKeySession(keySession: MediaKeySession) {
  291. logger.log(`New key-system session ${keySession.sessionId}`);
  292.  
  293. keySession.addEventListener(
  294. 'message',
  295. (event: MediaKeyMessageEvent) => {
  296. this._onKeySessionMessage(keySession, event.message);
  297. },
  298. false
  299. );
  300. }
  301.  
  302. /**
  303. * @private
  304. * @param {MediaKeySession} keySession
  305. * @param {ArrayBuffer} message
  306. */
  307. private _onKeySessionMessage(
  308. keySession: MediaKeySession,
  309. message: ArrayBuffer
  310. ) {
  311. logger.log('Got EME message event, creating license request');
  312.  
  313. this._requestLicense(message, (data: ArrayBuffer) => {
  314. logger.log(
  315. `Received license data (length: ${
  316. data ? data.byteLength : data
  317. }), updating key-session`
  318. );
  319. keySession.update(data);
  320. });
  321. }
  322.  
  323. /**
  324. * @private
  325. * @param e {MediaEncryptedEvent}
  326. */
  327. private onMediaEncrypted(e: MediaEncryptedEvent) {
  328. logger.log(`Media is encrypted using "${e.initDataType}" init data type`);
  329.  
  330. if (!this.mediaKeysPromise) {
  331. logger.error(
  332. 'Fatal: Media is encrypted but no CDM access or no keys have been requested'
  333. );
  334. this.hls.trigger(Events.ERROR, {
  335. type: ErrorTypes.KEY_SYSTEM_ERROR,
  336. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  337. fatal: true,
  338. });
  339. return;
  340. }
  341.  
  342. const finallySetKeyAndStartSession = (mediaKeys) => {
  343. if (!this._media) {
  344. return;
  345. }
  346. this._attemptSetMediaKeys(mediaKeys);
  347. this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
  348. };
  349.  
  350. // Could use `Promise.finally` but some Promise polyfills are missing it
  351. this.mediaKeysPromise
  352. .then(finallySetKeyAndStartSession)
  353. .catch(finallySetKeyAndStartSession);
  354. }
  355.  
  356. /**
  357. * @private
  358. */
  359. private _attemptSetMediaKeys(mediaKeys?: MediaKeys) {
  360. if (!this._media) {
  361. throw new Error(
  362. 'Attempted to set mediaKeys without first attaching a media element'
  363. );
  364. }
  365.  
  366. if (!this._hasSetMediaKeys) {
  367. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  368. const keysListItem = this._mediaKeysList[0];
  369. if (!keysListItem || !keysListItem.mediaKeys) {
  370. logger.error(
  371. 'Fatal: Media is encrypted but no CDM access or no keys have been obtained yet'
  372. );
  373. this.hls.trigger(Events.ERROR, {
  374. type: ErrorTypes.KEY_SYSTEM_ERROR,
  375. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  376. fatal: true,
  377. });
  378. return;
  379. }
  380.  
  381. logger.log('Setting keys for encrypted media');
  382.  
  383. this._media.setMediaKeys(keysListItem.mediaKeys);
  384. this._hasSetMediaKeys = true;
  385. }
  386. }
  387.  
  388. /**
  389. * @private
  390. */
  391. private _generateRequestWithPreferredKeySession(
  392. initDataType: string,
  393. initData: ArrayBuffer | null
  394. ) {
  395. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  396. const keysListItem = this._mediaKeysList[0];
  397. if (!keysListItem) {
  398. logger.error(
  399. 'Fatal: Media is encrypted but not any key-system access has been obtained yet'
  400. );
  401. this.hls.trigger(Events.ERROR, {
  402. type: ErrorTypes.KEY_SYSTEM_ERROR,
  403. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  404. fatal: true,
  405. });
  406. return;
  407. }
  408.  
  409. if (keysListItem.mediaKeysSessionInitialized) {
  410. logger.warn('Key-Session already initialized but requested again');
  411. return;
  412. }
  413.  
  414. const keySession = keysListItem.mediaKeysSession;
  415. if (!keySession) {
  416. logger.error('Fatal: Media is encrypted but no key-session existing');
  417. this.hls.trigger(Events.ERROR, {
  418. type: ErrorTypes.KEY_SYSTEM_ERROR,
  419. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  420. fatal: true,
  421. });
  422. return;
  423. }
  424.  
  425. // initData is null if the media is not CORS-same-origin
  426. if (!initData) {
  427. logger.warn(
  428. 'Fatal: initData required for generating a key session is null'
  429. );
  430. this.hls.trigger(Events.ERROR, {
  431. type: ErrorTypes.KEY_SYSTEM_ERROR,
  432. details: ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,
  433. fatal: true,
  434. });
  435. return;
  436. }
  437.  
  438. logger.log(
  439. `Generating key-session request for "${initDataType}" init data type`
  440. );
  441. keysListItem.mediaKeysSessionInitialized = true;
  442.  
  443. keySession
  444. .generateRequest(initDataType, initData)
  445. .then(() => {
  446. logger.debug('Key-session generation succeeded');
  447. })
  448. .catch((err) => {
  449. logger.error('Error generating key-session request:', err);
  450. this.hls.trigger(Events.ERROR, {
  451. type: ErrorTypes.KEY_SYSTEM_ERROR,
  452. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  453. fatal: false,
  454. });
  455. });
  456. }
  457.  
  458. /**
  459. * @private
  460. * @param {string} url License server URL
  461. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  462. * @param {function} callback Called when XHR has succeeded
  463. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  464. * @throws if XMLHttpRequest construction failed
  465. */
  466. private _createLicenseXhr(
  467. url: string,
  468. keyMessage: ArrayBuffer,
  469. callback: (data: ArrayBuffer) => void
  470. ): XMLHttpRequest {
  471. const xhr = new XMLHttpRequest();
  472. xhr.responseType = 'arraybuffer';
  473. xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(
  474. this,
  475. xhr,
  476. url,
  477. keyMessage,
  478. callback
  479. );
  480.  
  481. let licenseXhrSetup = this._licenseXhrSetup;
  482. if (licenseXhrSetup) {
  483. try {
  484. licenseXhrSetup.call(this.hls, xhr, url);
  485. licenseXhrSetup = undefined;
  486. } catch (e) {
  487. logger.error(e);
  488. }
  489. }
  490. try {
  491. // if licenseXhrSetup did not yet call open, let's do it now
  492. if (!xhr.readyState) {
  493. xhr.open('POST', url, true);
  494. }
  495. if (licenseXhrSetup) {
  496. licenseXhrSetup.call(this.hls, xhr, url);
  497. }
  498. } catch (e) {
  499. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  500. throw new Error(`issue setting up KeySystem license XHR ${e}`);
  501. }
  502.  
  503. return xhr;
  504. }
  505.  
  506. /**
  507. * @private
  508. * @param {XMLHttpRequest} xhr
  509. * @param {string} url License server URL
  510. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  511. * @param {function} callback Called when XHR has succeeded
  512. */
  513. private _onLicenseRequestReadyStageChange(
  514. xhr: XMLHttpRequest,
  515. url: string,
  516. keyMessage: ArrayBuffer,
  517. callback: (data: ArrayBuffer) => void
  518. ) {
  519. switch (xhr.readyState) {
  520. case 4:
  521. if (xhr.status === 200) {
  522. this._requestLicenseFailureCount = 0;
  523. logger.log('License request succeeded');
  524. let data: ArrayBuffer = xhr.response;
  525. const licenseResponseCallback = this._licenseResponseCallback;
  526. if (licenseResponseCallback) {
  527. try {
  528. data = licenseResponseCallback.call(this.hls, xhr, url);
  529. } catch (e) {
  530. logger.error(e);
  531. }
  532. }
  533. callback(data);
  534. } else {
  535. logger.error(
  536. `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`
  537. );
  538. this._requestLicenseFailureCount++;
  539. if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
  540. this.hls.trigger(Events.ERROR, {
  541. type: ErrorTypes.KEY_SYSTEM_ERROR,
  542. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  543. fatal: true,
  544. });
  545. return;
  546. }
  547.  
  548. const attemptsLeft =
  549. MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  550. logger.warn(
  551. `Retrying license request, ${attemptsLeft} attempts left`
  552. );
  553. this._requestLicense(keyMessage, callback);
  554. }
  555. break;
  556. }
  557. }
  558.  
  559. /**
  560. * @private
  561. * @param {MediaKeysListItem} keysListItem
  562. * @param {ArrayBuffer} keyMessage
  563. * @returns {ArrayBuffer} Challenge data posted to license server
  564. * @throws if KeySystem is unsupported
  565. */
  566. private _generateLicenseRequestChallenge(
  567. keysListItem: MediaKeysListItem,
  568. keyMessage: ArrayBuffer
  569. ): ArrayBuffer {
  570. switch (keysListItem.mediaKeySystemDomain) {
  571. // case KeySystems.PLAYREADY:
  572. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  573. /*
  574. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  575. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  576. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  577. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  578. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  579. } else {
  580. throw 'Cannot find <Challenge> in key message';
  581. }
  582. var headerNames = keyMessageXml.getElementsByTagName('name');
  583. var headerValues = keyMessageXml.getElementsByTagName('value');
  584. if (headerNames.length !== headerValues.length) {
  585. throw 'Mismatched header <name>/<value> pair in key message';
  586. }
  587. for (var i = 0; i < headerNames.length; i++) {
  588. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  589. }
  590. }
  591. break;
  592. */
  593. case KeySystems.WIDEVINE:
  594. // For Widevine CDMs, the challenge is the keyMessage.
  595. return keyMessage;
  596. }
  597.  
  598. throw new Error(
  599. `unsupported key-system: ${keysListItem.mediaKeySystemDomain}`
  600. );
  601. }
  602.  
  603. /**
  604. * @private
  605. * @param keyMessage
  606. * @param callback
  607. */
  608. private _requestLicense(
  609. keyMessage: ArrayBuffer,
  610. callback: (data: ArrayBuffer) => void
  611. ) {
  612. logger.log('Requesting content license for key-system');
  613.  
  614. const keysListItem = this._mediaKeysList[0];
  615. if (!keysListItem) {
  616. logger.error(
  617. 'Fatal error: Media is encrypted but no key-system access has been obtained yet'
  618. );
  619. this.hls.trigger(Events.ERROR, {
  620. type: ErrorTypes.KEY_SYSTEM_ERROR,
  621. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  622. fatal: true,
  623. });
  624. return;
  625. }
  626.  
  627. try {
  628. const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  629. const xhr = this._createLicenseXhr(url, keyMessage, callback);
  630. logger.log(`Sending license request to URL: ${url}`);
  631. const challenge = this._generateLicenseRequestChallenge(
  632. keysListItem,
  633. keyMessage
  634. );
  635. xhr.send(challenge);
  636. } catch (e) {
  637. logger.error(`Failure requesting DRM license: ${e}`);
  638. this.hls.trigger(Events.ERROR, {
  639. type: ErrorTypes.KEY_SYSTEM_ERROR,
  640. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  641. fatal: true,
  642. });
  643. }
  644. }
  645.  
  646. onMediaAttached(event: Events.MEDIA_ATTACHED, data: MediaAttachedData) {
  647. if (!this._emeEnabled) {
  648. return;
  649. }
  650.  
  651. const media = data.media;
  652.  
  653. // keep reference of media
  654. this._media = media;
  655.  
  656. media.addEventListener('encrypted', this._onMediaEncrypted);
  657. }
  658.  
  659. onMediaDetached() {
  660. const media = this._media;
  661. const mediaKeysList = this._mediaKeysList;
  662. if (!media) {
  663. return;
  664. }
  665. media.removeEventListener('encrypted', this._onMediaEncrypted);
  666. this._media = null;
  667. this._mediaKeysList = [];
  668. // Close all sessions and remove media keys from the video element.
  669. Promise.all(
  670. mediaKeysList.map((mediaKeysListItem) => {
  671. if (mediaKeysListItem.mediaKeysSession) {
  672. return mediaKeysListItem.mediaKeysSession.close().catch(() => {
  673. // Ignore errors when closing the sessions. Closing a session that
  674. // generated no key requests will throw an error.
  675. });
  676. }
  677. })
  678. )
  679. .then(() => {
  680. return media.setMediaKeys(null);
  681. })
  682. .catch(() => {
  683. // Ignore any failures while removing media keys from the video element.
  684. });
  685. }
  686.  
  687. onManifestParsed(event: Events.MANIFEST_PARSED, data: ManifestParsedData) {
  688. if (!this._emeEnabled) {
  689. return;
  690. }
  691.  
  692. const audioCodecs = data.levels
  693. .map((level) => level.audioCodec)
  694. .filter(
  695. (audioCodec: string | undefined): audioCodec is string => !!audioCodec
  696. );
  697. const videoCodecs = data.levels
  698. .map((level) => level.videoCodec)
  699. .filter(
  700. (videoCodec: string | undefined): videoCodec is string => !!videoCodec
  701. );
  702.  
  703. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  704. }
  705. }
  706.  
  707. export default EMEController;