# All files / src/controller eme-controller.ts

38.93% Statements 58/149
31.11% Branches 14/45
53.13% Functions 17/32
38.1% Lines 56/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509

    1x

    1x
    2x

    2x
    4x

    2x

    1x
    2x

    2x

    1694x
    154x

    154x

    154x
    154x
    154x
    154x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x

    2x
    2x

    2x

    2x

    2x

    1x

    1x
    1x

    1x

    1x

    1x
    1x
    1x
    1x

    1x

    1x

    1x
    1x
    1x
    1x

    1x

    6x
    4x

    2x

    2x

    2x

    15x

    3x
    1x

    4x
    4x

    2x

     /**
     * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
     *
     * DRM support for Hls.js
     */

    import EventHandler from '../event-handler';
    import Event from '../events';
    import { ErrorTypes, ErrorDetails } from '../errors';

    import { logger } from '../utils/logger';
    import { EMEControllerConfig } from '../config';
    import { KeySystems, MediaKeyFunc } from '../utils/mediakeys-helper';

    const MAX_LICENSE_REQUEST_FAILURES = 3;

    /**
     * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
     * @param {Array<string>} audioCodecs List of required audio codecs to support
     * @param {Array<string>} videoCodecs List of required video codecs to support
     * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
     * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
     */

    const createWidevineMediaKeySystemConfigurations = function (audioCodecs: string[], videoCodecs: string[]): MediaKeySystemConfiguration[] { /* jshint ignore:line */
      const baseConfig: MediaKeySystemConfiguration = {
        // initDataTypes: ['keyids', 'mp4'],
        // label: "",
        // persistentState: "not-allowed", // or "required" ?
        // distinctiveIdentifier: "not-allowed", // or "required" ?
        // sessionTypes: ['temporary'],
        videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
      };

      videoCodecs.forEach((codec) => {
        baseConfig.videoCapabilities!.push({
          contentType: `video/mp4; codecs="${codec}"`
        });
      });

      return [
        baseConfig
      ];
    };

    /**
     * The idea here is to handle key-system (and their respective platforms) specific configuration differences
     * in order to work with the local requestMediaKeySystemAccess method.
     *
     * We can also rule-out platform-related key-system support at this point by throwing an error.
     *
     * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
     * @param {Array<string>} audioCodecs List of required audio codecs to support
     * @param {Array<string>} videoCodecs List of required video codecs to support
     * @throws will throw an error if a unknown key system is passed
     * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
     */
    const getSupportedMediaKeySystemConfigurations = function (keySystem: KeySystems, audioCodecs: string[], videoCodecs: string[]): MediaKeySystemConfiguration[] {
      switch (keySystem) {
      case KeySystems.WIDEVINE:
        return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
      default:
        throw new Error(`Unknown key-system: ${keySystem}`);
      }
    };

    interface MediaKeysListItem {
      mediaKeys?: MediaKeys,
      mediaKeysSession?: MediaKeySession,
      mediaKeysSessionInitialized: boolean;
      mediaKeySystemAccess: MediaKeySystemAccess;
      mediaKeySystemDomain: KeySystems;
    }

    /**
     * Controller to deal with encrypted media extensions (EME)
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
     *
     * @class
     * @constructor
     */
    class EMEController extends EventHandler {
      private _widevineLicenseUrl?: string;
      private _licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;
      private _emeEnabled: boolean;
      private _requestMediaKeySystemAccess: MediaKeyFunc | null

      private _config: EMEControllerConfig;
      private _mediaKeysList: MediaKeysListItem[] = [];
      private _media: HTMLMediaElement | null = null;
      private _hasSetMediaKeys: boolean = false;
      private _requestLicenseFailureCount: number = 0;

      /**
         * @constructs
         * @param {Hls} hls Our Hls.js instance
         */
      constructor (hls) {
        super(hls,
          Event.MEDIA_ATTACHED,
          Event.MEDIA_DETACHED,
          Event.MANIFEST_PARSED
        );
        this._config = hls.config;

        this._widevineLicenseUrl = this._config.widevineLicenseUrl;
        this._licenseXhrSetup = this._config.licenseXhrSetup;
        this._emeEnabled = this._config.emeEnabled;
        this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;
      }

      /**
       * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
       * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
       * @throws if a unsupported keysystem is passed
       */
      getLicenseServerUrl (keySystem: KeySystems): string {
        switch (keySystem) {
        case KeySystems.WIDEVINE:
          if (!this._widevineLicenseUrl) {
            break;
          }
          return this._widevineLicenseUrl;
        }

        throw new Error(`no license server URL configured for key-system "${keySystem}"`);
      }

      /**
         * Requests access object and adds it to our list upon success
         * @private
         * @param {string} keySystem System ID (see `KeySystems`)
         * @param {Array<string>} audioCodecs List of required audio codecs to support
         * @param {Array<string>} videoCodecs List of required video codecs to support
         * @throws When a unsupported KeySystem is passed
         */
      private _attemptKeySystemAccess (keySystem: KeySystems, audioCodecs: string[], videoCodecs: string[]) {
        // TODO: add other DRM "options"

        // This can throw, but is caught in event handler callpath
        const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);

        logger.log('Requesting encrypted media key-system access');

        // expecting interface like window.navigator.requestMediaKeySystemAccess
        this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)
          .then((mediaKeySystemAccess) => {
            this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
          })
          .catch((err) => {
            logger.error(`Failed to obtain key-system "${keySystem}" access:`, err);
          });
      }

      get requestMediaKeySystemAccess () {
        Iif (!this._requestMediaKeySystemAccess) {
          throw new Error('No requestMediaKeySystemAccess function configured');
        }

        return this._requestMediaKeySystemAccess;
      }

      /**
         * Handles obtaining access to a key-system
         * @private
         * @param {string} keySystem
         * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
         */
      private _onMediaKeySystemAccessObtained (keySystem: KeySystems, mediaKeySystemAccess: MediaKeySystemAccess) {
        logger.log(`Access for key-system "${keySystem}" obtained`);

        const mediaKeysListItem: MediaKeysListItem = {
          mediaKeysSessionInitialized: false,
          mediaKeySystemAccess: mediaKeySystemAccess,
          mediaKeySystemDomain: keySystem
        };

        this._mediaKeysList.push(mediaKeysListItem);

        mediaKeySystemAccess.createMediaKeys()
          .then((mediaKeys) => {
            mediaKeysListItem.mediaKeys = mediaKeys;

            logger.log(`Media-keys created for key-system "${keySystem}"`);

            this._onMediaKeysCreated();
          })
          .catch((err) => {
            logger.error('Failed to create media-keys:', err);
          });
      }

      /**
       * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
       * for all existing keys where no session exists yet.
       *
       * @private
       */
      private _onMediaKeysCreated () {
        // check for all key-list items if a session exists, otherwise, create one
        this._mediaKeysList.forEach((mediaKeysListItem) => {
          if (!mediaKeysListItem.mediaKeysSession) {
            // mediaKeys is definitely initialized here
            mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys!.createSession();
            this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
          }
        });
      }

      /**
         * @private
         * @param {*} keySession
         */
      private _onNewMediaKeySession (keySession: MediaKeySession) {
        logger.log(`New key-system session ${keySession.sessionId}`);

        keySession.addEventListener('message', (event: MediaKeyMessageEvent) => {
          this._onKeySessionMessage(keySession, event.message);
        }, false);
      }

      /**
       * @private
       * @param {MediaKeySession} keySession
       * @param {ArrayBuffer} message
       */
      private _onKeySessionMessage (keySession: MediaKeySession, message: ArrayBuffer) {
        logger.log('Got EME message event, creating license request');

        this._requestLicense(message, (data: ArrayBuffer) => {
          logger.log('Received license data, updating key-session');
          keySession.update(data);
        });
      }

      /**
       * @private
       * @param {string} initDataType
       * @param {ArrayBuffer|null} initData
       */
      private _onMediaEncrypted = (e: MediaEncryptedEvent) => {
        logger.log(`Media is encrypted using "${e.initDataType}" init data type`);

        this._attemptSetMediaKeys();
        this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
      }

      /**
       * @private
       */
      private _attemptSetMediaKeys () {
        Iif (!this._media) {
          throw new Error('Attempted to set mediaKeys without first attaching a media element');
        }

        Eif (!this._hasSetMediaKeys) {
          // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
          const keysListItem = this._mediaKeysList[0];
          Eif (!keysListItem || !keysListItem.mediaKeys) {
            logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
            this.hls.trigger(Event.ERROR, {
              type: ErrorTypes.KEY_SYSTEM_ERROR,
              details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
              fatal: true
            });
            return;
          }

          logger.log('Setting keys for encrypted media');

          this._media.setMediaKeys(keysListItem.mediaKeys);
          this._hasSetMediaKeys = true;
        }
      }

      /**
       * @private
       */
      private _generateRequestWithPreferredKeySession (initDataType: string, initData: ArrayBuffer | null) {
        // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
        const keysListItem = this._mediaKeysList[0];
        Eif (!keysListItem) {
          logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
          this.hls.trigger(Event.ERROR, {
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
            fatal: true
          });
          return;
        }

        if (keysListItem.mediaKeysSessionInitialized) {
          logger.warn('Key-Session already initialized but requested again');
          return;
        }

        const keySession = keysListItem.mediaKeysSession;
        if (!keySession) {
          logger.error('Fatal: Media is encrypted but no key-session existing');
          this.hls.trigger(Event.ERROR, {
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
            fatal: true
          });
          return;
        }

        logger.log(`Generating key-session request for "${initDataType}" init data type`);
        keysListItem.mediaKeysSessionInitialized = true;

        keySession.generateRequest(initDataType, initData)
          .then(() => {
            logger.debug('Key-session generation succeeded');
          })
          .catch((err) => {
            logger.error('Error generating key-session request:', err);
            this.hls.trigger(Event.ERROR, {
              type: ErrorTypes.KEY_SYSTEM_ERROR,
              details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
              fatal: false
            });
          });
      }

      /**
       * @private
       * @param {string} url License server URL
       * @param {ArrayBuffer} keyMessage Message data issued by key-system
       * @param {function} callback Called when XHR has succeeded
       * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
       * @throws if XMLHttpRequest construction failed
       */
      private _createLicenseXhr (url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void): XMLHttpRequest {
        const xhr = new XMLHttpRequest();
        const licenseXhrSetup = this._licenseXhrSetup;

        try {
          if (licenseXhrSetup) {
            try {
              licenseXhrSetup(xhr, url);
            } catch (e) {
              // let's try to open before running setup
              xhr.open('POST', url, true);
              licenseXhrSetup(xhr, url);
            }
          }
          // if licenseXhrSetup did not yet call open, let's do it now
          if (!xhr.readyState) {
            xhr.open('POST', url, true);
          }
        } catch (e) {
          // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
          throw new Error(`issue setting up KeySystem license XHR ${e}`);
        }

        // Because we set responseType to ArrayBuffer here, callback is typed as handling only array buffers
        xhr.responseType = 'arraybuffer';
        xhr.onreadystatechange =
            this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
        return xhr;
      }

      /**
       * @private
       * @param {XMLHttpRequest} xhr
       * @param {string} url License server URL
       * @param {ArrayBuffer} keyMessage Message data issued by key-system
       * @param {function} callback Called when XHR has succeeded
       */
      private _onLicenseRequestReadyStageChange (xhr: XMLHttpRequest, url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {
        switch (xhr.readyState) {
        case 4:
          if (xhr.status === 200) {
            this._requestLicenseFailureCount = 0;
            logger.log('License request succeeded');

            if (xhr.responseType !== 'arraybuffer') {
              logger.warn('xhr response type was not set to the expected arraybuffer for license request');
            }
            callback(xhr.response);
          } else {
            logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);
            this._requestLicenseFailureCount++;
            if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
              this.hls.trigger(Event.ERROR, {
                type: ErrorTypes.KEY_SYSTEM_ERROR,
                details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
                fatal: true
              });
              return;
            }

            const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
            logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);
            this._requestLicense(keyMessage, callback);
          }
          break;
        }
      }

      /**
       * @private
       * @param {MediaKeysListItem} keysListItem
       * @param {ArrayBuffer} keyMessage
       * @returns {ArrayBuffer} Challenge data posted to license server
       * @throws if KeySystem is unsupported
       */
      private _generateLicenseRequestChallenge (keysListItem: MediaKeysListItem, keyMessage: ArrayBuffer): ArrayBuffer {
        switch (keysListItem.mediaKeySystemDomain) {
        // case KeySystems.PLAYREADY:
        // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
        /*
          if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
            // For PlayReady CDMs, we need to dig the Challenge out of the XML.
            var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
            if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
                challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
            } else {
                throw 'Cannot find <Challenge> in key message';
            }
            var headerNames = keyMessageXml.getElementsByTagName('name');
            var headerValues = keyMessageXml.getElementsByTagName('value');
            if (headerNames.length !== headerValues.length) {
                throw 'Mismatched header <name>/<value> pair in key message';
            }
            for (var i = 0; i < headerNames.length; i++) {
                xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
            }
          }
          break;
        */
        case KeySystems.WIDEVINE:
          // For Widevine CDMs, the challenge is the keyMessage.
          return keyMessage;
        }

        throw new Error(`unsupported key-system: ${keysListItem.mediaKeySystemDomain}`);
      }

      /**
       * @private
       * @param keyMessage
       * @param callback
       */
      private _requestLicense (keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {
        logger.log('Requesting content license for key-system');

        const keysListItem = this._mediaKeysList[0];
        if (!keysListItem) {
          logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
          this.hls.trigger(Event.ERROR, {
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
            fatal: true
          });
          return;
        }

        try {
          const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
          const xhr = this._createLicenseXhr(url, keyMessage, callback);
          logger.log(`Sending license request to URL: ${url}`);
          const challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
          xhr.send(challenge);
        } catch (e) {
          logger.error(`Failure requesting DRM license: ${e}`);
          this.hls.trigger(Event.ERROR, {
            type: ErrorTypes.KEY_SYSTEM_ERROR,
            details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
            fatal: true
          });
        }
      }

      onMediaAttached (data: { media: HTMLMediaElement; }) {
        if (!this._emeEnabled) {
          return;
        }

        const media = data.media;

        // keep reference of media
        this._media = media;

        media.addEventListener('encrypted', this._onMediaEncrypted);
      }

      onMediaDetached () {
        Iif (this._media) {
          this._media.removeEventListener('encrypted', this._onMediaEncrypted);
          this._media = null; // release reference
        }
      }

      // TODO: Use manifest types here when they are defined
      onManifestParsed (data: any) {
        if (!this._emeEnabled) {
          return;
        }

        const audioCodecs = data.levels.map((level) => level.audioCodec);
        const videoCodecs = data.levels.map((level) => level.videoCodec);

        this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
      }
    }

    export default EMEController;