Coverage Report

Created: 2026-12-01 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gpac/src/media_tools/m3u8.c
Line
Count
Source
1
/*
2
 *      GPAC - Multimedia Framework C SDK
3
 *
4
 *      Authors: Pierre Souchay, Jean Le Feuvre, Romain Bouqueau
5
 *      Copyright (c) Telecom ParisTech 2010-2026
6
 *          All rights reserved
7
 *
8
 *  This file is part of GPAC
9
 *
10
 *  GPAC is free software; you can redistribute it and/or modify
11
 *  it under the terms of the GNU Lesser General Public License as published by
12
 *  the Free Software Foundation; either version 2, or (at your option)
13
 *  any later version.
14
 *
15
 *  GPAC is distributed in the hope that it will be useful,
16
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 *  GNU Lesser General Public License for more details.
19
 *
20
 *  You should have received a copy of the GNU Lesser General Public
21
 *  License along with this library; see the file COPYING.  If not, write to
22
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
 *
24
 */
25
26
#define _GNU_SOURCE
27
28
#include <gpac/internal/m3u8.h>
29
#include <gpac/network.h>
30
31
/********** accumulated_attributes **********/
32
33
typedef struct _s_accumulated_attributes {
34
  //TODO: store as a structure with: { attribute, version, mandatory }
35
  char *title;
36
  char *mediaURL;
37
  double duration_in_seconds;
38
  int bandwidth;
39
  int width, height;
40
  int stream_id;
41
  char *codecs;
42
  char *language;
43
  char *name;
44
  u32 channels;
45
  MediaType type;
46
  char *group_audio;
47
  char *group_video;
48
  char *group_subtitle;
49
  char *group_closed_captions;
50
  Bool forced;
51
52
  int target_duration_in_seconds;
53
  int min_media_sequence;
54
  int current_media_seq;
55
  u32 version;
56
  u32 compatibility_version; /*compute version required by the M3U8 content*/
57
  Bool is_master_playlist;
58
  Bool is_media_segment;
59
  Bool is_playlist_ended;
60
  Bool is_default;
61
  Bool is_autoselect;
62
  u64 playlist_utc_timestamp;
63
  u64 byte_range_start, byte_range_end;
64
  u64 init_byte_range_start, init_byte_range_end;
65
  PlaylistElementDRMMethod key_method;
66
  char *init_url;
67
  char *key_url;
68
  bin128 key_iv;
69
  Bool has_iv;
70
  Bool independent_segments;
71
  Bool low_latency, independent_part;
72
  u32 discontinuity;
73
} s_accumulated_attributes;
74
75
76
/********** playlist_element **********/
77
78
GF_Err playlist_element_del(PlaylistElement * e);
79
80
0
static GF_Err cleanup_list_of_elements(GF_List *list) {
81
0
  GF_Err result = GF_OK;
82
0
  if (list == NULL)
83
0
    return result;
84
0
  while (gf_list_count(list)) {
85
0
    PlaylistElement *pl = (PlaylistElement *) gf_list_get(list, 0);
86
0
    if (pl)
87
0
      result |= playlist_element_del(pl);
88
0
    gf_list_rem(list, 0);
89
0
  }
90
0
  gf_list_del(list);
91
0
  return result;
92
0
}
93
94
/**
95
 * Deletes an Playlist element
96
 */
97
0
GF_Err playlist_element_del(PlaylistElement * e) {
98
0
  GF_Err result = GF_OK;
99
0
  if (e == NULL)
100
0
    return result;
101
0
  if (e->title) {
102
0
    gf_free(e->title);
103
0
  }
104
0
  if (e->codecs) {
105
0
    gf_free(e->codecs);
106
0
  }
107
0
  if (e->language) {
108
0
    gf_free(e->language);
109
0
  }
110
0
  if (e->name) {
111
0
    gf_free(e->name);
112
0
  }
113
0
  if (e->audio_group) {
114
0
    gf_free(e->audio_group);
115
0
  }
116
0
  if (e->video_group) {
117
0
    gf_free(e->video_group);
118
0
  }
119
0
  if (e->key_uri) {
120
0
    gf_free(e->key_uri);
121
0
  }
122
0
  if (e->init_segment_url) {
123
0
    gf_free(e->init_segment_url);
124
0
  }
125
0
  if (e->alt_bandwidths) {
126
0
    gf_free(e->alt_bandwidths);
127
0
  }
128
0
  if (e->main_codecs) {
129
0
    gf_free(e->main_codecs);
130
0
  }
131
0
  memset(e->key_iv, 0, sizeof(bin128) );
132
0
  if (e->url)
133
0
    gf_free(e->url);
134
135
0
  switch (e->element_type) {
136
0
  case TYPE_UNKNOWN:
137
0
  case TYPE_MEDIA:
138
0
    break;
139
0
  case TYPE_PLAYLIST:
140
0
    gf_assert(e->element.playlist.elements);
141
0
    result |= cleanup_list_of_elements(e->element.playlist.elements);
142
0
  default:
143
0
    break;
144
0
  }
145
0
  gf_free(e);
146
0
  return result;
147
0
}
148
149
/**
150
 * Creates an Playlist element.
151
 * This element can be either a playlist of a stream according to first parameter.
152
 * \return The PlaylistElement or NULL if it could not be created. Elements will be deleted recursively.
153
 */
154
static PlaylistElement* playlist_element_new(PlaylistElementType element_type, const char *url, s_accumulated_attributes *attribs)
155
0
{
156
0
  PlaylistElement *e;
157
0
  GF_SAFEALLOC(e, PlaylistElement);
158
0
  if (e == NULL)
159
0
    return NULL;
160
161
0
  e->media_type = attribs->type;
162
0
  e->duration_info = attribs->duration_in_seconds;
163
0
  e->byte_range_start = attribs->byte_range_start;
164
0
  e->byte_range_end = attribs->byte_range_end;
165
0
  e->low_lat_chunk = attribs->low_latency;
166
0
  e->independent_chunk = attribs->independent_part;
167
168
0
  e->title = (attribs->title ? gf_strdup(attribs->title) : NULL);
169
0
  e->codecs = (attribs->codecs ? gf_strdup(attribs->codecs) : NULL);
170
0
  e->language = (attribs->language ? gf_strdup(attribs->language) : NULL);
171
0
  e->name = (attribs->name ? gf_strdup(attribs->name) : NULL);
172
0
  e->drm_method = attribs->key_method;
173
0
  e->init_segment_url = attribs->init_url ? gf_strdup(attribs->init_url) : NULL;
174
0
  e->init_byte_range_start = attribs->init_byte_range_start;
175
0
  e->init_byte_range_end = attribs->init_byte_range_end;
176
177
0
  if (e->drm_method) {
178
0
    e->key_uri = NULL;
179
0
    if (attribs->key_url) {
180
0
      e->key_uri = gf_strdup(attribs->key_url);
181
0
    }
182
183
0
    if (attribs->has_iv) {
184
0
      memcpy(e->key_iv, attribs->key_iv, sizeof(bin128));
185
0
    } else {
186
0
      u32 iv = gf_htonl(attribs->current_media_seq);
187
0
      memset(e->key_iv, 0, sizeof(bin128) );
188
0
      memcpy(e->key_iv + 12, (const void *) &iv, sizeof(iv));
189
0
    }
190
0
  }
191
192
0
  e->utc_start_time = attribs->playlist_utc_timestamp;
193
0
  e->discontinuity = attribs->discontinuity;
194
195
0
  gf_assert(url);
196
0
  e->url = gf_strdup(url);
197
0
  e->bandwidth = 0;
198
0
  e->element_type = element_type;
199
0
  if (element_type == TYPE_PLAYLIST) {
200
0
    e->element.playlist.is_ended = GF_FALSE;
201
0
    e->element.playlist.target_duration = attribs->duration_in_seconds;
202
0
    e->element.playlist.current_media_seq = 0;
203
0
    e->element.playlist.media_seq_min = 0;
204
0
    e->element.playlist.media_seq_max = 0;
205
0
    e->element.playlist.elements = gf_list_new();
206
0
    if (NULL == (e->element.playlist.elements)) {
207
0
      playlist_element_del(e);
208
0
      return NULL;
209
0
    }
210
0
  } else {
211
    /* Nothing to do, media is an empty structure */
212
0
  }
213
0
  gf_assert(e->bandwidth == 0);
214
0
  gf_assert(e->url);
215
0
  return e;
216
0
}
217
218
219
/********** stream **********/
220
221
/**
222
 * Creates a new stream properly initialized
223
 */
224
0
static Stream* stream_new(int stream_id) {
225
0
  Stream *program = (Stream *) gf_malloc(sizeof(Stream));
226
0
  if (program == NULL) {
227
0
    return NULL;
228
0
  }
229
0
  program->stream_id = stream_id;
230
0
  program->variants = gf_list_new();
231
0
  if (program->variants == NULL) {
232
0
    gf_free(program);
233
0
    return NULL;
234
0
  }
235
0
  return program;
236
0
}
237
238
/**
239
 * Deletes the specified stream
240
 */
241
0
static GF_Err stream_del(Stream *stream) {
242
0
  GF_Err e = GF_OK;
243
0
  if (stream == NULL)
244
0
    return e;
245
0
  if (stream->variants) {
246
0
    while (gf_list_count(stream->variants)) {
247
0
      GF_List *l = gf_list_get(stream->variants, 0);
248
0
      cleanup_list_of_elements(l);
249
0
      gf_list_rem(stream->variants, 0);
250
0
    }
251
0
    gf_list_del(stream->variants);
252
0
  }
253
0
  stream->variants = NULL;
254
0
  gf_free(stream);
255
0
  return e;
256
0
}
257
258
259
260
0
static GFINLINE int string2num(const char *s) {
261
0
  u64 ret=0, i, shift=2;
262
0
  u8 hash[GF_SHA1_DIGEST_SIZE];
263
0
  gf_sha1_csum((u8*)s, (u32)strlen(s), hash);
264
0
  gf_assert(shift*GF_SHA1_DIGEST_SIZE < 64);
265
0
  for (i=0; i<GF_SHA1_DIGEST_SIZE; ++i)
266
0
    ret += (ret << shift) + hash[i];
267
0
  return (int)(ret % MEDIA_TYPE_AUDIO);
268
0
}
269
270
271
0
#define GROUP_ID_TO_PROGRAM_ID(type, group_id) (\
272
0
  MEDIA_TYPE_##type + \
273
0
  string2num(group_id) \
274
0
  ) \
275
276
0
static Bool safe_start_equals(const char *attribute, const char *line) {
277
0
  size_t len, atlen;
278
0
  if (line == NULL)
279
0
    return GF_FALSE;
280
0
  len = strlen(line);
281
0
  atlen = strlen(attribute);
282
0
  if (len < atlen)
283
0
    return GF_FALSE;
284
0
  return (0 == strncmp(attribute, line, atlen));
285
0
}
286
287
288
static void reset_attributes(s_accumulated_attributes *attributes)
289
0
{
290
0
  memset(attributes, 0, sizeof(s_accumulated_attributes));
291
0
  attributes->type = MEDIA_TYPE_UNKNOWN;
292
0
  attributes->min_media_sequence = 1;
293
0
  attributes->version = 1;
294
0
  attributes->compatibility_version = 0;
295
0
  attributes->key_method = DRM_NONE;
296
0
}
297
298
0
static char** extract_attributes(const char *name, const char *line, const int num_attributes) {
299
0
  int sz, i, curr_attribute, start;
300
0
  char **ret;
301
0
  u8 quote = 0;
302
0
  int len = (u32) strlen(line);
303
0
  start = (u32) strlen(name);
304
0
  if (len <= start)
305
0
    return NULL;
306
0
  if (!safe_start_equals(name, line))
307
0
    return NULL;
308
0
  ret = gf_calloc((num_attributes + 1), sizeof(char*));
309
0
  if (!ret) return NULL;
310
0
  if (!num_attributes) return ret;
311
312
0
  curr_attribute = 0;
313
0
  for (i=start; i<=len; i++) {
314
0
    if (line[i] == '\0' || (!quote && line[i] == ',')  || (line[i] == quote)) {
315
0
      u32 spaces = 0;
316
0
      sz = i - start;
317
0
      if (quote && (line[i] == quote))
318
0
        sz++;
319
320
0
      while (line[start+spaces] == ' ')
321
0
        spaces++;
322
0
      if ((sz-spaces<=1) && (line[start+spaces]==',')) {
323
        //start = i+1;
324
0
      } else {
325
0
        if (!strncmp(&line[start+spaces], "\t", sz-spaces) || !strncmp(&line[start+spaces], "\n", sz-spaces)) {
326
0
        } else {
327
0
          ret[curr_attribute] = gf_malloc( (1+sz-spaces) * sizeof(char));
328
0
          memcpy(ret[curr_attribute], &(line[start+spaces]), sz-spaces);
329
0
          ret[curr_attribute][sz-spaces] = 0;
330
331
0
          curr_attribute++;
332
0
          if (curr_attribute >= num_attributes)
333
0
            break;
334
0
        }
335
0
      }
336
0
      start = i+1;
337
338
0
      if (start == len) {
339
0
        return ret;
340
0
      }
341
0
    }
342
0
    if ((line[i] == '\'') || (line[i] == '"'))  {
343
0
      if (quote) {
344
0
        quote = 0;
345
0
      } else {
346
0
        quote = line[i];
347
0
      }
348
0
    }
349
0
  }
350
0
  if (curr_attribute == 0) {
351
0
    gf_free(ret);
352
0
    return NULL;
353
0
  }
354
0
  return ret;
355
0
}
356
357
#define M3U8_COMPATIBILITY_VERSION(v) \
358
0
  if (v > attributes->compatibility_version) \
359
0
    attributes->compatibility_version = v;
360
361
static void free_attrs(char** attributes)
362
0
{
363
0
  u32 i = 0;
364
0
  while (attributes[i] != NULL) {
365
0
    gf_free(attributes[i]);
366
0
    i++;
367
0
  }
368
0
  gf_free(attributes);
369
0
}
370
/**
371
 * Parses the attributes and accumulate into the attributes structure
372
 */
373
0
static char** parse_attributes(const char *line, s_accumulated_attributes *attributes) {
374
0
  int int_value, i;
375
0
  char **ret;
376
0
  char *end_ptr;
377
0
  if (line == NULL)
378
0
    return NULL;
379
0
  if (!safe_start_equals("#EXT", line))
380
0
    return NULL;
381
0
  if (safe_start_equals("#EXT-X-ENDLIST", line)) {
382
0
    attributes->is_playlist_ended = GF_TRUE;
383
0
    M3U8_COMPATIBILITY_VERSION(1);
384
0
    return NULL;
385
0
  }
386
  /* reset not accumated attributes */
387
0
  attributes->type = MEDIA_TYPE_UNKNOWN;
388
389
0
  ret = extract_attributes("#EXT-X-TARGETDURATION:", line, 1);
390
0
  if (ret) {
391
    /* #EXT-X-TARGETDURATION:<seconds> */
392
0
    if (ret[0]) {
393
0
      int_value = (s32) strtol(ret[0], &end_ptr, 10);
394
0
      if (end_ptr != ret[0]) {
395
0
        attributes->target_duration_in_seconds = int_value;
396
0
      }
397
0
    }
398
0
    M3U8_COMPATIBILITY_VERSION(1);
399
0
    return ret;
400
0
  }
401
0
  ret = extract_attributes("#EXT-X-MEDIA-SEQUENCE:", line, 1);
402
0
  if (ret) {
403
    /* #EXT-X-MEDIA-SEQUENCE:<number> */
404
0
    if (ret[0]) {
405
0
      int_value = (s32)strtol(ret[0], &end_ptr, 10);
406
0
      if (end_ptr != ret[0]) {
407
0
        attributes->min_media_sequence = int_value;
408
0
        attributes->current_media_seq = int_value;
409
0
      }
410
0
    }
411
0
    M3U8_COMPATIBILITY_VERSION(1);
412
0
    return ret;
413
0
  }
414
0
  ret = extract_attributes("#EXT-X-VERSION:", line, 1);
415
0
  if (ret) {
416
    /* #EXT-X-VERSION:<number> */
417
0
    if (ret[0]) {
418
0
      int_value = (s32)strtol(ret[0], &end_ptr, 10);
419
0
      if (end_ptr != ret[0]) {
420
0
        attributes->version = int_value;
421
0
      }
422
      //although technically it is mandated for v2 or more, don't complain if set for v1
423
0
      M3U8_COMPATIBILITY_VERSION(1);
424
0
    }
425
0
    return ret;
426
0
  }
427
0
  ret = extract_attributes("#EXTINF:", line, 2);
428
0
  if (ret) {
429
0
    M3U8_COMPATIBILITY_VERSION(1);
430
    /* #EXTINF:<duration>,<title> */
431
0
    attributes->is_media_segment = GF_TRUE;
432
0
    if (ret[0]) {
433
0
      double double_value = strtod(ret[0], &end_ptr);
434
0
      if (end_ptr != ret[0]) {
435
0
        attributes->duration_in_seconds = double_value;
436
0
      }
437
0
      if (strstr(ret[0], ".") || (double_value > (int)double_value)) {
438
0
        M3U8_COMPATIBILITY_VERSION(3);
439
0
      }
440
0
    }
441
0
    if (ret[1]) {
442
0
      if (attributes->title) gf_free(attributes->title);
443
0
      attributes->title = gf_strdup(ret[1]);
444
0
    }
445
0
    return ret;
446
0
  }
447
0
  ret = extract_attributes("#EXT-X-KEY:", line, 4);
448
0
  if (ret) {
449
    /* #EXT-X-KEY:METHOD=<method>[,URI="<URI>"] */
450
0
    const char *method = "METHOD=";
451
0
    const size_t method_len = strlen(method);
452
0
    if (safe_start_equals(method, ret[0])) {
453
0
      if (!strncmp(ret[0]+method_len, "NONE", 4)) {
454
0
        attributes->key_method = DRM_NONE;
455
0
        if (attributes->key_url) {
456
0
          gf_free(attributes->key_url);
457
0
          attributes->key_url = NULL;
458
0
        }
459
0
      } else if (!strncmp(ret[0]+method_len, "AES-128", 7)) {
460
0
        attributes->key_method = DRM_AES_128;
461
0
      } else if (!strncmp(ret[0]+method_len, "SAMPLE-AES", 10)) {
462
0
        attributes->key_method = DRM_CENC_CBCS;
463
0
      } else if (!strncmp(ret[0]+method_len, "SAMPLE-AES-CTR", 14)) {
464
0
        attributes->key_method = DRM_CENC_CTR;
465
0
      } else {
466
0
        GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] EXT-X-KEY method not recognized.\n"));
467
0
      }
468
0
      if (ret[1] != NULL && safe_start_equals("URI=\"", ret[1])) {
469
0
        int_value = (u32) strlen(ret[1]);
470
0
        if (ret[1][int_value-1] == '"') {
471
0
          if (attributes->key_url) gf_free(attributes->key_url);
472
0
          attributes->key_url = gf_strdup(&(ret[1][5]));
473
0
          if (attributes->key_url) {
474
0
            u32 klen = (u32) strlen(attributes->key_url);
475
0
            attributes->key_url[klen ? klen-1 : 0] = 0;
476
0
          }
477
0
        }
478
0
      }
479
0
      attributes->has_iv = GF_FALSE;
480
0
      if (ret[2] != NULL && safe_start_equals("IV=", ret[2])) {
481
0
        char *IV = ret[2] + 3;
482
0
        if (!strncmp(IV, "0x", 2)) IV+=2;
483
0
        if (strlen(IV) != 32) {
484
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] EXT-X-KEY wrong IV len\n"));
485
0
        } else {
486
0
          for (i=0; i<16; i++) {
487
0
            char szV[3];
488
0
            u32 v;
489
0
            szV[0] = IV[2*i];
490
0
            szV[1] = IV[2*i + 1];
491
0
            szV[2] = 0;
492
0
            sscanf(szV, "%X", &v);
493
0
            attributes->key_iv[i] = v;
494
0
          }
495
0
        }
496
0
        attributes->has_iv = GF_TRUE;
497
0
      }
498
0
    }
499
0
    M3U8_COMPATIBILITY_VERSION(1);
500
0
    return ret;
501
0
  }
502
0
  ret = extract_attributes("#EXT-X-PROGRAM-DATE-TIME:", line, 1);
503
0
  if (ret) {
504
    /* #EXT-X-PROGRAM-DATE-TIME:<YYYY-MM-DDThh:mm:ssZ> */
505
0
    if (ret[0]) attributes->playlist_utc_timestamp = gf_net_parse_date(ret[0]);
506
0
    M3U8_COMPATIBILITY_VERSION(1);
507
0
    return ret;
508
0
  }
509
0
  ret = extract_attributes("#EXT-X-ALLOW-CACHE:", line, 1);
510
0
  if (ret) {
511
    /* #EXT-X-ALLOW-CACHE:<YES|NO> */
512
0
    GF_LOG(GF_LOG_INFO, GF_LOG_DASH,("[M3U8] EXT-X-ALLOW-CACHE not supported.\n", line));
513
0
    M3U8_COMPATIBILITY_VERSION(1);
514
0
    return ret;
515
0
  }
516
0
  ret = extract_attributes("#EXT-X-PLAYLIST-TYPE", line, 1);
517
0
  if (ret) {
518
0
    if (ret[0] && !strcmp(ret[0], "VOD")) attributes->is_playlist_ended = GF_TRUE;
519
0
    M3U8_COMPATIBILITY_VERSION(3);
520
0
    return ret;
521
0
  }
522
0
  ret = extract_attributes("#EXT-X-MAP", line, 4);
523
0
  if (ret) {
524
    /* #EXT-X-MAP:URI="<URI>"] */
525
0
    i=0;
526
0
    while (ret[i] != NULL) {
527
0
      char *val = ret[i];
528
0
      if (val[0]==':') val++;
529
0
      if (safe_start_equals("URI=\"", val)) {
530
0
        char *uri = val + 5;
531
0
        int_value = (u32) strlen(uri);
532
0
        if (int_value > 0 && uri[int_value-1] == '"') {
533
0
          if (attributes->init_url) gf_free(attributes->init_url);
534
0
          attributes->init_url = gf_strdup(uri);
535
0
          attributes->init_url[int_value-1]=0;
536
0
        } else {
537
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Invalid URI (%s) in EXT-X-MAP\n", val));
538
0
        }
539
0
      }
540
0
      else if (safe_start_equals("BYTERANGE=\"", val)) {
541
0
        u64 begin, size;
542
0
        val+=10;
543
0
        if (sscanf(val, "\""LLU"@"LLU"\"", &size, &begin) == 2) {
544
0
          if (size) {
545
0
            attributes->init_byte_range_start = begin;
546
0
            attributes->init_byte_range_end = begin + size - 1;
547
0
          } else {
548
0
            GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Invalid byte range %s\n", val));
549
0
          }
550
0
        }
551
0
      }
552
0
      i++;
553
0
    }
554
0
    M3U8_COMPATIBILITY_VERSION(3);
555
0
    return ret;
556
0
  }
557
0
  ret = extract_attributes("#EXT-X-STREAM-INF:", line, 10);
558
0
  if (ret) {
559
    /* #EXT-X-STREAM-INF:[attribute=value][,attribute=value]* */
560
0
    i = 0;
561
0
    attributes->is_master_playlist = GF_TRUE;
562
0
    M3U8_COMPATIBILITY_VERSION(1);
563
0
    while (ret[i] != NULL) {
564
0
      char *utility;
565
0
      if (safe_start_equals("BANDWIDTH=", ret[i])) {
566
0
        utility = &(ret[i][10]);
567
0
        int_value = (s32) strtol(utility, &end_ptr, 10);
568
0
        if (end_ptr != utility)
569
0
          attributes->bandwidth = int_value;
570
0
      } else if (safe_start_equals("PROGRAM-ID=", ret[i])) {
571
0
        utility = &(ret[i][11]);
572
0
        int_value = (s32) strtol(utility, &end_ptr, 10);
573
0
        if (end_ptr != utility)
574
0
          attributes->stream_id = int_value;
575
0
      } else if (safe_start_equals("CODECS=\"", ret[i])) {
576
0
        int_value = (u32) strlen(ret[i]);
577
0
        if (ret[i][int_value-1] == '"') {
578
0
          if (attributes->codecs) gf_free(attributes->codecs);
579
0
          attributes->codecs = gf_strdup(&(ret[i][8]));
580
0
          if (attributes->codecs[0]) attributes->codecs[strlen(attributes->codecs)-1] = 0;
581
0
        }
582
0
      } else if (safe_start_equals("RESOLUTION=", ret[i])) {
583
0
        u32 w, h;
584
0
        utility = &(ret[i][11]);
585
0
        if ((sscanf(utility, "%dx%d", &w, &h)==2) || (sscanf(utility, "%dx%d,", &w, &h)==2)) {
586
0
          attributes->width = w;
587
0
          attributes->height = h;
588
0
        }
589
0
        M3U8_COMPATIBILITY_VERSION(2);
590
0
      } else if (safe_start_equals("AUDIO=", ret[i])) {
591
0
        gf_assert(attributes->type == MEDIA_TYPE_UNKNOWN);
592
0
        attributes->type = MEDIA_TYPE_AUDIO;
593
0
        if (attributes->group_audio) gf_free(attributes->group_audio);
594
0
        attributes->group_audio = gf_strdup(ret[i] + 6);
595
0
        M3U8_COMPATIBILITY_VERSION(4);
596
0
      } else if (safe_start_equals("VIDEO=", ret[i])) {
597
0
        gf_assert(attributes->type == MEDIA_TYPE_UNKNOWN);
598
0
        attributes->type = MEDIA_TYPE_VIDEO;
599
0
        if (attributes->group_video) gf_free(attributes->group_video);
600
0
        attributes->group_video = gf_strdup(ret[i] + 6);
601
0
        M3U8_COMPATIBILITY_VERSION(4);
602
0
      }
603
0
      i++;
604
0
    }
605
0
    if (!attributes->bandwidth) {
606
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-STREAM-INF: no BANDWIDTH found. Ignoring the line.\n"));
607
0
      free_attrs(ret);
608
0
      return NULL;
609
0
    }
610
0
    return ret;
611
0
  }
612
0
  if (!strcmp(line, "#EXT-X-DISCONTINUITY") ) {
613
0
    attributes->discontinuity += 1;
614
0
    M3U8_COMPATIBILITY_VERSION(1);
615
0
    return ret;
616
0
  }
617
0
  ret = extract_attributes("#EXT-X-DISCONTINUITY-SEQUENCE:", line, 1);
618
0
  if (ret) {
619
0
    if (ret[0]) {
620
0
      int_value = (s32)strtol(ret[0], &end_ptr, 10);
621
0
      if (end_ptr != ret[0]) {
622
0
        attributes->discontinuity = int_value;
623
0
      }
624
0
    }
625
0
    M3U8_COMPATIBILITY_VERSION(1);
626
0
    return ret;
627
0
  }
628
0
  ret = extract_attributes("#EXT-X-BYTERANGE:", line, 1);
629
0
  if (ret) {
630
    /* #EXT-X-BYTERANGE:<begin@end> */
631
0
    if (ret[0]) {
632
0
      u64 begin, size;
633
0
      if (sscanf(ret[0], LLU"@"LLU, &size, &begin) == 2) {
634
0
        if (size) {
635
0
          attributes->byte_range_start = begin;
636
0
          attributes->byte_range_end = begin + size - 1;
637
0
        } else {
638
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Invalid byte range %s\n", ret[0]));
639
0
        }
640
0
      }
641
0
    }
642
0
    M3U8_COMPATIBILITY_VERSION(4);
643
0
    return ret;
644
0
  }
645
0
  ret = extract_attributes("#EXT-X-MEDIA:", line, 14);
646
0
  if (ret) {
647
    /* #EXT-X-MEDIA:[TYPE={AUDIO,VIDEO}],[URI],[GROUP-ID],[LANGUAGE],[NAME],[DEFAULT={YES,NO}],[AUTOSELECT={YES,NO}] */
648
0
    M3U8_COMPATIBILITY_VERSION(4);
649
0
    attributes->is_master_playlist = GF_TRUE;
650
0
    attributes->bandwidth = 0;
651
0
    attributes->width = 0;
652
0
    attributes->height = 0;
653
0
    attributes->channels = 0;
654
0
    attributes->forced = GF_FALSE;
655
0
    i = 0;
656
0
    while (ret[i] != NULL) {
657
0
      if (safe_start_equals("TYPE=", ret[i])) {
658
0
        if (!strncmp(ret[i]+5, "AUDIO", 5)) {
659
0
          attributes->type = MEDIA_TYPE_AUDIO;
660
0
        } else if (!strncmp(ret[i]+5, "VIDEO", 5)) {
661
0
          attributes->type = MEDIA_TYPE_VIDEO;
662
0
        } else if (!strncmp(ret[i]+5, "SUBTITLES", 9)) {
663
0
          attributes->type = MEDIA_TYPE_SUBTITLES;
664
0
        } else if (!strncmp(ret[i]+5, "CLOSED-CAPTIONS", 15)) {
665
0
          attributes->type = MEDIA_TYPE_CLOSED_CAPTIONS;
666
0
        } else {
667
0
          GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Unsupported #EXT-X-MEDIA:TYPE=%s\n", ret[i]+5));
668
0
        }
669
0
      } else if (safe_start_equals("URI=\"", ret[i])) {
670
0
        size_t len;
671
0
        if (attributes->mediaURL) gf_free(attributes->mediaURL);
672
0
        attributes->mediaURL = gf_strdup(ret[i]+5);
673
0
        len = strlen(attributes->mediaURL);
674
0
        if (len && (attributes->mediaURL[len-1] == '"')) {
675
0
          attributes->mediaURL[len-1] = '\0';
676
0
        } else {
677
0
          GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Misformed #EXT-X-MEDIA:URI=%s. Quotes are incorrect.\n", ret[i]+5));
678
0
        }
679
0
      } else if (safe_start_equals("GROUP-ID=", ret[i])) {
680
0
        if (attributes->type == MEDIA_TYPE_AUDIO) {
681
0
          if (attributes->group_audio) gf_free(attributes->group_audio);
682
0
          attributes->group_audio = gf_strdup(ret[i]+9);
683
0
          attributes->stream_id = GROUP_ID_TO_PROGRAM_ID(AUDIO, attributes->group_audio);
684
0
        } else if (attributes->type == MEDIA_TYPE_VIDEO) {
685
0
          if (attributes->group_video) gf_free(attributes->group_video);
686
0
          attributes->group_video = gf_strdup(ret[i]+9);
687
0
          attributes->stream_id = GROUP_ID_TO_PROGRAM_ID(VIDEO, attributes->group_video);
688
0
        } else if (attributes->type == MEDIA_TYPE_SUBTITLES) {
689
0
          if (attributes->group_subtitle) gf_free(attributes->group_subtitle);
690
0
          attributes->group_subtitle = gf_strdup(ret[i]+9);
691
0
          attributes->stream_id = GROUP_ID_TO_PROGRAM_ID(SUBTITLES, attributes->group_subtitle);
692
0
        } else if (attributes->type == MEDIA_TYPE_CLOSED_CAPTIONS) {
693
0
          if (attributes->group_closed_captions) gf_free(attributes->group_closed_captions);
694
0
          attributes->group_closed_captions = gf_strdup(ret[i]+9);
695
0
          attributes->stream_id = GROUP_ID_TO_PROGRAM_ID(CLOSED_CAPTIONS, attributes->group_closed_captions);
696
0
        } else if (attributes->type == MEDIA_TYPE_UNKNOWN) {
697
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA:GROUP-ID=%s. Ignoring the line.\n", ret[i]+9));
698
0
          free_attrs(ret);
699
0
          return NULL;
700
0
        }
701
0
      } else if (safe_start_equals("LANGUAGE=\"", ret[i])) {
702
0
        size_t len;
703
0
        u32 offset=9;
704
0
        if (ret[i][9] == '"') offset++;
705
0
        if (attributes->language) gf_free(attributes->language);
706
0
        attributes->language = gf_strdup(ret[i]+offset);
707
0
        len = strlen(attributes->language);
708
0
        if (len && (attributes->language[len-1] == '"')) {
709
0
          attributes->language[len-1] = '\0';
710
0
        } else {
711
0
          GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Misformed #EXT-X-MEDIA:LANGUAGE=%s. Quotes are incorrect.\n", ret[i]+5));
712
0
        }
713
0
      } else if (safe_start_equals("NAME=\"", ret[i])) {
714
0
        if (attributes->name) gf_free(attributes->name);
715
0
        attributes->name = gf_strdup(ret[i]+5+1);
716
0
        u32 len = (u32) strlen(attributes->name);
717
0
        if (len) attributes->name[len-1]=0;
718
0
      } else if (safe_start_equals("DEFAULT=", ret[i])) {
719
0
        if (!strncmp(ret[i]+8, "YES", 3)) {
720
0
          attributes->is_default = GF_TRUE;
721
0
        } else if (!strncmp(ret[i]+8, "NO", 2)) {
722
0
          attributes->is_default = GF_FALSE;
723
0
        } else {
724
0
          GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA:DEFAULT=%s\n", ret[i]+8));
725
0
        }
726
0
      } else if (safe_start_equals("AUTOSELECT=", ret[i])) {
727
0
        if (!strncmp(ret[i]+11, "YES", 3)) {
728
0
          attributes->is_autoselect = GF_TRUE;
729
0
        } else if (!strncmp(ret[i]+11, "NO", 2)) {
730
0
          attributes->is_autoselect = GF_TRUE;
731
0
        } else {
732
0
          GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA:AUTOSELECT=%s\n", ret[i]+11));
733
0
        }
734
0
      } else if (safe_start_equals("CHANNELS=", ret[i])) {
735
0
        sscanf(ret[i] + 9, "\"%u\"", &attributes->channels);
736
0
      } else if (safe_start_equals("INSTREAM-ID=", ret[i])) {
737
        //we don't signal CC for now
738
0
      } else if (safe_start_equals("FORCED=", ret[i])) {
739
0
        attributes->forced = !stricmp(ret[i] + 7, "yes") ? GF_TRUE : GF_FALSE;
740
0
      } else {
741
0
        GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Attribute %s not supported\n", ret[i]));
742
0
      }
743
0
      i++;
744
0
    }
745
746
0
    if (attributes->type == MEDIA_TYPE_UNKNOWN) {
747
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA: TYPE is missing. Ignoring the line.\n"));
748
0
      free_attrs(ret);
749
0
      return NULL;
750
0
    }
751
0
    if (attributes->type == MEDIA_TYPE_CLOSED_CAPTIONS && attributes->mediaURL) {
752
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA: TYPE is CLOSED-CAPTIONS but URI is present. Ignoring the URI.\n"));
753
0
      gf_free(attributes->mediaURL);
754
0
      attributes->mediaURL = NULL;
755
0
    }
756
0
    if ((attributes->type == MEDIA_TYPE_AUDIO && !attributes->group_audio)
757
0
            || (attributes->type == MEDIA_TYPE_VIDEO && !attributes->group_video)) {
758
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA: missing GROUP-ID attribute. Ignoring the line.\n"));
759
0
      free_attrs(ret);
760
0
      return NULL;
761
0
    }
762
0
    if (!attributes->stream_id) {
763
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Invalid #EXT-X-MEDIA: no ID was computed. Check previous errors. Ignoring the line.\n"));
764
0
      free_attrs(ret);
765
0
      return NULL;
766
0
    }
767
768
0
    return ret;
769
0
  }
770
0
  if (!strncmp(line, "#EXT-X-INDEPENDENT-SEGMENTS", strlen("#EXT-X-INDEPENDENT-SEGMENTS") )) {
771
0
    attributes->independent_segments = GF_TRUE;
772
0
    M3U8_COMPATIBILITY_VERSION(1);
773
0
    return NULL;
774
0
  }
775
0
  if (!strncmp(line, "#EXT-X-I-FRAME-STREAM-INF", strlen("#EXT-X-I-FRAME-STREAM-INF") )) {
776
    //todo extract I/intra rate for speed adaptation
777
0
    return NULL;
778
0
  }
779
  //ignored for now
780
0
  if (!strncmp(line, "#EXT-X-BITRATE", strlen("#EXT-X-BITRATE") )) {
781
0
    return NULL;
782
0
  }
783
0
  if (!strncmp(line, "#EXT-X-PART-INF", strlen("#EXT-X-PART-INF") )) {
784
0
    attributes->low_latency = GF_TRUE;
785
0
    return NULL;
786
0
  }
787
  //TODO for now we don't use preload hint
788
0
  if (!strncmp(line, "#EXT-X-SERVER-CONTROL", strlen("#EXT-X-SERVER-CONTROL") )) {
789
0
    return NULL;
790
0
  }
791
  //TODO for now we don't use preload hint
792
0
  if (!strncmp(line, "#EXT-X-PRELOAD-HINT", strlen("#EXT-X-PRELOAD-HINT") )) {
793
0
    return NULL;
794
0
  }
795
  //TODO for now we don't use preload hint
796
0
  if (!strncmp(line, "#EXT-X-RENDITION-REPORT", strlen("#EXT-X-RENDITION-REPORT") )) {
797
0
    return NULL;
798
0
  }
799
  //TODO for now we don't support interstitials
800
0
  if (!strncmp(line, "#EXT-X-DATERANGE", strlen("#EXT-X-DATERANGE") )) {
801
0
    return NULL;
802
0
  }
803
0
  GF_LOG(GF_LOG_WARNING, GF_LOG_DASH,("[M3U8] Unsupported directive %s\n", line));
804
0
  return NULL;
805
0
}
806
807
/**
808
 * Creates a new MasterPlaylist
809
\return NULL if MasterPlaylist element could not be allocated
810
 */
811
MasterPlaylist* master_playlist_new()
812
0
{
813
0
  MasterPlaylist *pl;
814
0
  GF_SAFEALLOC(pl, MasterPlaylist);
815
816
0
  if (pl == NULL)
817
0
    return NULL;
818
0
  pl->streams = gf_list_new();
819
0
  if (!pl->streams) {
820
0
    gf_free(pl);
821
0
    return NULL;
822
0
  }
823
0
  pl->current_stream = -1;
824
0
  pl->playlist_needs_refresh = GF_TRUE;
825
0
  return pl;
826
0
}
827
828
829
/********** master_playlist **********/
830
831
0
GF_Err gf_m3u8_master_playlist_del(MasterPlaylist **playlist) {
832
0
  if ((playlist == NULL) || (*playlist == NULL))
833
0
    return GF_OK;
834
0
  gf_assert((*playlist)->streams);
835
0
  while (gf_list_count((*playlist)->streams)) {
836
0
    Stream *p = gf_list_get((*playlist)->streams, 0);
837
0
    while (p && gf_list_count(p->variants)) {
838
0
      PlaylistElement *pl = gf_list_get(p->variants, 0);
839
0
      if (!pl) break;
840
0
      playlist_element_del(pl);
841
0
      gf_list_rem(p->variants, 0);
842
0
    }
843
0
    gf_list_del(p->variants);
844
0
    p->variants = NULL;
845
0
    stream_del(p);
846
0
    gf_list_rem((*playlist)->streams, 0);
847
0
  }
848
0
  gf_list_del((*playlist)->streams);
849
0
  (*playlist)->streams = NULL;
850
0
  gf_free(*playlist);
851
0
  *playlist = NULL;
852
853
0
  return GF_OK;
854
0
}
855
856
0
static Stream* master_playlist_find_matching_stream(const MasterPlaylist *pl, const u32 stream_id) {
857
0
  u32 count, i;
858
0
  gf_assert(pl);
859
0
  gf_assert(pl->streams);
860
0
  gf_assert(stream_id >= 0);
861
0
  count = gf_list_count(pl->streams);
862
0
  for (i=0; i<count; i++) {
863
0
    Stream *cur = gf_list_get(pl->streams, i);
864
0
    gf_assert(cur);
865
0
    if (stream_id == cur->stream_id) {
866
      /* We found the program */
867
0
      return cur;
868
0
    }
869
0
  }
870
0
  return NULL;
871
0
}
872
873
874
/********** sub_playlist **********/
875
876
#define M3U8_BUF_SIZE 2048
877
878
GF_EXPORT
879
GF_Err gf_m3u8_parse_master_playlist(const char *file, MasterPlaylist **playlist, const char *baseURL)
880
0
{
881
#ifdef GPAC_ENABLE_COVERAGE
882
  if (gf_sys_is_cov_mode()) {
883
    string2num("coverage");
884
  }
885
#endif
886
0
  return gf_m3u8_parse_sub_playlist(file, playlist, baseURL, NULL, NULL, GF_TRUE);
887
0
}
888
889
GF_Err declare_sub_playlist(char *currentLine, const char *baseURL, s_accumulated_attributes *attribs, PlaylistElement *sub_playlist, MasterPlaylist **playlist, Stream *in_stream)
890
0
{
891
0
  u32 i, count;
892
893
0
  char *fullURL = currentLine;
894
0
  if (!fullURL) return GF_BAD_PARAM;
895
896
0
  if (attribs->is_master_playlist && attribs->is_media_segment) {
897
0
    GF_LOG(GF_LOG_ERROR, GF_LOG_DASH, ("[M3U8] Media segment tag MUST NOT appear in a Master Playlist\n"));
898
0
    return GF_BAD_PARAM;
899
0
  }
900
901
0
  GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, ("[M3U8] declaring %s %s\n", attribs->is_master_playlist ? "sub-playlist" : "media segment", fullURL));
902
903
0
  {
904
0
    PlaylistElement *curr_playlist = sub_playlist;
905
    /* First, we have to find the matching stream */
906
0
    Stream *stream = in_stream;
907
0
    if (!in_stream)
908
0
      stream = master_playlist_find_matching_stream(*playlist, attribs->stream_id);
909
    /* We did not found the stream, we create it */
910
0
    if (stream == NULL) {
911
0
      stream = stream_new(attribs->stream_id);
912
0
      if (stream == NULL) {
913
        /* out of memory */
914
0
        gf_m3u8_master_playlist_del(playlist);
915
0
        return GF_OUT_OF_MEM;
916
0
      }
917
0
      gf_list_add((*playlist)->streams, stream);
918
      /* take the first regular variant stream */
919
0
      if ((*playlist)->current_stream < 0 && stream->stream_id < MEDIA_TYPE_AUDIO)
920
0
        (*playlist)->current_stream = stream->stream_id;
921
0
    }
922
923
    /* OK, we have a stream, we have to choose the elements within the same stream variant */
924
0
    gf_assert(stream);
925
0
    gf_assert(stream->variants);
926
0
    count = gf_list_count(stream->variants);
927
928
0
    if (!curr_playlist) {
929
0
      for (i=0; i<(s32)count; i++) {
930
0
        PlaylistElement *i_playlist_element = gf_list_get(stream->variants, i);
931
0
        gf_assert(i_playlist_element);
932
0
        if (stream->stream_id < MEDIA_TYPE_AUDIO) {
933
          /* regular stream (EXT-X-STREAM-INF) */
934
          // Two stream are identical only if they have the same URL
935
0
          if (attribs->is_media_segment || !strcmp(i_playlist_element->url, fullURL)) {
936
0
            curr_playlist = i_playlist_element;
937
0
            break;
938
0
          }
939
0
        } else {
940
          /* group streams (EXT-X-MEDIA) */
941
          //TODO: add renditions and compare depending on context parameters
942
0
        }
943
0
      }
944
0
    }
945
946
    /* We are the Master Playlist */
947
0
    if (attribs->is_master_playlist) {
948
0
      if (curr_playlist != NULL) {
949
        //playlist has already been defined - this happens when the same video playlist is defined several times with different audio codecs ...
950
0
        if (!attribs->codecs || !curr_playlist->audio_group || !attribs->group_audio || strstr(curr_playlist->audio_group, attribs->group_audio))
951
0
          return GF_OK;
952
        //gather codecs and bandwidth so that we can recompute them when generating the MPD
953
0
        if (!curr_playlist->alt_bandwidths) {
954
0
          curr_playlist->nb_alt_bandwidths = 1;
955
0
          curr_playlist->alt_bandwidths = gf_malloc(sizeof(u32));
956
0
          curr_playlist->alt_bandwidths[0] = curr_playlist->bandwidth;
957
0
        }
958
0
        char *codec = attribs->codecs;
959
0
        while (codec) {
960
0
          char *sep = strchr(codec, ',');
961
0
          if (sep) sep[0] = 0;
962
0
          if (!curr_playlist->codecs)
963
0
            gf_dynstrcat(&curr_playlist->codecs, codec, NULL);
964
0
          else if (!strstr(curr_playlist->codecs, codec))
965
0
            gf_dynstrcat(&curr_playlist->codecs, codec, ",");
966
0
          else if (!curr_playlist->main_codecs || !strstr(curr_playlist->main_codecs, codec))
967
0
            gf_dynstrcat(&curr_playlist->main_codecs, codec, ",");
968
0
          if (!sep) break;
969
0
          sep[0] = ',';
970
0
          codec = sep+1;
971
0
        }
972
0
        gf_dynstrcat(&curr_playlist->audio_group, attribs->group_audio, ",");
973
0
        curr_playlist->alt_bandwidths = gf_realloc(curr_playlist->alt_bandwidths, sizeof(u32)*(curr_playlist->nb_alt_bandwidths+1) );
974
0
        curr_playlist->alt_bandwidths[curr_playlist->nb_alt_bandwidths] = attribs->bandwidth;
975
0
        curr_playlist->nb_alt_bandwidths++;
976
0
        return GF_OK;
977
0
      }
978
0
      curr_playlist = playlist_element_new(TYPE_PLAYLIST, fullURL, attribs);
979
0
      if (curr_playlist == NULL) {
980
        /* out of memory */
981
0
        gf_m3u8_master_playlist_del(playlist);
982
0
        return GF_OUT_OF_MEM;
983
0
      }
984
0
      if (curr_playlist->url)
985
0
        gf_free(curr_playlist->url);
986
0
      curr_playlist->url = gf_strdup(fullURL);
987
0
      if (curr_playlist->title)
988
0
        gf_free(curr_playlist->title);
989
0
      curr_playlist->title = attribs->title ? gf_strdup(attribs->title) : NULL;
990
0
      if (curr_playlist->codecs)
991
0
        gf_free(curr_playlist->codecs);
992
0
      curr_playlist->codecs = attribs->codecs ? gf_strdup(attribs->codecs) : NULL;
993
0
      if (curr_playlist->audio_group) {
994
0
        GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[M3U8] Warning: found an AUDIO group in the master playlist."));
995
0
      }
996
0
      if (curr_playlist->video_group) {
997
0
        GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[M3U8] Warning: found an VIDEO group in the master playlist."));
998
0
      }
999
0
      curr_playlist->audio_group = attribs->group_audio ? gf_strdup(attribs->group_audio) : NULL;
1000
0
      gf_list_add(stream->variants, curr_playlist);
1001
0
      curr_playlist->width = attribs->width;
1002
0
      curr_playlist->height = attribs->height;
1003
0
      curr_playlist->channels = attribs->channels;
1004
0
    } else {
1005
      /* Normal Playlist */
1006
0
      gf_assert((*playlist)->streams);
1007
0
      if (curr_playlist == NULL) {
1008
1009
        /* This is a "normal" playlist without any element in it */
1010
0
        PlaylistElement *subElement;
1011
0
        gf_assert(baseURL);
1012
0
        curr_playlist = playlist_element_new(TYPE_PLAYLIST, baseURL, attribs);
1013
0
        if (curr_playlist == NULL) {
1014
          /* out of memory */
1015
0
          gf_m3u8_master_playlist_del(playlist);
1016
0
          return GF_OUT_OF_MEM;
1017
0
        }
1018
0
        gf_assert(curr_playlist->element.playlist.elements);
1019
0
        gf_assert(curr_playlist->url && !curr_playlist->codecs);
1020
0
        curr_playlist->codecs = NULL;
1021
1022
0
        subElement = playlist_element_new(TYPE_UNKNOWN, fullURL, attribs);
1023
0
        if (attribs->init_url) {
1024
0
          gf_free(attribs->init_url);
1025
0
          attribs->init_url = NULL;
1026
0
        }
1027
0
        if (subElement == NULL) {
1028
0
          gf_m3u8_master_playlist_del(playlist);
1029
0
          playlist_element_del(curr_playlist);
1030
0
          return GF_OUT_OF_MEM;
1031
0
        }
1032
0
        gf_list_add(curr_playlist->element.playlist.elements, subElement);
1033
0
        gf_list_add(stream->variants, curr_playlist);
1034
0
        curr_playlist->element.playlist.computed_duration += subElement->duration_info;
1035
0
        gf_assert(stream);
1036
0
        gf_assert(stream->variants);
1037
0
        gf_assert(curr_playlist);
1038
0
      } else {
1039
0
        PlaylistElement *subElement = playlist_element_new(TYPE_UNKNOWN, fullURL, attribs);
1040
0
        if (curr_playlist->element_type != TYPE_PLAYLIST) {
1041
0
          curr_playlist->element_type = TYPE_PLAYLIST;
1042
0
          if (!curr_playlist->element.playlist.elements)
1043
0
            curr_playlist->element.playlist.elements = gf_list_new();
1044
0
        }
1045
0
        if (subElement == NULL) {
1046
0
          gf_m3u8_master_playlist_del(playlist);
1047
0
          playlist_element_del(curr_playlist);
1048
0
          return GF_OUT_OF_MEM;
1049
0
        }
1050
0
        gf_list_add(curr_playlist->element.playlist.elements, subElement);
1051
0
        curr_playlist->element.playlist.computed_duration += subElement->duration_info;
1052
0
      }
1053
0
    }
1054
1055
0
    curr_playlist->element.playlist.current_media_seq = attribs->current_media_seq;
1056
    /* We first set the default duration for element, aka targetDuration */
1057
0
    if (attribs->target_duration_in_seconds > 0) {
1058
0
      curr_playlist->element.playlist.target_duration = attribs->target_duration_in_seconds;
1059
0
      curr_playlist->duration_info = attribs->target_duration_in_seconds;
1060
0
    }
1061
0
    if (attribs->duration_in_seconds) {
1062
0
      if (curr_playlist->duration_info == 0) {
1063
        /* we set the playlist duration info as the duration of a segment, only if it's not set
1064
        There are cases of playlist with the last segment with a duration different from the others
1065
        (example: Apple bipbop test)*/
1066
0
        curr_playlist->duration_info = attribs->duration_in_seconds;
1067
0
      }
1068
0
    }
1069
0
    curr_playlist->element.playlist.media_seq_min = attribs->min_media_sequence;
1070
0
    curr_playlist->element.playlist.media_seq_max = attribs->current_media_seq;
1071
0
    curr_playlist->element.playlist.discontinuity = attribs->discontinuity;
1072
0
    if (attribs->bandwidth > 1)
1073
0
      curr_playlist->bandwidth = attribs->bandwidth;
1074
0
    if (attribs->is_playlist_ended)
1075
0
      curr_playlist->element.playlist.is_ended = GF_TRUE;
1076
0
  }
1077
  /* Cleanup all line-specific fields */
1078
0
  if (attribs->title) {
1079
0
    gf_free(attribs->title);
1080
0
    attribs->title = NULL;
1081
0
  }
1082
0
  attribs->duration_in_seconds = 0;
1083
0
  attribs->playlist_utc_timestamp = 0;
1084
0
  attribs->bandwidth = 0;
1085
0
  attribs->stream_id = 0;
1086
0
  attribs->is_default = 0;
1087
0
  attribs->is_autoselect = 0;
1088
0
  if (attribs->codecs != NULL) {
1089
0
    gf_free(attribs->codecs);
1090
0
    attribs->codecs = NULL;
1091
0
  }
1092
0
  if (attribs->language != NULL) {
1093
0
    gf_free(attribs->language);
1094
0
    attribs->language = NULL;
1095
0
  }
1096
0
  if (attribs->name != NULL) {
1097
0
    gf_free(attribs->name);
1098
0
    attribs->name = NULL;
1099
0
  }
1100
0
  if (attribs->group_audio != NULL) {
1101
0
    gf_free(attribs->group_audio);
1102
0
    attribs->group_audio = NULL;
1103
0
  }
1104
0
  if (attribs->group_video != NULL) {
1105
0
    gf_free(attribs->group_video);
1106
0
    attribs->group_video = NULL;
1107
0
  }
1108
0
  if (attribs->group_subtitle != NULL) {
1109
0
    gf_free(attribs->group_subtitle);
1110
0
    attribs->group_subtitle = NULL;
1111
0
  }
1112
0
  if (attribs->group_closed_captions != NULL) {
1113
0
    gf_free(attribs->group_closed_captions);
1114
0
    attribs->group_closed_captions = NULL;
1115
0
  }
1116
0
  return GF_OK;
1117
0
}
1118
1119
typedef struct
1120
{
1121
  char *name;
1122
  u64 start;
1123
  u32 size;
1124
  Double duration;
1125
} HLS_LLChunk;
1126
1127
static void reset_attribs(s_accumulated_attributes *attribs, Bool is_cleanup)
1128
0
{
1129
0
  attribs->width = attribs->height = 0;
1130
0
#define RST_ATTR(_name) if (attribs->_name) { gf_free(attribs->_name); attribs->_name = NULL; }
1131
1132
0
  RST_ATTR(codecs)
1133
0
  RST_ATTR(group_audio)
1134
0
  RST_ATTR(group_video)
1135
0
  RST_ATTR(group_subtitle)
1136
0
  RST_ATTR(group_closed_captions)
1137
0
  RST_ATTR(language)
1138
0
  RST_ATTR(title)
1139
0
  if (is_cleanup) {
1140
0
    RST_ATTR(key_url)
1141
0
    RST_ATTR(name)
1142
0
  }
1143
0
  RST_ATTR(init_url)
1144
0
  RST_ATTR(mediaURL)
1145
0
}
1146
1147
1148
GF_Err gf_m3u8_parse_sub_playlist(const char *m3u8_file, MasterPlaylist **playlist, const char *baseURL, Stream *in_stream, PlaylistElement *sub_playlist, Bool is_master)
1149
0
{
1150
0
  int i, currentLineNumber;
1151
0
  FILE *f = NULL;
1152
0
  u8 *m3u8_payload;
1153
0
  u32 m3u8_size, m3u8pos;
1154
0
  char line_buffer[M3U8_BUF_SIZE];
1155
0
  char *currentLine = line_buffer;
1156
0
  size_t line_capacity = sizeof(line_buffer);
1157
0
  char **attributes = NULL;
1158
0
  Bool release_blob = GF_FALSE;
1159
0
  s_accumulated_attributes attribs;
1160
1161
0
  if (!strncmp(m3u8_file, "gmem://", 7)) {
1162
0
    GF_Err e = gf_blob_get(m3u8_file, &m3u8_payload,  &m3u8_size, NULL);
1163
0
    if (e) {
1164
0
      GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Cannot Open m3u8 source %s for reading\n", m3u8_file));
1165
0
      return e;
1166
0
    }
1167
0
    release_blob = GF_TRUE;
1168
0
  } else {
1169
0
    f = gf_fopen(m3u8_file, "rt");
1170
0
    if (!f) {
1171
0
      GF_LOG(GF_LOG_ERROR, GF_LOG_DASH,("[M3U8] Cannot open m3u8 file %s for reading\n", m3u8_file));
1172
0
      return GF_URL_ERROR;
1173
0
    }
1174
0
  }
1175
1176
0
  memset(&attribs, 0, sizeof(s_accumulated_attributes));
1177
1178
0
#define _CLEANUP \
1179
0
  reset_attribs(&attribs, GF_TRUE);\
1180
0
  if (currentLine != line_buffer) gf_free(currentLine); \
1181
0
  if (f) gf_fclose(f); \
1182
0
  else if (release_blob) gf_blob_release(m3u8_file);
1183
1184
1185
0
  if (*playlist == NULL) {
1186
0
    *playlist = master_playlist_new();
1187
0
    if (!(*playlist)) {
1188
0
      _CLEANUP
1189
0
      return GF_OUT_OF_MEM;
1190
0
    }
1191
0
  }
1192
0
  currentLineNumber = 0;
1193
0
  reset_attributes(&attribs);
1194
0
  m3u8pos = 0;
1195
0
  while (1) {
1196
0
    char *eof;
1197
0
    int len;
1198
0
    if (f) {
1199
0
      if (!gf_fgets(currentLine, sizeof(line_buffer), f))
1200
0
        break;
1201
0
    } else {
1202
0
      u32 line_start = m3u8pos;
1203
0
      size_t line_size;
1204
0
      if (m3u8pos >= m3u8_size)
1205
0
        break;
1206
      /* Keep a complete logical line, including its terminating newline. */
1207
0
      while (m3u8pos < m3u8_size) {
1208
0
        char c = m3u8_payload[m3u8pos++];
1209
0
        if ((c=='\n') || (c=='\r')) break;
1210
0
      }
1211
0
      line_size = m3u8pos - line_start;
1212
0
      if (line_size >= line_capacity) {
1213
0
        char *new_line = NULL;
1214
        /* Reserve the NUL without overflowing size_t on 32-bit builds. */
1215
0
        if (line_size != (size_t) -1)
1216
0
          new_line = gf_realloc(currentLine == line_buffer ? NULL : currentLine, line_size + 1);
1217
0
        if (!new_line) {
1218
0
          _CLEANUP
1219
0
          return GF_OUT_OF_MEM;
1220
0
        }
1221
0
        currentLine = new_line;
1222
0
        line_capacity = line_size + 1;
1223
0
      }
1224
0
      memcpy(currentLine, m3u8_payload + line_start, line_size);
1225
0
      currentLine[line_size] = 0;
1226
0
    }
1227
0
    currentLineNumber++;
1228
0
    eof = strchr(currentLine, '\r');
1229
0
    if (eof)
1230
0
      eof[0] = '\0';
1231
0
    eof = strchr(currentLine, '\n');
1232
0
    if (eof)
1233
0
      eof[0] = '\0';
1234
0
    len = (u32) strlen(currentLine);
1235
0
    if (len < 1)
1236
0
      continue;
1237
0
    if (currentLineNumber == 1) {
1238
      /* Playlist MUST start with #EXTM3U */
1239
0
      if (len < 7 || (strncmp("#EXTM3U", currentLine, 7) != 0)) {
1240
0
        GF_LOG(GF_LOG_ERROR, GF_LOG_DASH, ("Failed to parse M3U8 File, it should start with #EXTM3U, but was : %s\n", currentLine));
1241
0
        _CLEANUP
1242
0
        return GF_STREAM_NOT_FOUND;
1243
0
      }
1244
0
      continue;
1245
0
    }
1246
0
    if (currentLine[0] == '#') {
1247
      /* chunk */
1248
0
      if (!strncmp("#EXT-X-PART:", currentLine, 12)) {
1249
0
        GF_Err e = GF_NON_COMPLIANT_BITSTREAM;
1250
0
        char *sep;
1251
0
        char *file = strstr(currentLine, "URI=\"");
1252
0
        char *dur = strstr(currentLine, "DURATION=");
1253
0
        char *br = strstr(currentLine, "BYTERANGE=");
1254
1255
0
        if (strstr(currentLine, "INDEPENDENT=YES")) {
1256
0
          attribs.independent_part = GF_TRUE;
1257
0
        }
1258
0
        if (br) {
1259
0
          u64 start=0;
1260
0
          u32 size=0;
1261
0
          sep = strchr(br, ',');
1262
0
          if (sep) sep[0] = 0;
1263
0
          if (sscanf(br+10, "\"%u@"LLU"\"", &size, &start) != 2)
1264
0
            file = NULL;
1265
0
          attribs.byte_range_start = start;
1266
0
          attribs.byte_range_end = start + size - 1;
1267
0
        }
1268
0
        if (dur) {
1269
0
          sep = strchr(dur, ',');
1270
0
          if (sep) sep[0] = 0;
1271
0
          attribs.duration_in_seconds = atof(dur+9);
1272
0
        }
1273
1274
0
        if (file && dur) {
1275
0
          file += 5; // file starts with `URI:"`, move to start of URL
1276
          //find end quote
1277
0
          sep = strchr(file, '"');
1278
0
          if (!sep) {
1279
0
            e = GF_NON_COMPLIANT_BITSTREAM;
1280
0
            _CLEANUP
1281
0
            return e;
1282
0
          }
1283
0
          sep[0] = 0;
1284
1285
0
          attribs.low_latency = GF_TRUE;
1286
0
          attribs.is_media_segment = GF_TRUE;
1287
0
          e = declare_sub_playlist(file, baseURL, &attribs, sub_playlist, playlist, in_stream);
1288
1289
0
          (*playlist)->low_latency = GF_TRUE;
1290
0
          sep[0] = '"';
1291
0
        }
1292
0
        attribs.is_media_segment = GF_FALSE;
1293
0
        attribs.low_latency = GF_FALSE;
1294
0
        attribs.independent_part = GF_FALSE;
1295
0
        attribs.byte_range_start = attribs.byte_range_end = 0;
1296
0
        attribs.duration_in_seconds = 0;
1297
0
        if (e != GF_OK) {
1298
0
          _CLEANUP
1299
0
          return e;
1300
0
        }
1301
0
      }
1302
      /* A comment or a directive */
1303
0
      else if (!strncmp("#EXT", currentLine, 4)) {
1304
0
        attributes = parse_attributes(currentLine, &attribs);
1305
0
        if (attributes == NULL) {
1306
0
          GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, ("[M3U8]Comment at line %d : %s\n", currentLineNumber, currentLine));
1307
0
        } else {
1308
0
          GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, ("[M3U8] Directive at line %d: \"%s\", attributes=", currentLineNumber, currentLine));
1309
0
          i = 0;
1310
0
          while (attributes[i] != NULL) {
1311
0
            GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, (" [%d]='%s'", i, attributes[i]));
1312
0
            gf_free(attributes[i]);
1313
0
            attributes[i] = NULL;
1314
0
            i++;
1315
0
          }
1316
0
          GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, ("\n"));
1317
0
          gf_free(attributes);
1318
0
          attributes = NULL;
1319
0
        }
1320
0
        if (attribs.is_playlist_ended) {
1321
0
          (*playlist)->playlist_needs_refresh = GF_FALSE;
1322
0
        }
1323
0
        if (attribs.independent_segments) {
1324
0
          (*playlist)->independent_segments = GF_TRUE;
1325
0
        }
1326
0
        if (attribs.low_latency) {
1327
0
          (*playlist)->low_latency = GF_TRUE;
1328
0
          attribs.low_latency = GF_FALSE;
1329
0
        }
1330
0
        if (attribs.version > (*playlist)->version) {
1331
0
          (*playlist)->version = attribs.version;
1332
0
        }
1333
0
        if (attribs.mediaURL) {
1334
0
          GF_Err e = declare_sub_playlist(attribs.mediaURL, baseURL, &attribs, sub_playlist, playlist, in_stream);
1335
0
          gf_free(attribs.mediaURL);
1336
0
          attribs.mediaURL = NULL;
1337
0
          if (e != GF_OK) {
1338
0
            _CLEANUP
1339
0
            return e;
1340
0
          }
1341
0
        }
1342
0
      }
1343
0
    } else {
1344
1345
      /*file encountered: sub-playlist or segment*/
1346
0
      GF_Err e;
1347
0
      const char *pl_url = baseURL;
1348
      //this is the first (master) playlist but what is parsed is not a master playlist
1349
      //we will create a master + child with xlink, but the xlink must be only the file name
1350
      //otherwise dir/pl_video.m3u8 will be translated in master(dir/pl_video.m3u8) [ child(xlink=dir/pl_video.m3u8) ]
1351
      //thus xlink resolution would give dir/dir/pl_video.m3u8
1352
0
      if (is_master && !attribs.is_master_playlist)
1353
0
        pl_url = gf_file_basename(baseURL);
1354
0
      e = declare_sub_playlist(currentLine, pl_url, &attribs, sub_playlist, playlist, in_stream);
1355
0
      attribs.current_media_seq += 1;
1356
0
      if (e != GF_OK) {
1357
0
        _CLEANUP
1358
0
        return e;
1359
0
      }
1360
1361
      //do not reset all attributes but at least set width/height/codecs to NULL, otherwise we may miss detection
1362
      //of audio-only playlists in av sequences
1363
1364
0
      reset_attribs(&attribs, GF_FALSE);
1365
0
    }
1366
0
  }
1367
1368
0
  _CLEANUP
1369
1370
0
#undef _CLEANUP
1371
1372
0
  for (i=0; i<(int)gf_list_count((*playlist)->streams); i++) {
1373
0
    u32 j;
1374
0
    Stream *prog = gf_list_get((*playlist)->streams, i);
1375
0
    prog->computed_duration = 0;
1376
0
    for (j=0; j<gf_list_count(prog->variants); j++) {
1377
0
      PlaylistElement *ple = gf_list_get(prog->variants, j);
1378
0
      if (ple->element_type == TYPE_PLAYLIST) {
1379
0
        if (ple->element.playlist.computed_duration > prog->computed_duration)
1380
0
          prog->computed_duration = ple->element.playlist.computed_duration;
1381
0
      }
1382
0
    }
1383
1384
0
  }
1385
1386
0
  if (attribs.version < attribs.compatibility_version) {
1387
0
    GF_LOG(GF_LOG_DEBUG, GF_LOG_DASH, ("[M3U8] Version %d specified but tags from version %d detected\n", attribs.version, attribs.compatibility_version));
1388
0
  }
1389
0
  return GF_OK;
1390
0
}