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

82.3% Statements 93/113
77.78% Branches 49/63
80.95% Functions 17/21
81.13% Lines 86/106

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

    171x
    171x

    171x
    171x
    171x
    171x

    171x

    171x

    15x

    3x
    3x
    3x
    2x

    1x

    1x

    1x
    1x

    1x

    15x
    15x

    9x
    9x
    9x
    9x
    9x
    8x
    8x

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

    2x
    2x

    1x
    1x

    6x

    15x
    14x
    14x

    9x
    1x
    1x

    13x
    13x
    13x
    8x

    5x
    5x

    17x
    17x
    1x

    16x
    16x
    2x
    4x

    14x
    14x
    5x

    16x
    16x
    9x

    14x
    14x
    4x

    10x
    10x
    10x
    10x

    3x

    3x
    3x
    3x
    5x

    1x
    4x
    1x
    1x

    3x

    19x
    19x
    38x

    38x
    38x

    19x

     import Event from '../events';
    import EventHandler from '../event-handler';
    import { logger } from '../utils/logger';
    import { computeReloadInterval } from './level-helper';

    class SubtitleTrackController extends EventHandler {
      constructor (hls) {
        super(hls,
          Event.MEDIA_ATTACHED,
          Event.MEDIA_DETACHING,
          Event.MANIFEST_LOADED,
          Event.SUBTITLE_TRACK_LOADED);
        this.tracks = [];
        this.trackId = -1;
        this.media = null;
        this.stopped = true;

        /**
         * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
         */
        this.subtitleDisplay = true;

        /**
         * Keeps reference to a default track id when media has not been attached yet
         * @member {number}
         */
        this.queuedDefaultTrack = null;
      }

      destroy () {
        EventHandler.prototype.destroy.call(this);
      }

      // Listen for subtitle track change, then extract the current track ID.
      onMediaAttached (data) {
        this.media = data.media;
        if (!this.media) {
          return;
        }

        Iif (Number.isFinite(this.queuedDefaultTrack)) {
          this.subtitleTrack = this.queuedDefaultTrack;
          this.queuedDefaultTrack = null;
        }

        this.trackChangeListener = this._onTextTracksChanged.bind(this);

        this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
        Iif (this.useTextTrackPolling) {
          this.subtitlePollingInterval = setInterval(() => {
            this.trackChangeListener();
          }, 500);
        } else {
          this.media.textTracks.addEventListener('change', this.trackChangeListener);
        }
      }

      onMediaDetaching () {
        Eif (!this.media) {
          return;
        }

        if (this.useTextTrackPolling) {
          clearInterval(this.subtitlePollingInterval);
        } else {
          this.media.textTracks.removeEventListener('change', this.trackChangeListener);
        }

        this.media = null;
      }

      // Fired whenever a new manifest is loaded.
      onManifestLoaded (data) {
        let tracks = data.subtitles || [];
        this.tracks = tracks;
        this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });

        // loop through available subtitle tracks and autoselect default if needed
        // TODO: improve selection logic to handle forced, etc
        tracks.forEach(track => {
          if (track.default) {
            // setting this.subtitleTrack will trigger internal logic
            // if media has not been attached yet, it will fail
            // we keep a reference to the default track id
            // and we'll set subtitleTrack when onMediaAttached is triggered
            if (this.media) {
              this.subtitleTrack = track.id;
            } else {
              this.queuedDefaultTrack = track.id;
            }
          }
        });
      }

      onSubtitleTrackLoaded (data) {
        const { id, details } = data;
        const { trackId, tracks } = this;
        const currentTrack = tracks[trackId];
        if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
          this._clearReloadTimer();
          return;
        }

        logger.log(`subtitle track ${id} loaded`);
        Eif (details.live) {
          const reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);
          logger.log(`Reloading live subtitle playlist in ${reloadInterval}ms`);
          this.timer = setTimeout(() => {
            this._loadCurrentTrack();
          }, reloadInterval);
        } else {
          this._clearReloadTimer();
        }
      }

      startLoad () {
        this.stopped = false;
        this._loadCurrentTrack();
      }

      stopLoad () {
        this.stopped = true;
        this._clearReloadTimer();
      }

      /** get alternate subtitle tracks list from playlist **/
      get subtitleTracks () {
        return this.tracks;
      }

      /** get index of the selected subtitle track (index in subtitle track lists) **/
      get subtitleTrack () {
        return this.trackId;
      }

      /** select a subtitle track, based on its index in subtitle track lists**/
      set subtitleTrack (subtitleTrackId) {
        if (this.trackId !== subtitleTrackId) {
          this._toggleTrackModes(subtitleTrackId);
          this._setSubtitleTrackInternal(subtitleTrackId);
        }
      }

      _clearReloadTimer () {
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }
      }

      _loadCurrentTrack () {
        const { trackId, tracks, hls } = this;
        const currentTrack = tracks[trackId];
        if (trackId < 0 || !currentTrack || (currentTrack.details && !currentTrack.details.live)) {
          return;
        }
        logger.log(`Loading subtitle track ${trackId}`);
        hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });
      }

      /**
       * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
       * This operates on the DOM textTracks.
       * A value of -1 will disable all subtitle tracks.
       * @param newId - The id of the next track to enable
       * @private
       */
      _toggleTrackModes (newId) {
        const { media, subtitleDisplay, trackId } = this;
        if (!media) {
          return;
        }

        const textTracks = filterSubtitleTracks(media.textTracks);
        if (newId === -1) {
          [].slice.call(textTracks).forEach(track => {
            track.mode = 'disabled';
          });
        } else {
          const oldTrack = textTracks[trackId];
          if (oldTrack) {
            oldTrack.mode = 'disabled';
          }
        }

        const nextTrack = textTracks[newId];
        if (nextTrack) {
          nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
        }
      }

      /**
         * This method is responsible for validating the subtitle index and periodically reloading if live.
         * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
         * @param newId - The id of the subtitle track to activate.
         */
      _setSubtitleTrackInternal (newId) {
        const { hls, tracks } = this;
        if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {
          return;
        }

        this.trackId = newId;
        logger.log(`Switching to subtitle track ${newId}`);
        hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });
        this._loadCurrentTrack();
      }

      _onTextTracksChanged () {
        // Media is undefined when switching streams via loadSource()
        Iif (!this.media) {
          return;
        }

        let trackId = -1;
        let tracks = filterSubtitleTracks(this.media.textTracks);
        for (let id = 0; id < tracks.length; id++) {
          if (tracks[id].mode === 'hidden') {
            // Do not break in case there is a following track with showing.
            trackId = id;
          } else if (tracks[id].mode === 'showing') {
            trackId = id;
            break;
          }
        }

        // Setting current subtitleTrack will invoke code.
        this.subtitleTrack = trackId;
      }
    }

    function filterSubtitleTracks (textTrackList) {
      let tracks = [];
      for (let i = 0; i < textTrackList.length; i++) {
        const track = textTrackList[i];
        // Edge adds a track without a label; we don't want to use it
        Eif (track.kind === 'subtitles' && track.label) {
          tracks.push(textTrackList[i]);
        }
      }
      return tracks;
    }

    export default SubtitleTrackController;