# All files / src/controller subtitle-stream-controller.js

58.14% Statements 75/129
27.94% Branches 19/68
75% Functions 12/16
56.8% Lines 71/125

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

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

    1x

    1x

    1x

    1x

    1x

    141x

    141x
    141x
    141x
    141x
    141x
    141x
    141x

    1x
    15x
    15x
    15x

    1x

    1x
    11x
    11x

    1x
    23x
    23x

    1x
    59x

    59x
    59x

    2x
    2x
    2x
    2x
    2x
    4x

    1x
    20x
    20x
    4x
    4x

    16x
    16x
    3x

    1x
    12x

    12x
    2x
    2x

    10x
    4x
    4x

    10x

    1x

    1x
    20x
    20x
    20x
    20x

    20x

    1x
    4x
    4x
    4x

    1x

    1x
     /**
     * @class SubtitleStreamController
     */

    import Event from '../events';
    import { logger } from '../utils/logger';
    import Decrypter from '../crypt/decrypter';
    import TaskLoop from '../task-loop';
    import { BufferHelper } from '../utils/buffer-helper';
    import { findFragmentByPTS, findFragmentByPDT } from './fragment-finders';
    import { FragmentState } from './fragment-tracker';

    const { performance } = window;

    export const SubtitleStreamControllerState = {
      STOPPED: 'STOPPED',
      IDLE: 'IDLE',
      KEY_LOADING: 'KEY_LOADING',
      FRAG_LOADING: 'FRAG_LOADING'
    };

    const State = SubtitleStreamControllerState;

    const TICK_INTERVAL = 500; // how often to tick in ms

    export class SubtitleStreamController extends TaskLoop {
      constructor (hls, fragmentTracker) {
        super(hls,
          Event.MEDIA_ATTACHED,
          Event.MEDIA_DETACHING,
          Event.ERROR,
          Event.KEY_LOADED,
          Event.FRAG_LOADED,
          Event.SUBTITLE_TRACKS_UPDATED,
          Event.SUBTITLE_TRACK_SWITCH,
          Event.SUBTITLE_TRACK_LOADED,
          Event.SUBTITLE_FRAG_PROCESSED);

        this.fragmentTracker = fragmentTracker;
        this.config = hls.config;
        this.state = State.STOPPED;
        this.tracks = [];
        this.tracksBuffered = [];
        this.currentTrackId = -1;
        this.decrypter = new Decrypter(hls, hls.config);
      }

      onHandlerDestroyed () {
        this.fragmentTracker = null;
        this.state = State.STOPPED;
        super.onHandlerDestroyed();
      }

      onSubtitleFragProcessed (data) {
        this.state = State.IDLE;

        if (!data.success) {
          return;
        }

        const buffered = this.tracksBuffered[this.currentTrackId];
        const frag = data.frag;

        this.fragPrevious = frag;

        if (!buffered) {
          return;
        }

        // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
        // so we can re-use the logic used to detect how much have been buffered
        // FIXME: put this in a utility function or proper object for time-ranges manipulation?
        let timeRange;
        for (let i = 0; i < buffered.length; i++) {
          if (frag.start >= buffered[i].start && frag.start <= buffered[i].end) {
            timeRange = buffered[i];
            break;
          }
        }

        if (timeRange) {
          timeRange.end = frag.start + frag.duration;
        } else {
          buffered.push({
            start: frag.start,
            end: frag.start + frag.duration
          });
        }
      }

      onMediaAttached (data) {
        this.media = data.media;
        this.state = State.IDLE;
      }

      onMediaDetaching () {
        this.media = null;
        this.state = State.STOPPED;
      }

      // If something goes wrong, procede to next frag, if we were processing one.
      onError (data) {
        let frag = data.frag;
        // don't handle error not related to subtitle fragment
        Eif (!frag || frag.type !== 'subtitle') {
          return;
        }
        this.state = State.IDLE;
      }

      // Got all new subtitle tracks.
      onSubtitleTracksUpdated (data) {
        logger.log('subtitle tracks updated');
        this.tracksBuffered = [];
        this.tracks = data.subtitleTracks;
        this.tracks.forEach((track) => {
          this.tracksBuffered[track.id] = [];
        });
      }

      onSubtitleTrackSwitch (data) {
        this.currentTrackId = data.id;
        if (!this.tracks || this.currentTrackId === -1) {
          this.clearInterval();
          return;
        }

        // Check if track has the necessary details to load fragments
        const currentTrack = this.tracks[this.currentTrackId];
        if (currentTrack && currentTrack.details) {
          this.setInterval(TICK_INTERVAL);
        }
      }

      // Got a new set of subtitle fragments.
      onSubtitleTrackLoaded (data) {
        const { id, details } = data;

        if (!this.tracks) {
          logger.warn('Can not update subtitle details, no tracks found');
          return;
        }

        if (this.tracks[id]) {
          logger.log('Updating subtitle track details');
          this.tracks[id].details = details;
        }

        this.setInterval(TICK_INTERVAL);
      }

      onKeyLoaded () {
        if (this.state === State.KEY_LOADING) {
          this.state = State.IDLE;
        }
      }

      onFragLoaded (data) {
        const fragCurrent = this.fragCurrent;
        const decryptData = data.frag.decryptdata;
        const fragLoaded = data.frag;
        const hls = this.hls;

        Iif (this.state === State.FRAG_LOADING &&
            fragCurrent &&
            data.frag.type === 'subtitle' &&
            fragCurrent.sn === data.frag.sn) {
          // check to see if the payload needs to be decrypted
          if (data.payload.byteLength > 0 && (decryptData && decryptData.key && decryptData.method === 'AES-128')) {
            let startTime = performance.now();

            // decrypt the subtitles
            this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
              let endTime = performance.now();

              hls.trigger(Event.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
            });
          }
        }
      }

      doTick () {
        Eif (!this.media) {
          this.state = State.IDLE;
          return;
        }

        switch (this.state) {
        case State.IDLE:
          const tracks = this.tracks;
          const trackId = this.currentTrackId;

          if (!tracks || !tracks[trackId] || !tracks[trackId].details) {
            break;
          }

          const trackDetails = tracks[trackId].details;

          const config = this.config;
          const maxBufferHole = config.maxBufferHole;
          const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
          const maxFragLookUpTolerance = config.maxFragLookUpTolerance;

          const bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), this.media.currentTime, maxBufferHole);
          const bufferEnd = bufferedInfo.end;
          const bufferLen = bufferedInfo.len;

          const fragments = trackDetails.fragments;
          const fragLen = fragments.length;
          const end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;

          let foundFrag;
          if (bufferLen < maxConfigBuffer && bufferEnd < end) {
            foundFrag = findFragmentByPTS(this.fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
          } else if (trackDetails.hasProgramDateTime && this.fragPrevious) {
            foundFrag = findFragmentByPDT(fragments, this.fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
          }

          if (foundFrag && foundFrag.encrypted) {
            logger.log(`Loading key for ${foundFrag.sn}`);
            this.state = State.KEY_LOADING;
            this.hls.trigger(Event.KEY_LOADING, { frag: foundFrag });
          } else if (foundFrag && this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
            // only load if fragment is not loaded
            foundFrag.trackId = trackId; // Frags don't know their subtitle track ID, so let's just add that...
            this.fragCurrent = foundFrag;
            this.state = State.FRAG_LOADING;

            this.hls.trigger(Event.FRAG_LOADING, { frag: foundFrag });
          }
        }
      }

      _getBuffered () {
        return this.tracksBuffered[this.currentTrackId] || [];
      }
    }