# All files / src hls.ts

66.67% Statements 112/168
50% Branches 36/72
52.94% Functions 27/51
66.26% Lines 108/163

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
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675

    9x

    7x

    1x

    165x
    165x

    2416x
    151x

    151x

    151x

    151x

    151x

    151x

    151x

    151x

    151x
    151x
    151x
    151x
    151x
    151x
    151x
    151x

    151x

    151x

    151x

    151x

    151x
    151x
    151x

    151x

    151x

    151x
    151x
    151x

    151x
    151x

    151x
    151x
    151x

    151x
    151x

    151x
    151x
    151x

    151x
    151x

    151x
    151x
    151x

    151x
    151x
    151x

    151x

    16x
    16x
    16x
    16x
    272x

    16x
    16x
    16x

    16x
    16x
    16x

    1x
    1x
    1x
    5x

    23x

    3x

    2x

    9x
    9x

    2x

    1x

    1x

    1x

    4x

    4x
    3x

    3x
    3x
    3x

    3x

    5x

    2x
    2x

    3x
    3x

    3x

    7x
    7x

    7x
    1x

    1x
    1x

    6x

    5x

    5x
    1x

    4x

    5x

    2x

    2x

    12x
    12x

    2x
    2x

     import * as URLToolkit from 'url-toolkit';

    import {
      ErrorTypes,
      ErrorDetails
    } from './errors';

    import PlaylistLoader from './loader/playlist-loader';
    import FragmentLoader from './loader/fragment-loader';
    import KeyLoader from './loader/key-loader';

    import { FragmentTracker } from './controller/fragment-tracker';
    import StreamController from './controller/stream-controller';
    import LevelController from './controller/level-controller';
    import ID3TrackController from './controller/id3-track-controller';

    import { isSupported } from './is-supported';
    import { logger, enableLogs } from './utils/logger';
    import { hlsDefaultConfig, HlsConfig } from './config';

    import HlsEvents from './events';

    import { Observer } from './observer';

    /**
     * @module Hls
     * @class
     * @constructor
     */
    export default class Hls extends Observer {
      public static defaultConfig?: HlsConfig;
      public config: HlsConfig;

      private _autoLevelCapping: number;
      private abrController: any;
      private capLevelController: any;
      private levelController: any;
      private streamController: any;
      private networkControllers: any[];
      private audioTrackController: any;
      private subtitleTrackController: any;
      private emeController: any;
      private coreComponents: any[];
      private media: HTMLMediaElement | null = null;
      private url: string | null = null;

      /**
       * @type {string}
       */
      static get version (): string {
        return __VERSION__;
      }

      /**
       * @type {boolean}
       */
      static isSupported (): boolean {
        return isSupported();
      }

      /**
       * @type {HlsEvents}
       */
      static get Events () {
        return HlsEvents;
      }

      /**
       * @type {HlsErrorTypes}
       */
      static get ErrorTypes () {
        return ErrorTypes;
      }

      /**
       * @type {HlsErrorDetails}
       */
      static get ErrorDetails () {
        return ErrorDetails;
      }

      /**
       * @type {HlsConfig}
       */
      static get DefaultConfig (): HlsConfig {
        Eif (!Hls.defaultConfig) {
          return hlsDefaultConfig;
        }

        return Hls.defaultConfig;
      }

      /**
       * @type {HlsConfig}
       */
      static set DefaultConfig (defaultConfig: HlsConfig) {
        Hls.defaultConfig = defaultConfig;
      }

      /**
       * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
       *
       * @constructs Hls
       * @param {HlsConfig} config
       */
      constructor (userConfig: Partial<HlsConfig> = {}) {
        super();

        const defaultConfig = Hls.DefaultConfig;

        Iif ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
          throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
        }

        // Shallow clone
        this.config = {
          ...defaultConfig,
          ...userConfig
        };

        const { config } = this;

        Iif (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
          throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
        }

        Iif (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {
          throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
        }

        enableLogs(config.debug);

        this._autoLevelCapping = -1;

        // core controllers and network loaders

        /**
         * @member {AbrController} abrController
         */
        const abrController = this.abrController = new config.abrController(this); // eslint-disable-line new-cap
        const bufferController = new config.bufferController(this); // eslint-disable-line new-cap
        const capLevelController = this.capLevelController = new config.capLevelController(this); // eslint-disable-line new-cap
        const fpsController = new config.fpsController(this); // eslint-disable-line new-cap
        const playListLoader = new PlaylistLoader(this);
        const fragmentLoader = new FragmentLoader(this);
        const keyLoader = new KeyLoader(this);
        const id3TrackController = new ID3TrackController(this);

        // network controllers

        /**
         * @member {LevelController} levelController
         */
        const levelController = this.levelController = new LevelController(this);

        // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
        const fragmentTracker = new FragmentTracker(this);

        /**
         * @member {StreamController} streamController
         */
        const streamController = this.streamController = new StreamController(this, fragmentTracker);

        let networkControllers = [levelController, streamController];

        // optional audio stream controller
        /**
         * @var {ICoreComponent | Controller}
         */
        let Controller = config.audioStreamController;
        Eif (Controller) {
          networkControllers.push(new Controller(this, fragmentTracker));
        }

        /**
         * @member {INetworkController[]} networkControllers
         */
        this.networkControllers = networkControllers;

        /**
         * @var {ICoreComponent[]}
         */
        const coreComponents = [
          playListLoader,
          fragmentLoader,
          keyLoader,
          abrController,
          bufferController,
          capLevelController,
          fpsController,
          id3TrackController,
          fragmentTracker
        ];

        // optional audio track and subtitle controller
        Controller = config.audioTrackController;
        Eif (Controller) {
          const audioTrackController = new Controller(this);

          /**
           * @member {AudioTrackController} audioTrackController
           */
          this.audioTrackController = audioTrackController;
          coreComponents.push(audioTrackController);
        }

        Controller = config.subtitleTrackController;
        Eif (Controller) {
          const subtitleTrackController = new Controller(this);

          /**
           * @member {SubtitleTrackController} subtitleTrackController
           */
          this.subtitleTrackController = subtitleTrackController;
          networkControllers.push(subtitleTrackController);
        }

        Controller = config.emeController;
        Eif (Controller) {
          const emeController = new Controller(this);

          /**
           * @member {EMEController} emeController
           */
          this.emeController = emeController;
          coreComponents.push(emeController);
        }

        // optional subtitle controllers
        Controller = config.subtitleStreamController;
        Eif (Controller) {
          networkControllers.push(new Controller(this, fragmentTracker));
        }
        Controller = config.timelineController;
        Eif (Controller) {
          coreComponents.push(new Controller(this));
        }

        /**
         * @member {ICoreComponent[]}
         */
        this.coreComponents = coreComponents;
      }

      /**
       * Dispose of the instance
       */
      destroy () {
        logger.log('destroy');
        this.trigger(HlsEvents.DESTROYING);
        this.detachMedia();
        this.coreComponents.concat(this.networkControllers).forEach(component => {
          component.destroy();
        });
        this.url = null;
        this.removeAllListeners();
        this._autoLevelCapping = -1;
      }

      /**
       * Attach a media element
       * @param {HTMLMediaElement} media
       */
      attachMedia (media: HTMLMediaElement) {
        logger.log('attachMedia');
        this.media = media;
        this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });
      }

      /**
       * Detach from the media
       */
      detachMedia () {
        logger.log('detachMedia');
        this.trigger(HlsEvents.MEDIA_DETACHING);
        this.media = null;
      }

      /**
       * Set the source URL. Can be relative or absolute.
       * @param {string} url
       */
      loadSource (url: string) {
        url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
        logger.log(`loadSource:${url}`);
        this.url = url;
        // when attaching to a source URL, trigger a playlist load
        this.trigger(HlsEvents.MANIFEST_LOADING, { url: url });
      }

      /**
       * Start loading data from the stream source.
       * Depending on default config, client starts loading automatically when a source is set.
       *
       * @param {number} startPosition Set the start position to stream from
       * @default -1 None (from earliest point)
       */
      startLoad (startPosition: number = -1) I{
        logger.log(`startLoad(${startPosition})`);
        this.networkControllers.forEach(controller => {
          controller.startLoad(startPosition);
        });
      }

      /**
       * Stop loading of any stream data.
       */
      stopLoad () {
        logger.log('stopLoad');
        this.networkControllers.forEach(controller => {
          controller.stopLoad();
        });
      }

      /**
       * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
       */
      swapAudioCodec () {
        logger.log('swapAudioCodec');
        this.streamController.swapAudioCodec();
      }

      /**
       * When the media-element fails, this allows to detach and then re-attach it
       * as one call (convenience method).
       *
       * Automatic recovery of media-errors by this process is configurable.
       */
      recoverMediaError () {
        logger.log('recoverMediaError');
        let media = this.media;
        this.detachMedia();
        if (media) {
          this.attachMedia(media);
        }
      }

      /**
       * @type {QualityLevel[]}
       */
      // todo(typescript-levelController)
      get levels (): any[] {
        return this.levelController.levels;
      }

      /**
       * Index of quality level currently played
       * @type {number}
       */
      get currentLevel (): number {
        return this.streamController.currentLevel;
      }

      /**
       * Set quality level index immediately .
       * This will flush the current buffer to replace the quality asap.
       * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
       * @type {number} -1 for automatic level selection
       */
      set currentLevel (newLevel: number) {
        logger.log(`set currentLevel:${newLevel}`);
        this.loadLevel = newLevel;
        this.streamController.immediateLevelSwitch();
      }

      /**
       * Index of next quality level loaded as scheduled by stream controller.
       * @type {number}
       */
      get nextLevel (): number {
        return this.streamController.nextLevel;
      }

      /**
       * Set quality level index for next loaded data.
       * This will switch the video quality asap, without interrupting playback.
       * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
       * @type {number} -1 for automatic level selection
       */
      set nextLevel (newLevel: number) {
        logger.log(`set nextLevel:${newLevel}`);
        this.levelController.manualLevel = newLevel;
        this.streamController.nextLevelSwitch();
      }

      /**
       * Return the quality level of the currently or last (of none is loaded currently) segment
       * @type {number}
       */
      get loadLevel (): number {
        return this.levelController.level;
      }

      /**
       * Set quality level index for next loaded data in a conservative way.
       * This will switch the quality without flushing, but interrupt current loading.
       * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
       * @type {number} newLevel -1 for automatic level selection
       */
      set loadLevel (newLevel: number) {
        logger.log(`set loadLevel:${newLevel}`);
        this.levelController.manualLevel = newLevel;
      }

      /**
       * get next quality level loaded
       * @type {number}
       */
      get nextLoadLevel (): number {
        return this.levelController.nextLoadLevel;
      }

      /**
       * Set quality level of next loaded segment in a fully "non-destructive" way.
       * Same as `loadLevel` but will wait for next switch (until current loading is done).
       * @type {number} level
       */
      set nextLoadLevel (level: number) {
        this.levelController.nextLoadLevel = level;
      }

      /**
       * Return "first level": like a default level, if not set,
       * falls back to index of first level referenced in manifest
       * @type {number}
       */
      get firstLevel (): number {
        return Math.max(this.levelController.firstLevel, this.minAutoLevel);
      }

      /**
       * Sets "first-level", see getter.
       * @type {number}
       */
      set firstLevel (newLevel: number) {
        logger.log(`set firstLevel:${newLevel}`);
        this.levelController.firstLevel = newLevel;
      }

      /**
       * Return start level (level of first fragment that will be played back)
       * if not overrided by user, first level appearing in manifest will be used as start level
       * if -1 : automatic start level selection, playback will start from level matching download bandwidth
       * (determined from download of first segment)
       * @type {number}
       */
      get startLevel (): number {
        return this.levelController.startLevel;
      }

      /**
       * set  start level (level of first fragment that will be played back)
       * if not overrided by user, first level appearing in manifest will be used as start level
       * if -1 : automatic start level selection, playback will start from level matching download bandwidth
       * (determined from download of first segment)
       * @type {number} newLevel
       */
      set startLevel (newLevel: number) {
        logger.log(`set startLevel:${newLevel}`);
        // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
        Iif (newLevel !== -1) {
          newLevel = Math.max(newLevel, this.minAutoLevel);
        }

        this.levelController.startLevel = newLevel;
      }

      /**
       * set  dynamically set capLevelToPlayerSize against (`CapLevelController`)
       *
       * @type {boolean}
       */
      set capLevelToPlayerSize (shouldStartCapping: boolean) {
        const newCapLevelToPlayerSize = !!shouldStartCapping;

        if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
          Iif (newCapLevelToPlayerSize) {
            this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
          } else {
            this.capLevelController.stopCapping();
            this.autoLevelCapping = -1;
            this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
          }

          this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
        }
      }

      /**
       * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
       * @type {number}
       */
      get autoLevelCapping (): number {
        return this._autoLevelCapping;
      }

      /**
       * get bandwidth estimate
       * @type {number}
       */
      get bandwidthEstimate (): number {
        const bwEstimator = this.abrController._bwEstimator;
        return bwEstimator ? bwEstimator.getEstimate() : NaN;
      }

      /**
       * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
       * @type {number}
       */
      set autoLevelCapping (newLevel: number) {
        logger.log(`set autoLevelCapping:${newLevel}`);
        this._autoLevelCapping = newLevel;
      }

      /**
       * True when automatic level selection enabled
       * @type {boolean}
       */
      get autoLevelEnabled (): boolean {
        return (this.levelController.manualLevel === -1);
      }

      /**
       * Level set manually (if any)
       * @type {number}
       */
      get manualLevel (): number {
        return this.levelController.manualLevel;
      }

      /**
       * min level selectable in auto mode according to config.minAutoBitrate
       * @type {number}
       */
      get minAutoLevel (): number {
        const { levels, config: { minAutoBitrate } } = this;
        const len = levels ? levels.length : 0;

        for (let i = 0; i < len; i++) {
          const levelNextBitrate = levels[i].realBitrate
            ? Math.max(levels[i].realBitrate, levels[i].bitrate)
            : levels[i].bitrate;

          Eif (levelNextBitrate > minAutoBitrate) {
            return i;
          }
        }

        return 0;
      }

      /**
       * max level selectable in auto mode according to autoLevelCapping
       * @type {number}
       */
      get maxAutoLevel (): number {
        const { levels, autoLevelCapping } = this;

        let maxAutoLevel;
        if (autoLevelCapping === -1 && levels && levels.length) {
          maxAutoLevel = levels.length - 1;
        } else {
          maxAutoLevel = autoLevelCapping;
        }

        return maxAutoLevel;
      }

      /**
       * next automatically selected quality level
       * @type {number}
       */
      get nextAutoLevel (): number {
        // ensure next auto level is between  min and max auto level
        return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
      }

      /**
       * this setter is used to force next auto level.
       * this is useful to force a switch down in auto mode:
       * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
       * forced value is valid for one fragment. upon succesful frag loading at forced level,
       * this value will be resetted to -1 by ABR controller.
       * @type {number}
       */
      set nextAutoLevel (nextLevel: number) {
        this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
      }

      /**
       * @type {AudioTrack[]}
       */
      // todo(typescript-audioTrackController)
      get audioTracks (): any[] {
        const audioTrackController = this.audioTrackController;
        return audioTrackController ? audioTrackController.audioTracks : [];
      }

      /**
       * index of the selected audio track (index in audio track lists)
       * @type {number}
       */
      get audioTrack (): number {
        const audioTrackController = this.audioTrackController;
        return audioTrackController ? audioTrackController.audioTrack : -1;
      }

      /**
       * selects an audio track, based on its index in audio track lists
       * @type {number}
       */
      set audioTrack (audioTrackId: number) {
        const audioTrackController = this.audioTrackController;
        if (audioTrackController) {
          audioTrackController.audioTrack = audioTrackId;
        }
      }

      /**
       * @type {Seconds}
       */
      get liveSyncPosition (): number {
        return this.streamController.liveSyncPosition;
      }

      /**
       * get alternate subtitle tracks list from playlist
       * @type {SubtitleTrack[]}
       */
      // todo(typescript-subtitleTrackController)
      get subtitleTracks (): any[] {
        const subtitleTrackController = this.subtitleTrackController;
        return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
      }

      /**
       * index of the selected subtitle track (index in subtitle track lists)
       * @type {number}
       */
      get subtitleTrack (): number {
        const subtitleTrackController = this.subtitleTrackController;
        return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
      }

      /**
       * select an subtitle track, based on its index in subtitle track lists
       * @type {number}
       */
      set subtitleTrack (subtitleTrackId: number) {
        const subtitleTrackController = this.subtitleTrackController;
        if (subtitleTrackController) {
          subtitleTrackController.subtitleTrack = subtitleTrackId;
        }
      }

      /**
       * @type {boolean}
       */
      get subtitleDisplay (): boolean {
        const subtitleTrackController = this.subtitleTrackController;
        return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
      }

      /**
       * Enable/disable subtitle display rendering
       * @type {boolean}
       */
      set subtitleDisplay (value: boolean) {
        const subtitleTrackController = this.subtitleTrackController;
        if (subtitleTrackController) {
          subtitleTrackController.subtitleDisplay = value;
        }
      }
    }