# All files / src/controller fragment-tracker.js

96.36% Statements 106/110
84.75% Branches 50/59
100% Functions 23/23
96.36% Lines 106/110

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

    1x

    20x
    209x
    209x

    209x

    209x
    209x

    209x

    15x
    15x
    15x
    15x
    15x

    15x
    15x
    38x
    38x
    1x

    37x
    12x

    25x
    25x

    15x
    7x

    8x
    8x

    34x

    34x
    34x
    34x
    6x
    6x
    6x
    6x
    6x

    6x

    2x
    2x

    32x
    32x
    32x
    32x
    32x

    32x
    28x
    26x

    26x

    26x

    26x
    26x
    26x
    26x
    26x

    10x

    10x
    16x

    16x

    16x

    26x

    91x

    7x

    7x
    7x
    7x
    4x
    4x
    4x
    4x
    4x

    3x
    3x
    3x
    3x

    7x

    8x
    8x
    8x

    8x
    7x
    1x
    6x
    4x

    2x

    8x

    10x

    6x
    6x
    6x
    6x
    4x

    2x

    2x

    40x

    40x

    40x

    18x

    18x
    18x
    34x
    34x

    32x

    8x
    8x

    3x
    3x

    40x

     import EventHandler from '../event-handler';
    import Event from '../events';

    export const FragmentState = {
      NOT_LOADED: 'NOT_LOADED',
      APPENDING: 'APPENDING',
      PARTIAL: 'PARTIAL',
      OK: 'OK'
    };

    export class FragmentTracker extends EventHandler {
      constructor (hls) {
        super(hls,
          Event.BUFFER_APPENDED,
          Event.FRAG_BUFFERED,
          Event.FRAG_LOADED
        );

        this.bufferPadding = 0.2;

        this.fragments = Object.create(null);
        this.timeRanges = Object.create(null);

        this.config = hls.config;
      }

      destroy () {
        this.fragments = Object.create(null);
        this.timeRanges = Object.create(null);
        this.config = null;
        EventHandler.prototype.destroy.call(this);
        super.destroy();
      }

      /**
       * Return a Fragment that match the position and levelType.
       * If not found any Fragment, return null
       * @param {number} position
       * @param {LevelType} levelType
       * @returns {Fragment|null}
       */
      getBufferedFrag (position, levelType) {
        const fragments = this.fragments;
        const bufferedFrags = Object.keys(fragments).filter(key => {
          const fragmentEntity = fragments[key];
          if (fragmentEntity.body.type !== levelType) {
            return false;
          }

          if (!fragmentEntity.buffered) {
            return false;
          }

          const frag = fragmentEntity.body;
          return frag.startPTS <= position && position <= frag.endPTS;
        });
        if (bufferedFrags.length === 0) {
          return null;
        } else {
          // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
          const bufferedFragKey = bufferedFrags.pop();
          return fragments[bufferedFragKey].body;
        }
      }

      /**
       * Partial fragments effected by coded frame eviction will be removed
       * The browser will unload parts of the buffer to free up memory for new buffer data
       * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
       * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
       * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
       */
      detectEvictedFragments (elementaryStream, timeRange) {
        let fragmentTimes, time;
        // Check if any flagged fragments have been unloaded
        Object.keys(this.fragments).forEach(key => {
          const fragmentEntity = this.fragments[key];
          if (fragmentEntity.buffered === true) {
            const esData = fragmentEntity.range[elementaryStream];
            Eif (esData) {
              fragmentTimes = esData.time;
              for (let i = 0; i < fragmentTimes.length; i++) {
                time = fragmentTimes[i];

                if (this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
                  // Unregister partial fragment as it needs to load again to be reused
                  this.removeFragment(fragmentEntity.body);
                  break;
                }
              }
            }
          }
        });
      }

      /**
       * Checks if the fragment passed in is loaded in the buffer properly
       * Partially loaded fragments will be registered as a partial fragment
       * @param {Object} fragment Check the fragment against all sourceBuffers loaded
       */
      detectPartialFragments (fragment) {
        let fragKey = this.getFragmentKey(fragment);
        let fragmentEntity = this.fragments[fragKey];
        Eif (fragmentEntity) {
          fragmentEntity.buffered = true;

          Object.keys(this.timeRanges).forEach(elementaryStream => {
            if (fragment.hasElementaryStream(elementaryStream)) {
              let timeRange = this.timeRanges[elementaryStream];
              // Check for malformed fragments
              // Gaps need to be calculated for each elementaryStream
              fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
            }
          });
        }
      }

      getBufferedTimes (startPTS, endPTS, timeRange) {
        let fragmentTimes = [];
        let startTime, endTime;
        let fragmentPartial = false;
        for (let i = 0; i < timeRange.length; i++) {
          startTime = timeRange.start(i) - this.bufferPadding;
          endTime = timeRange.end(i) + this.bufferPadding;
          if (startPTS >= startTime && endPTS <= endTime) {
            // Fragment is entirely contained in buffer
            // No need to check the other timeRange times since it's completely playable
            fragmentTimes.push({
              startPTS: Math.max(startPTS, timeRange.start(i)),
              endPTS: Math.min(endPTS, timeRange.end(i))
            });
            break;
          } else Eif (startPTS < endTime && endPTS > startTime) {
            // Check for intersection with buffer
            // Get playable sections of the fragment
            fragmentTimes.push({
              startPTS: Math.max(startPTS, timeRange.start(i)),
              endPTS: Math.min(endPTS, timeRange.end(i))
            });
            fragmentPartial = true;
          } else if (endPTS <= startTime) {
            // No need to check the rest of the timeRange as it is in order
            break;
          }
        }

        return {
          time: fragmentTimes,
          partial: fragmentPartial
        };
      }

      getFragmentKey (fragment) {
        return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;
      }

      /**
       * Gets the partial fragment for a certain time
       * @param {Number} time
       * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
       */
      getPartialFragment (time) {
        let timePadding, startTime, endTime;
        let bestFragment = null;
        let bestOverlap = 0;
        Object.keys(this.fragments).forEach(key => {
          const fragmentEntity = this.fragments[key];
          Eif (this.isPartial(fragmentEntity)) {
            startTime = fragmentEntity.body.startPTS - this.bufferPadding;
            endTime = fragmentEntity.body.endPTS + this.bufferPadding;
            if (time >= startTime && time <= endTime) {
              // Use the fragment that has the most padding from start and end time
              timePadding = Math.min(time - startTime, endTime - time);
              Eif (bestOverlap <= timePadding) {
                bestFragment = fragmentEntity.body;
                bestOverlap = timePadding;
              }
            }
          }
        });
        return bestFragment;
      }

      /**
       * @param {Object} fragment The fragment to check
       * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
       */
      getState (fragment) {
        let fragKey = this.getFragmentKey(fragment);
        let fragmentEntity = this.fragments[fragKey];
        let state = FragmentState.NOT_LOADED;

        if (fragmentEntity !== undefined) {
          if (!fragmentEntity.buffered) {
            state = FragmentState.APPENDING;
          } else if (this.isPartial(fragmentEntity) === true) {
            state = FragmentState.PARTIAL;
          } else {
            state = FragmentState.OK;
          }
        }

        return state;
      }

      isPartial (fragmentEntity) {
        return fragmentEntity.buffered === true &&
          ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||
            (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));
      }

      isTimeBuffered (startPTS, endPTS, timeRange) {
        let startTime, endTime;
        for (let i = 0; i < timeRange.length; i++) {
          startTime = timeRange.start(i) - this.bufferPadding;
          endTime = timeRange.end(i) + this.bufferPadding;
          if (startPTS >= startTime && endPTS <= endTime) {
            return true;
          }

          Iif (endPTS <= startTime) {
            // No need to check the rest of the timeRange as it is in order
            return false;
          }
        }

        return false;
      }

      /**
       * Fires when a fragment loading is completed
       */
      onFragLoaded (e) {
        const fragment = e.frag;
        // don't track initsegment (for which sn is not a number)
        // don't track frags used for bitrateTest, they're irrelevant.
        Iif (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {
          return;
        }

        this.fragments[this.getFragmentKey(fragment)] = {
          body: fragment,
          range: Object.create(null),
          buffered: false
        };
      }

      /**
       * Fires when the buffer is updated
       */
      onBufferAppended (e) {
        // Store the latest timeRanges loaded in the buffer
        this.timeRanges = e.timeRanges;
        Object.keys(this.timeRanges).forEach(elementaryStream => {
          let timeRange = this.timeRanges[elementaryStream];
          this.detectEvictedFragments(elementaryStream, timeRange);
        });
      }

      /**
       * Fires after a fragment has been loaded into the source buffer
       */
      onFragBuffered (e) {
        this.detectPartialFragments(e.frag);
      }

      /**
       * Return true if fragment tracker has the fragment.
       * @param {Object} fragment
       * @returns {boolean}
       */
      hasFragment (fragment) {
        const fragKey = this.getFragmentKey(fragment);
        return this.fragments[fragKey] !== undefined;
      }

      /**
       * Remove a fragment from fragment tracker until it is loaded again
       * @param {Object} fragment The fragment to remove
       */
      removeFragment (fragment) {
        let fragKey = this.getFragmentKey(fragment);
        delete this.fragments[fragKey];
      }

      /**
       * Remove all fragments from fragment tracker.
       */
      removeAllFragments () {
        this.fragments = Object.create(null);
      }
    }