# All files / src/loader m3u8-parser.js

87.14% Statements 183/210
79% Branches 79/100
92.86% Functions 13/14
86.96% Lines 180/207

    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

    15x
    15x

    15x

    15x

    15x

    14x
    14x

    14x

    14x

    17x

    9x
    9x

    16x
    46x
    32x
    28x
    28x

    28x

    42x

    16x

    9x
    16x

    16x
    16x

    16x
    16x
    16x
    16x

    16x
    16x

    16x

    16x
    14x

    16x

    9x

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

    1x
    1x

    1x

    1x
    1x

    1x

    26x
    26x
    26x
    26x
    26x
    26x
    26x

    26x

    26x

    26x
    374x
    374x
    103x

    103x
    103x
    103x
    271x
    114x
    102x
    102x
    102x
    102x
    102x
    102x
    102x
    102x
    102x

    102x
    102x

    102x
    102x
    102x

    102x

    157x
    24x
    24x
    20x
    20x
    20x

    133x

    13x
    13x
    13x
    7x

    120x
    120x
    1093x
    120x

    120x
    120x

    120x

    15x
    15x

    8x
    8x

    15x
    15x

    20x
    20x

    19x
    19x

    23x

    10x
    10x

    5x
    5x
    5x

    1x
    1x

    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x

    2x

    2x

    1x
    1x
    1x

    1x
    1x

    1x

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

    26x

    26x

    26x
    26x
    26x
    26x
    26x

    26x

    23x

    26x
    1x

    26x

    1x
    1x
    2x
    2x
    2x

    102x
    13x
    89x
    6x

    102x
    84x
    84x

     import * as URLToolkit from 'url-toolkit';

    import Fragment from './fragment';
    import Level from './level';
    import LevelKey from './level-key';

    import AttrList from '../utils/attr-list';
    import { logger } from '../utils/logger';
    import { isCodecType } from '../utils/codecs';

    /**
     * M3U8 parser
     * @module
     */

    // https://regex101.com is your friend
    const MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
    const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;

    const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
      /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
      /|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
      /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
      /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
      /|#.*/.source // All other non-segment oriented tags will match with all groups empty
    ].join(''), 'g');

    const LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;

    const MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;

    export default class M3U8Parser {
      static findGroup (groups, mediaGroupId) {
        if (!groups) {
          return null;
        }

        let matchingGroup = null;

        for (let i = 0; i < groups.length; i++) {
          const group = groups[i];
          if (group.id === mediaGroupId) {
            matchingGroup = group;
          }
        }

        return matchingGroup;
      }

      static convertAVC1ToAVCOTI (codec) {
        let result, avcdata = codec.split('.');
        Iif (avcdata.length > 2) {
          result = avcdata.shift() + '.';
          result += parseInt(avcdata.shift()).toString(16);
          result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
        } else {
          result = codec;
        }
        return result;
      }

      static resolve (url, baseUrl) {
        return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
      }

      static parseMasterPlaylist (string, baseurl) {
        let levels = [], result;
        MASTER_PLAYLIST_REGEX.lastIndex = 0;

        function setCodecs (codecs, level) {
          ['video', 'audio'].forEach((type) => {
            const filtered = codecs.filter((codec) => isCodecType(codec, type));
            if (filtered.length) {
              const preferred = filtered.filter((codec) => {
                return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
              });
              level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];

              // remove from list
              codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);
            }
          });

          level.unknownCodecs = codecs;
        }

        while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
          const level = {};

          const attrs = level.attrs = new AttrList(result[1]);
          level.url = M3U8Parser.resolve(result[2], baseurl);

          const resolution = attrs.decimalResolution('RESOLUTION');
          Eif (resolution) {
            level.width = resolution.width;
            level.height = resolution.height;
          }
          level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
          level.name = attrs.NAME;

          setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);

          if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
            level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
          }

          levels.push(level);
        }
        return levels;
      }

      static parseMasterPlaylistMedia (string, baseurl, type, audioGroups = []) {
        let result;
        let medias = [];
        let id = 0;
        MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
        while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
          const media = {};
          const attrs = new AttrList(result[1]);
          Eif (attrs.TYPE === type) {
            media.groupId = attrs['GROUP-ID'];
            media.name = attrs.NAME;
            media.type = type;
            media.default = (attrs.DEFAULT === 'YES');
            media.autoselect = (attrs.AUTOSELECT === 'YES');
            media.forced = (attrs.FORCED === 'YES');
            Eif (attrs.URI) {
              media.url = M3U8Parser.resolve(attrs.URI, baseurl);
            }

            media.lang = attrs.LANGUAGE;
            Iif (!media.name) {
              media.name = media.lang;
            }

            Iif (audioGroups.length) {
              const groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
              media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
            }
            media.id = id++;
            medias.push(media);
          }
        }
        return medias;
      }

      static parseLevelPlaylist (string, baseurl, id, type, levelUrlId) {
        let currentSN = 0;
        let totalduration = 0;
        let level = new Level(baseurl);
        let levelkey = new LevelKey();
        let cc = 0;
        let prevFrag = null;
        let frag = new Fragment();
        let result;
        let i;

        let firstPdtIndex = null;

        LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;

        while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
          const duration = result[1];
          if (duration) { // INF
            frag.duration = parseFloat(duration);
            // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
            const title = (' ' + result[2]).slice(1);
            frag.title = title || null;
            frag.tagList.push(title ? [ 'INF', duration, title ] : [ 'INF', duration ]);
          } else if (result[3]) { // url
            if (Number.isFinite(frag.duration)) {
              const sn = currentSN++;
              frag.type = type;
              frag.start = totalduration;
              frag.levelkey = levelkey;
              frag.sn = sn;
              frag.level = id;
              frag.cc = cc;
              frag.urlId = levelUrlId;
              frag.baseurl = baseurl;
              // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
              frag.relurl = (' ' + result[3]).slice(1);
              assignProgramDateTime(frag, prevFrag);

              level.fragments.push(frag);
              prevFrag = frag;
              totalduration += frag.duration;

              frag = new Fragment();
            }
          } else if (result[4]) { // X-BYTERANGE
            frag.rawByteRange = (' ' + result[4]).slice(1);
            if (prevFrag) {
              const lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
              Eif (lastByteRangeEndOffset) {
                frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
              }
            }
          } else if (result[5]) { // PROGRAM-DATE-TIME
            // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
            frag.rawProgramDateTime = (' ' + result[5]).slice(1);
            frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
            if (firstPdtIndex === null) {
              firstPdtIndex = level.fragments.length;
            }
          } else {
            result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
            for (i = 1; i < result.length; i++) {
              if (result[i] !== undefined) {
                break;
              }
            }

            // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
            const value1 = (' ' + result[i + 1]).slice(1);
            const value2 = (' ' + result[i + 2]).slice(1);

            switch (result[i]) {
            case '#':
              frag.tagList.push(value2 ? [ value1, value2 ] : [ value1 ]);
              break;
            case 'PLAYLIST-TYPE':
              level.type = value1.toUpperCase();
              break;
            case 'MEDIA-SEQUENCE':
              currentSN = level.startSN = parseInt(value1);
              break;
            case 'TARGETDURATION':
              level.targetduration = parseFloat(value1);
              break;
            case 'VERSION':
              level.version = parseInt(value1);
              break;
            case 'EXTM3U':
              break;
            case 'ENDLIST':
              level.live = false;
              break;
            case 'DIS':
              cc++;
              frag.tagList.push(['DIS']);
              break;
            case 'DISCONTINUITY-SEQ':
              cc = parseInt(value1);
              break;
            case 'KEY':
              // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
              var decryptparams = value1;
              var keyAttrs = new AttrList(decryptparams);
              var decryptmethod = keyAttrs.enumeratedString('METHOD'),
                decrypturi = keyAttrs.URI,
                decryptiv = keyAttrs.hexadecimalInteger('IV');
              Eif (decryptmethod) {
                levelkey = new LevelKey();
                Eif ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {
                  levelkey.method = decryptmethod;
                  // URI to get the key
                  levelkey.baseuri = baseurl;
                  levelkey.reluri = decrypturi;
                  levelkey.key = null;
                  // Initialization Vector (IV)
                  levelkey.iv = decryptiv;
                }
              }
              break;
            case 'START':
              let startParams = value1;
              let startAttrs = new AttrList(startParams);
              let startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
              // TIME-OFFSET can be 0
              Eif (Number.isFinite(startTimeOffset)) {
                level.startTimeOffset = startTimeOffset;
              }

              break;
            case 'MAP':
              let mapAttrs = new AttrList(value1);
              frag.relurl = mapAttrs.URI;
              frag.rawByteRange = mapAttrs.BYTERANGE;
              frag.baseurl = baseurl;
              frag.level = id;
              frag.type = type;
              frag.sn = 'initSegment';
              level.initSegment = frag;
              frag = new Fragment();
              frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
              break;
            default:
              logger.warn(`line parsed but not handled: ${result}`);
              break;
            }
          }
        }
        frag = prevFrag;
        // logger.log('found ' + level.fragments.length + ' fragments');
        Iif (frag && !frag.relurl) {
          level.fragments.pop();
          totalduration -= frag.duration;
        }
        level.totalduration = totalduration;
        level.averagetargetduration = totalduration / level.fragments.length;
        level.endSN = currentSN - 1;
        level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
        level.endCC = cc;

        if (!level.initSegment && level.fragments.length) {
          // this is a bit lurky but HLS really has no other way to tell us
          // if the fragments are TS or MP4, except if we download them :/
          // but this is to be able to handle SIDX.
          Iif (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {
            logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');

            frag = new Fragment();
            frag.relurl = level.fragments[0].relurl;
            frag.baseurl = baseurl;
            frag.level = id;
            frag.type = type;
            frag.sn = 'initSegment';

            level.initSegment = frag;
            level.needSidxRanges = true;
          }
        }

        /**
         * Backfill any missing PDT values
           "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
           one or more Media Segment URIs, the client SHOULD extrapolate
           backward from that tag (using EXTINF durations and/or media
           timestamps) to associate dates with those segments."
         * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
         * computed.
         */
        if (firstPdtIndex) {
          backfillProgramDateTimes(level.fragments, firstPdtIndex);
        }

        return level;
      }
    }

    function backfillProgramDateTimes (fragments, startIndex) {
      let fragPrev = fragments[startIndex];
      for (let i = startIndex - 1; i >= 0; i--) {
        const frag = fragments[i];
        frag.programDateTime = fragPrev.programDateTime - (frag.duration * 1000);
        fragPrev = frag;
      }
    }

    function assignProgramDateTime (frag, prevFrag) {
      if (frag.rawProgramDateTime) {
        frag.programDateTime = Date.parse(frag.rawProgramDateTime);
      } else if (prevFrag && prevFrag.programDateTime) {
        frag.programDateTime = prevFrag.endProgramDateTime;
      }

      if (!Number.isFinite(frag.programDateTime)) {
        frag.programDateTime = null;
        frag.rawProgramDateTime = null;
      }
    }