# All files / src/controller level-controller.js

47.42% Statements 101/213
40.58% Branches 56/138
60% Functions 21/35
47.57% Lines 98/206

    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

    14x

    129x

    129x
    129x
    129x
    129x

    129x

    13x
    13x

    14x

    1x

    1x
    1x

    1x

    1x

    8x
    8x

    8x
    8x
    8x
    8x

    8x
    17x
    17x
    17x

    17x
    17x

    17x

    17x

    17x
    17x
    17x
    17x
    17x

    17x
    1x
    1x
    1x

    1x

    8x

    8x
    17x

    8x
    8x

    8x
    4x

    8x

    7x

    10x
    7x

    7x
    7x
    7x
    7x
    7x

    7x

    3x

    1x

    4x

    2x
    2x
    1x
    1x
    1x

    1x
    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    3x

    4x

    1x
    1x
    1x

    1x

    59x
    1x

    1x

    58x

    58x

    3x
    3x
    3x

    58x

    20x
    18x

    4x

    1x
    1x
    1x

     /*
     * Level Controller
    */

    import Event from '../events';
    import EventHandler from '../event-handler';
    import { logger } from '../utils/logger';
    import { ErrorTypes, ErrorDetails } from '../errors';
    import { isCodecSupportedInMp4 } from '../utils/codecs';
    import { addGroupId } from './level-helper';

    const { performance } = window;
    let chromeOrFirefox;

    export default class LevelController extends EventHandler {
      constructor (hls) {
        super(hls,
          Event.MANIFEST_LOADED,
          Event.LEVEL_LOADED,
          Event.AUDIO_TRACK_SWITCHED,
          Event.FRAG_LOADED,
          Event.ERROR);

        this.canload = false;
        this.currentLevelIndex = null;
        this.manualLevelIndex = -1;
        this.timer = null;

        chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
      }

      onHandlerDestroying () {
        this.clearTimer();
        this.manualLevelIndex = -1;
      }

      clearTimer () {
        Iif (this.timer !== null) {
          clearTimeout(this.timer);
          this.timer = null;
        }
      }

      startLoad () {
        let levels = this._levels;

        this.canload = true;
        this.levelRetryCount = 0;

        // clean up live level details to force reload them, and reset load errors
        Iif (levels) {
          levels.forEach(level => {
            level.loadError = 0;
            const levelDetails = level.details;
            if (levelDetails && levelDetails.live) {
              level.details = undefined;
            }
          });
        }
        // speed up live playlist refresh if timer exists
        Iif (this.timer !== null) {
          this.loadLevel();
        }
      }

      stopLoad () {
        this.canload = false;
      }

      onManifestLoaded (data) {
        let levels = [];
        let audioTracks = [];
        let bitrateStart;
        let levelSet = {};
        let levelFromSet = null;
        let videoCodecFound = false;
        let audioCodecFound = false;

        // regroup redundant levels together
        data.levels.forEach(level => {
          const attributes = level.attrs;
          level.loadError = 0;
          level.fragmentError = false;

          videoCodecFound = videoCodecFound || !!level.videoCodec;
          audioCodecFound = audioCodecFound || !!level.audioCodec;

          // erase audio codec info if browser does not support mp4a.40.34.
          // demuxer will autodetect codec and fallback to mpeg/audio
          Iif (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
            level.audioCodec = undefined;
          }

          levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here

          Eif (!levelFromSet) {
            level.url = [level.url];
            level.urlId = 0;
            levelSet[level.bitrate] = level;
            levels.push(level);
          } else {
            levelFromSet.url.push(level.url);
          }

          if (attributes) {
            Eif (attributes.AUDIO) {
              audioCodecFound = true;
              addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);
            }
            Iif (attributes.SUBTITLES) {
              addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);
            }
          }
        });

        // remove audio-only level if we also have levels with audio+video codecs signalled
        Iif (videoCodecFound && audioCodecFound) {
          levels = levels.filter(({ videoCodec }) => !!videoCodec);
        }

        // only keep levels with supported audio/video codecs
        levels = levels.filter(({ audioCodec, videoCodec }) => {
          return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));
        });

        Eif (data.audioTracks) {
          audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));
          // Reassign id's after filtering since they're used as array indices
          audioTracks.forEach((track, index) => {
            track.id = index;
          });
        }

        if (levels.length > 0) {
          // start bitrate is the first bitrate of the manifest
          bitrateStart = levels[0].bitrate;
          // sort level on bitrate
          levels.sort((a, b) => a.bitrate - b.bitrate);
          this._levels = levels;
          // find index of first level in sorted levels
          for (let i = 0; i < levels.length; i++) {
            Eif (levels[i].bitrate === bitrateStart) {
              this._firstLevel = i;
              logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);
              break;
            }
          }

          // Audio is only alternate if manifest include a URI along with the audio group tag
          this.hls.trigger(Event.MANIFEST_PARSED, {
            levels,
            audioTracks,
            firstLevel: this._firstLevel,
            stats: data.stats,
            audio: audioCodecFound,
            video: videoCodecFound,
            altAudio: audioTracks.some(t => !!t.url)
          });
        } else {
          this.hls.trigger(Event.ERROR, {
            type: ErrorTypes.MEDIA_ERROR,
            details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
            fatal: true,
            url: this.hls.url,
            reason: 'no level with compatible codecs found in manifest'
          });
        }
      }

      get levels () {
        return this._levels;
      }

      get level () {
        return this.currentLevelIndex;
      }

      set level (newLevel) {
        let levels = this._levels;
        if (levels) {
          newLevel = Math.min(newLevel, levels.length - 1);
          Eif (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
            this.setLevelInternal(newLevel);
          }
        }
      }

      setLevelInternal (newLevel) {
        const levels = this._levels;
        const hls = this.hls;
        // check if level idx is valid
        Eif (newLevel >= 0 && newLevel < levels.length) {
          // stopping live reloading timer if any
          this.clearTimer();
          Eif (this.currentLevelIndex !== newLevel) {
            logger.log(`switching to level ${newLevel}`);
            this.currentLevelIndex = newLevel;
            const levelProperties = levels[newLevel];
            levelProperties.level = newLevel;
            hls.trigger(Event.LEVEL_SWITCHING, levelProperties);
          }
          const level = levels[newLevel];
          const levelDetails = level.details;

          // check if we need to load playlist for this level
          Iif (!levelDetails || levelDetails.live) {
            // level not retrieved yet, or live playlist we need to (re)load it
            let urlId = level.urlId;
            hls.trigger(Event.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
          }
        } else {
          // invalid level id given, trigger error
          hls.trigger(Event.ERROR, {
            type: ErrorTypes.OTHER_ERROR,
            details: ErrorDetails.LEVEL_SWITCH_ERROR,
            level: newLevel,
            fatal: false,
            reason: 'invalid level idx'
          });
        }
      }

      get manualLevel () {
        return this.manualLevelIndex;
      }

      set manualLevel (newLevel) {
        this.manualLevelIndex = newLevel;
        if (this._startLevel === undefined) {
          this._startLevel = newLevel;
        }

        if (newLevel !== -1) {
          this.level = newLevel;
        }
      }

      get firstLevel () {
        return this._firstLevel;
      }

      set firstLevel (newLevel) {
        this._firstLevel = newLevel;
      }

      get startLevel () {
        // hls.startLevel takes precedence over config.startLevel
        // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
        Eif (this._startLevel === undefined) {
          let configStartLevel = this.hls.config.startLevel;
          Iif (configStartLevel !== undefined) {
            return configStartLevel;
          } else {
            return this._firstLevel;
          }
        } else {
          return this._startLevel;
        }
      }

      set startLevel (newLevel) {
        this._startLevel = newLevel;
      }

      onError (data) {
        if (data.fatal) {
          Iif (data.type === ErrorTypes.NETWORK_ERROR) {
            this.clearTimer();
          }

          return;
        }

        let levelError = false, fragmentError = false;
        let levelIndex;

        // try to recover not fatal errors
        switch (data.details) {
        case ErrorDetails.FRAG_LOAD_ERROR:
        case ErrorDetails.FRAG_LOAD_TIMEOUT:
        case ErrorDetails.KEY_LOAD_ERROR:
        case ErrorDetails.KEY_LOAD_TIMEOUT:
          levelIndex = data.frag.level;
          fragmentError = true;
          break;
        case ErrorDetails.LEVEL_LOAD_ERROR:
        case ErrorDetails.LEVEL_LOAD_TIMEOUT:
          levelIndex = data.context.level;
          levelError = true;
          break;
        case ErrorDetails.REMUX_ALLOC_ERROR:
          levelIndex = data.level;
          levelError = true;
          break;
        }

        Iif (levelIndex !== undefined) {
          this.recoverLevel(data, levelIndex, levelError, fragmentError);
        }
      }

      /**
       * Switch to a redundant stream if any available.
       * If redundant stream is not available, emergency switch down if ABR mode is enabled.
       *
       * @param {Object} errorEvent
       * @param {Number} levelIndex current level index
       * @param {Boolean} levelError
       * @param {Boolean} fragmentError
       */
      // FIXME Find a better abstraction where fragment/level retry management is well decoupled
      recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {
        let { config } = this.hls;
        let { details: errorDetails } = errorEvent;
        let level = this._levels[levelIndex];
        let redundantLevels, delay, nextLevel;

        level.loadError++;
        level.fragmentError = fragmentError;

        if (levelError) {
          if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {
            // exponential backoff capped to max retry timeout
            delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
            // Schedule level reload
            this.timer = setTimeout(() => this.loadLevel(), delay);
            // boolean used to inform stream controller not to switch back to IDLE on non fatal error
            errorEvent.levelRetry = true;
            this.levelRetryCount++;
            logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);
          } else {
            logger.error(`level controller, cannot recover from ${errorDetails} error`);
            this.currentLevelIndex = null;
            // stopping live reloading timer if any
            this.clearTimer();
            // switch error to fatal
            errorEvent.fatal = true;
            return;
          }
        }

        // Try any redundant streams if available for both errors: level and fragment
        // If level.loadError reaches redundantLevels it means that we tried them all, no hope  => let's switch down
        if (levelError || fragmentError) {
          redundantLevels = level.url.length;

          if (redundantLevels > 1 && level.loadError < redundantLevels) {
            level.urlId = (level.urlId + 1) % redundantLevels;
            level.details = undefined;

            logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);

            // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
            // console.log('New video quality level audio group id:', level.attrs.AUDIO);
          } else {
            // Search for available level
            if (this.manualLevelIndex === -1) {
              // When lowest level has been reached, let's start hunt from the top
              nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;
              logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);
              this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
            } else if (fragmentError) {
              // Allow fragment retry as long as configuration allows.
              // reset this._level so that another call to set level() will trigger again a frag load
              logger.warn(`level controller, ${errorDetails}: reload a fragment`);
              this.currentLevelIndex = null;
            }
          }
        }
      }

      // reset errors on the successful load of a fragment
      onFragLoaded ({ frag }) {
        if (frag !== undefined && frag.type === 'main') {
          const level = this._levels[frag.level];
          if (level !== undefined) {
            level.fragmentError = false;
            level.loadError = 0;
            this.levelRetryCount = 0;
          }
        }
      }

      onLevelLoaded (data) {
        const levelId = data.level;
        // only process level loaded events matching with expected level
        if (levelId !== this.currentLevelIndex) {
          return;
        }

        const curLevel = this._levels[levelId];
        // reset level load error counter on successful level loaded only if there is no issues with fragments
        if (!curLevel.fragmentError) {
          curLevel.loadError = 0;
          this.levelRetryCount = 0;
        }
        let newDetails = data.details;
        // if current playlist is a live playlist, arm a timer to reload it
        if (newDetails.live) {
          const targetdurationMs = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration);
          let reloadInterval = targetdurationMs,
            curDetails = curLevel.details;
          if (curDetails && newDetails.endSN === curDetails.endSN) {
            // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
            // changed then it MUST wait for a period of one-half the target
            // duration before retrying.
            reloadInterval /= 2;
            logger.log('same live playlist, reload twice faster');
          }
          // decrement reloadInterval with level loading delay
          reloadInterval -= performance.now() - data.stats.trequest;
          // in any case, don't reload more than half of target duration
          reloadInterval = Math.max(targetdurationMs / 2, Math.round(reloadInterval));
          logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);
          this.timer = setTimeout(() => this.loadLevel(), reloadInterval);
        } else {
          this.clearTimer();
        }
      }

      onAudioTrackSwitched (data) {
        const audioGroupId = this.hls.audioTracks[data.id].groupId;

        const currentLevel = this.hls.levels[this.currentLevelIndex];
        if (!currentLevel) {
          return;
        }

        if (currentLevel.audioGroupIds) {
          const urlId = currentLevel.audioGroupIds.findIndex((groupId) => groupId === audioGroupId);
          if (urlId !== currentLevel.urlId) {
            currentLevel.urlId = urlId;
            this.startLoad();
          }
        }
      }

      loadLevel () {
        logger.debug('call to loadLevel');

        if (this.currentLevelIndex !== null && this.canload) {
          const levelObject = this._levels[this.currentLevelIndex];

          if (typeof levelObject === 'object' &&
            levelObject.url.length > 0) {
            const level = this.currentLevelIndex;
            const id = levelObject.urlId;
            const url = levelObject.url[id];

            logger.log(`Attempt loading level index ${level} with URL-id ${id}`);

            // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
            // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);

            this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });
          }
        }
      }

      get nextLoadLevel () {
        if (this.manualLevelIndex !== -1) {
          return this.manualLevelIndex;
        } else {
          return this.hls.nextAutoLevel;
        }
      }

      set nextLoadLevel (nextLevel) {
        this.level = nextLevel;
        Eif (this.manualLevelIndex === -1) {
          this.hls.nextAutoLevel = nextLevel;
        }
      }
    }