d27d4ca77748ce9695d171c2acd8f6b14aab0405
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / ext / adaptivedemux2 / hls / m3u8.c
1 /* GStreamer
2  * Copyright (C) 2010 Marc-Andre Lureau <marcandre.lureau@gmail.com>
3  * Copyright (C) 2015 Tim-Philipp Müller <tim@centricular.com>
4  *
5  * Copyright (C) 2021-2022 Centricular Ltd
6  *   Author: Edward Hervey <edward@centricular.com>
7  *   Author: Jan Schmidt <jan@centricular.com>
8  *
9  * m3u8.c:
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public
22  * License along with this library; if not, write to the
23  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #include <stdlib.h>
28 #include <math.h>
29 #include <errno.h>
30 #include <glib.h>
31 #include <gmodule.h>
32 #include <string.h>
33
34 #include <gst/pbutils/pbutils.h>
35 #include "m3u8.h"
36 #include "gstadaptivedemux.h"
37 #include "gsthlselements.h"
38
39 #define GST_CAT_DEFAULT hls2_debug
40
41 static gchar *uri_join (const gchar * uri, const gchar * path);
42
43 GstHLSMediaPlaylist *
44 gst_hls_media_playlist_ref (GstHLSMediaPlaylist * m3u8)
45 {
46   g_assert (m3u8 != NULL && m3u8->ref_count > 0);
47
48   g_atomic_int_add (&m3u8->ref_count, 1);
49   return m3u8;
50 }
51
52 void
53 gst_hls_media_playlist_unref (GstHLSMediaPlaylist * self)
54 {
55   g_return_if_fail (self != NULL && self->ref_count > 0);
56
57   if (g_atomic_int_dec_and_test (&self->ref_count)) {
58     g_free (self->uri);
59     g_free (self->base_uri);
60
61     g_ptr_array_free (self->segments, TRUE);
62
63     g_free (self->last_data);
64     g_mutex_clear (&self->lock);
65     g_free (self);
66   }
67 }
68
69 static GstM3U8MediaSegment *
70 gst_m3u8_media_segment_new (gchar * uri, gchar * title, GstClockTime duration,
71     gint64 sequence, gint64 discont_sequence)
72 {
73   GstM3U8MediaSegment *file;
74
75   file = g_new0 (GstM3U8MediaSegment, 1);
76   file->uri = uri;
77   file->title = title;
78   file->duration = duration;
79   file->sequence = sequence;
80   file->discont_sequence = discont_sequence;
81   file->ref_count = 1;
82
83   file->stream_time = GST_CLOCK_STIME_NONE;
84
85   return file;
86 }
87
88 GstM3U8MediaSegment *
89 gst_m3u8_media_segment_ref (GstM3U8MediaSegment * mfile)
90 {
91   g_assert (mfile != NULL && mfile->ref_count > 0);
92
93   g_atomic_int_add (&mfile->ref_count, 1);
94   return mfile;
95 }
96
97 void
98 gst_m3u8_media_segment_unref (GstM3U8MediaSegment * self)
99 {
100   g_return_if_fail (self != NULL && self->ref_count > 0);
101
102   if (g_atomic_int_dec_and_test (&self->ref_count)) {
103     if (self->init_file)
104       gst_m3u8_init_file_unref (self->init_file);
105     g_free (self->title);
106     g_free (self->uri);
107     g_free (self->key);
108     if (self->datetime)
109       g_date_time_unref (self->datetime);
110     g_free (self);
111   }
112 }
113
114 static GstM3U8InitFile *
115 gst_m3u8_init_file_new (gchar * uri)
116 {
117   GstM3U8InitFile *file;
118
119   file = g_new0 (GstM3U8InitFile, 1);
120   file->uri = uri;
121   file->ref_count = 1;
122
123   return file;
124 }
125
126 GstM3U8InitFile *
127 gst_m3u8_init_file_ref (GstM3U8InitFile * ifile)
128 {
129   g_assert (ifile != NULL && ifile->ref_count > 0);
130
131   g_atomic_int_add (&ifile->ref_count, 1);
132   return ifile;
133 }
134
135 void
136 gst_m3u8_init_file_unref (GstM3U8InitFile * self)
137 {
138   g_return_if_fail (self != NULL && self->ref_count > 0);
139
140   if (g_atomic_int_dec_and_test (&self->ref_count)) {
141     g_free (self->uri);
142     g_free (self);
143   }
144 }
145
146 gboolean
147 gst_m3u8_init_file_equal (const GstM3U8InitFile * ifile1,
148     const GstM3U8InitFile * ifile2)
149 {
150   if (ifile1 == ifile2)
151     return TRUE;
152
153   if (ifile1 == NULL && ifile2 != NULL)
154     return FALSE;
155   if (ifile1 != NULL && ifile2 == NULL)
156     return FALSE;
157
158   if (!g_str_equal (ifile1->uri, ifile2->uri))
159     return FALSE;
160   if (ifile1->offset != ifile2->offset)
161     return FALSE;
162   if (ifile1->size != ifile2->size)
163     return FALSE;
164
165   return TRUE;
166 }
167
168 static gboolean
169 int_from_string (gchar * ptr, gchar ** endptr, gint * val)
170 {
171   gchar *end;
172   gint64 ret;
173
174   g_return_val_if_fail (ptr != NULL, FALSE);
175   g_return_val_if_fail (val != NULL, FALSE);
176
177   errno = 0;
178   ret = g_ascii_strtoll (ptr, &end, 10);
179   if ((errno == ERANGE && (ret == G_MAXINT64 || ret == G_MININT64))
180       || (errno != 0 && ret == 0)) {
181     GST_WARNING ("%s", g_strerror (errno));
182     return FALSE;
183   }
184
185   if (ret > G_MAXINT || ret < G_MININT) {
186     GST_WARNING ("%s", g_strerror (ERANGE));
187     return FALSE;
188   }
189
190   if (endptr)
191     *endptr = end;
192
193   *val = (gint) ret;
194
195   return end != ptr;
196 }
197
198 static gboolean
199 int64_from_string (gchar * ptr, gchar ** endptr, gint64 * val)
200 {
201   gchar *end;
202   gint64 ret;
203
204   g_return_val_if_fail (ptr != NULL, FALSE);
205   g_return_val_if_fail (val != NULL, FALSE);
206
207   errno = 0;
208   ret = g_ascii_strtoll (ptr, &end, 10);
209   if ((errno == ERANGE && (ret == G_MAXINT64 || ret == G_MININT64))
210       || (errno != 0 && ret == 0)) {
211     GST_WARNING ("%s", g_strerror (errno));
212     return FALSE;
213   }
214
215   if (endptr)
216     *endptr = end;
217
218   *val = ret;
219
220   return end != ptr;
221 }
222
223 static gboolean
224 double_from_string (gchar * ptr, gchar ** endptr, gdouble * val)
225 {
226   gchar *end;
227   gdouble ret;
228
229   g_return_val_if_fail (ptr != NULL, FALSE);
230   g_return_val_if_fail (val != NULL, FALSE);
231
232   errno = 0;
233   ret = g_ascii_strtod (ptr, &end);
234   if ((errno == ERANGE && (ret == HUGE_VAL || ret == -HUGE_VAL))
235       || (errno != 0 && ret == 0)) {
236     GST_WARNING ("%s", g_strerror (errno));
237     return FALSE;
238   }
239
240   if (!isfinite (ret)) {
241     GST_WARNING ("%s", g_strerror (ERANGE));
242     return FALSE;
243   }
244
245   if (endptr)
246     *endptr = end;
247
248   *val = (gdouble) ret;
249
250   return end != ptr;
251 }
252
253 static gboolean
254 parse_attributes (gchar ** ptr, gchar ** a, gchar ** v)
255 {
256   gchar *end = NULL, *p, *ve;
257
258   g_return_val_if_fail (ptr != NULL, FALSE);
259   g_return_val_if_fail (*ptr != NULL, FALSE);
260   g_return_val_if_fail (a != NULL, FALSE);
261   g_return_val_if_fail (v != NULL, FALSE);
262
263   /* [attribute=value,]* */
264
265   *a = *ptr;
266   end = p = g_utf8_strchr (*ptr, -1, ',');
267   if (end) {
268     gchar *q = g_utf8_strchr (*ptr, -1, '"');
269     if (q && q < end) {
270       /* special case, such as CODECS="avc1.77.30, mp4a.40.2" */
271       q = g_utf8_next_char (q);
272       if (q) {
273         q = g_utf8_strchr (q, -1, '"');
274       }
275       if (q) {
276         end = p = g_utf8_strchr (q, -1, ',');
277       }
278     }
279   }
280   if (end) {
281     do {
282       end = g_utf8_next_char (end);
283     } while (end && *end == ' ');
284     *p = '\0';
285   }
286
287   *v = p = g_utf8_strchr (*ptr, -1, '=');
288   if (*v) {
289     *p = '\0';
290     *v = g_utf8_next_char (*v);
291     if (**v == '"') {
292       ve = g_utf8_next_char (*v);
293       if (ve) {
294         ve = g_utf8_strchr (ve, -1, '"');
295       }
296       if (ve) {
297         *v = g_utf8_next_char (*v);
298         *ve = '\0';
299       } else {
300         GST_WARNING ("Cannot remove quotation marks from %s", *a);
301       }
302     }
303   } else {
304     GST_WARNING ("missing = after attribute");
305     return FALSE;
306   }
307
308   *ptr = end;
309   return TRUE;
310 }
311
312 GstHLSMediaPlaylist *
313 gst_hls_media_playlist_new (const gchar * uri, const gchar * base_uri)
314 {
315   GstHLSMediaPlaylist *m3u8;
316
317   m3u8 = g_new0 (GstHLSMediaPlaylist, 1);
318
319   m3u8->uri = g_strdup (uri);
320   m3u8->base_uri = g_strdup (base_uri);
321
322   m3u8->version = 1;
323   m3u8->type = GST_HLS_PLAYLIST_TYPE_UNDEFINED;
324   m3u8->targetduration = GST_CLOCK_TIME_NONE;
325   m3u8->media_sequence = 0;
326   m3u8->discont_sequence = 0;
327   m3u8->endlist = FALSE;
328   m3u8->i_frame = FALSE;
329   m3u8->allowcache = TRUE;
330
331   m3u8->ext_x_key_present = FALSE;
332   m3u8->ext_x_pdt_present = FALSE;
333
334   m3u8->segments =
335       g_ptr_array_new_full (16, (GDestroyNotify) gst_m3u8_media_segment_unref);
336
337   m3u8->duration = 0;
338
339   g_mutex_init (&m3u8->lock);
340   m3u8->ref_count = 1;
341
342   return m3u8;
343 }
344
345 void
346 gst_hls_media_playlist_dump (GstHLSMediaPlaylist * self)
347 {
348 #ifndef GST_DISABLE_GST_DEBUG
349   guint idx;
350   gchar *datestring;
351
352   GST_DEBUG ("uri              : %s", self->uri);
353   GST_DEBUG ("base_uri         : %s", self->base_uri);
354
355   GST_DEBUG ("version          : %d", self->version);
356
357   GST_DEBUG ("targetduration   : %" GST_TIME_FORMAT,
358       GST_TIME_ARGS (self->targetduration));
359   GST_DEBUG ("media_sequence   : %" G_GINT64_FORMAT, self->media_sequence);
360   GST_DEBUG ("discont_sequence : %" G_GINT64_FORMAT, self->discont_sequence);
361
362   GST_DEBUG ("endlist          : %s",
363       self->endlist ? "present" : "NOT present");
364   GST_DEBUG ("i_frame          : %s", self->i_frame ? "YES" : "NO");
365
366   GST_DEBUG ("EXT-X-KEY        : %s",
367       self->ext_x_key_present ? "present" : "NOT present");
368   GST_DEBUG ("EXT-X-PROGRAM-DATE-TIME : %s",
369       self->ext_x_pdt_present ? "present" : "NOT present");
370
371   GST_DEBUG ("duration         : %" GST_TIME_FORMAT,
372       GST_TIME_ARGS (self->duration));
373
374   GST_DEBUG ("Segments : %d", self->segments->len);
375   for (idx = 0; idx < self->segments->len; idx++) {
376     GstM3U8MediaSegment *segment = g_ptr_array_index (self->segments, idx);
377
378     GST_DEBUG ("  sequence:%" G_GINT64_FORMAT " discont_sequence:%"
379         G_GINT64_FORMAT, segment->sequence, segment->discont_sequence);
380     GST_DEBUG ("    stream_time : %" GST_STIME_FORMAT,
381         GST_STIME_ARGS (segment->stream_time));
382     GST_DEBUG ("    duration    :  %" GST_TIME_FORMAT,
383         GST_TIME_ARGS (segment->duration));
384     if (segment->title)
385       GST_DEBUG ("    title       : %s", segment->title);
386     GST_DEBUG ("    discont     : %s", segment->discont ? "YES" : "NO");
387     if (segment->datetime) {
388       datestring = g_date_time_format_iso8601 (segment->datetime);
389       GST_DEBUG ("    date/time    : %s", datestring);
390       g_free (datestring);
391     }
392     GST_DEBUG ("    uri         : %s %" G_GUINT64_FORMAT " %" G_GINT64_FORMAT,
393         segment->uri, segment->offset, segment->size);
394   }
395 #endif
396 }
397
398 static void
399 gst_hls_media_playlist_postprocess_pdt (GstHLSMediaPlaylist * self)
400 {
401   gint idx, len = self->segments->len;
402   gint first_pdt = -1;
403   GstM3U8MediaSegment *previous = NULL;
404   GstM3U8MediaSegment *segment = NULL;
405
406   /* Iterate forward, and make sure datetimes are coherent */
407   for (idx = 0; idx < len; idx++, previous = segment) {
408     segment = g_ptr_array_index (self->segments, idx);
409
410 #define ABSDIFF(a,b) ((a) > (b) ? (a) - (b) : (b) - (a))
411
412     if (segment->datetime) {
413       if (first_pdt == -1)
414         first_pdt = idx;
415       if (!segment->discont && previous && previous->datetime) {
416         GstClockTimeDiff diff = g_date_time_difference (segment->datetime,
417             previous->datetime) * GST_USECOND;
418         if (ABSDIFF (diff, previous->duration) > 500 * GST_MSECOND) {
419           GST_LOG ("PDT diff %" GST_STIME_FORMAT " previous duration %"
420               GST_TIME_FORMAT, GST_STIME_ARGS (diff),
421               GST_TIME_ARGS (previous->duration));
422           g_date_time_unref (segment->datetime);
423           segment->datetime =
424               g_date_time_add (previous->datetime,
425               previous->duration / GST_USECOND);
426         }
427       }
428     } else {
429       if (segment->discont) {
430         GST_WARNING ("Discont segment doesn't have a PDT !");
431       } else if (previous) {
432         if (previous->datetime) {
433           segment->datetime =
434               g_date_time_add (previous->datetime,
435               previous->duration / GST_USECOND);
436           GST_LOG
437               ("Generated new PDT based on previous segment PDT and duration");
438         } else {
439           GST_LOG ("Missing PDT, but can't generate it from previous one");
440         }
441       }
442     }
443   }
444
445   if (first_pdt != -1 && first_pdt != 0) {
446     GST_LOG ("Scanning backwards from %d", first_pdt);
447     previous = g_ptr_array_index (self->segments, first_pdt);
448     for (idx = first_pdt - 1; idx >= 0; idx = idx - 1) {
449       GST_LOG ("%d", idx);
450       segment = g_ptr_array_index (self->segments, idx);
451       if (!segment->datetime && previous->datetime) {
452         segment->datetime =
453             g_date_time_add (previous->datetime,
454             -(segment->duration / GST_USECOND));
455       }
456       previous = segment;
457     }
458   }
459 }
460
461 /* Parse and create a new GstHLSMediaPlaylist */
462 GstHLSMediaPlaylist *
463 gst_hls_media_playlist_parse (gchar * data, const gchar * uri,
464     const gchar * base_uri)
465 {
466   gchar *input_data = data;
467   GstHLSMediaPlaylist *self;
468   gint val;
469   GstClockTime duration;
470   gchar *title, *end;
471   gboolean discontinuity = FALSE;
472   gchar *current_key = NULL;
473   gboolean have_iv = FALSE;
474   guint8 iv[16] = { 0, };
475   gint64 size = -1, offset = -1;
476   gint64 mediasequence = 0;
477   gint64 dsn = 0;
478   GDateTime *date_time = NULL;
479   GstM3U8InitFile *last_init_file = NULL;
480   GstM3U8MediaSegment *previous = NULL;
481
482   GST_LOG ("uri: %s", uri);
483   GST_LOG ("base_uri: %s", base_uri);
484   GST_TRACE ("data:\n%s", data);
485
486   if (!g_str_has_prefix (data, "#EXTM3U")) {
487     GST_WARNING ("Data doesn't start with #EXTM3U");
488     g_free (data);
489     return NULL;
490   }
491
492   if (g_strrstr (data, "\n#EXT-X-STREAM-INF:") != NULL) {
493     GST_WARNING ("Not a media playlist, but a master playlist!");
494     g_free (data);
495     return NULL;
496   }
497
498   self = gst_hls_media_playlist_new (uri, base_uri);
499
500   /* Store a copy of the data */
501   self->last_data = g_strdup (data);
502
503   duration = 0;
504   title = NULL;
505   data += 7;
506   while (TRUE) {
507     gchar *r;
508
509     end = g_utf8_strchr (data, -1, '\n');
510     if (end)
511       *end = '\0';
512
513     r = g_utf8_strchr (data, -1, '\r');
514     if (r)
515       *r = '\0';
516
517     if (data[0] != '#' && data[0] != '\0') {
518       if (duration <= 0) {
519         GST_LOG ("%s: got line without EXTINF, dropping", data);
520         goto next_line;
521       }
522
523       data = uri_join (self->base_uri ? self->base_uri : self->uri, data);
524
525       /* Let's check this is not a bogus duplicate entry */
526       if (previous && !discontinuity && !g_strcmp0 (data, previous->uri)
527           && (offset == -1 || previous->offset == offset)) {
528         GST_WARNING ("Dropping duplicate segment entry");
529         g_free (data);
530         data = NULL;
531         date_time = NULL;
532         duration = 0;
533         g_free (title);
534         title = NULL;
535         discontinuity = FALSE;
536         size = offset = -1;
537         goto next_line;
538       }
539       if (data != NULL) {
540         GstM3U8MediaSegment *file;
541         /* We can finally create the segment */
542         /* The disconinuity sequence number is only stored if the header has
543          * EXT-X-DISCONTINUITY-SEQUENCE present.  */
544         file =
545             gst_m3u8_media_segment_new (data, title, duration, mediasequence++,
546             dsn);
547         self->duration += duration;
548
549         /* set encryption params */
550         file->key = current_key ? g_strdup (current_key) : NULL;
551         if (file->key) {
552           if (have_iv) {
553             memcpy (file->iv, iv, sizeof (iv));
554           } else {
555             guint8 *iv = file->iv + 12;
556             GST_WRITE_UINT32_BE (iv, file->sequence);
557           }
558         }
559
560         if (size != -1) {
561           file->size = size;
562           if (offset != -1) {
563             file->offset = offset;
564           } else {
565             file->offset = 0;
566           }
567         } else {
568           file->size = -1;
569           file->offset = 0;
570         }
571
572         file->datetime = date_time;
573         file->discont = discontinuity;
574         if (last_init_file)
575           file->init_file = gst_m3u8_init_file_ref (last_init_file);
576
577         date_time = NULL;       /* Ownership was passed to the segment */
578         duration = 0;
579         title = NULL;           /* Ownership was passed to the segment */
580         discontinuity = FALSE;
581         size = offset = -1;
582         g_ptr_array_add (self->segments, file);
583         previous = file;
584       }
585
586     } else if (g_str_has_prefix (data, "#EXTINF:")) {
587       gdouble fval;
588       if (!double_from_string (data + 8, &data, &fval)) {
589         GST_WARNING ("Can't read EXTINF duration");
590         goto next_line;
591       }
592       duration = fval * (gdouble) GST_SECOND;
593       if (self->targetduration > 0 && duration > self->targetduration) {
594         GST_DEBUG ("EXTINF duration (%" GST_TIME_FORMAT
595             ") > TARGETDURATION (%" GST_TIME_FORMAT ")",
596             GST_TIME_ARGS (duration), GST_TIME_ARGS (self->targetduration));
597       }
598       if (!data || *data != ',')
599         goto next_line;
600       data = g_utf8_next_char (data);
601       if (data != end) {
602         g_free (title);
603         title = g_strdup (data);
604       }
605     } else if (g_str_has_prefix (data, "#EXT-X-")) {
606       gchar *data_ext_x = data + 7;
607
608       /* All these entries start with #EXT-X- */
609       if (g_str_has_prefix (data_ext_x, "ENDLIST")) {
610         self->endlist = TRUE;
611       } else if (g_str_has_prefix (data_ext_x, "VERSION:")) {
612         if (int_from_string (data + 15, &data, &val))
613           self->version = val;
614       } else if (g_str_has_prefix (data_ext_x, "PLAYLIST-TYPE:")) {
615         if (!g_strcmp0 (data + 21, "VOD"))
616           self->type = GST_HLS_PLAYLIST_TYPE_VOD;
617         else if (!g_strcmp0 (data + 21, "EVENT"))
618           self->type = GST_HLS_PLAYLIST_TYPE_EVENT;
619         else
620           GST_WARNING ("Unknown playlist type '%s'", data + 21);
621       } else if (g_str_has_prefix (data_ext_x, "TARGETDURATION:")) {
622         if (int_from_string (data + 22, &data, &val))
623           self->targetduration = val * GST_SECOND;
624       } else if (g_str_has_prefix (data_ext_x, "MEDIA-SEQUENCE:")) {
625         if (int_from_string (data + 22, &data, &val))
626           self->media_sequence = mediasequence = val;
627       } else if (g_str_has_prefix (data_ext_x, "DISCONTINUITY-SEQUENCE:")) {
628         if (int_from_string (data + 30, &data, &val)
629             && val != self->discont_sequence) {
630           dsn = self->discont_sequence = val;
631           self->has_ext_x_dsn = TRUE;
632         }
633       } else if (g_str_has_prefix (data_ext_x, "DISCONTINUITY")) {
634         dsn++;
635         discontinuity = TRUE;
636       } else if (g_str_has_prefix (data_ext_x, "PROGRAM-DATE-TIME:")) {
637         date_time = g_date_time_new_from_iso8601 (data + 25, NULL);
638         if (date_time)
639           self->ext_x_pdt_present = TRUE;
640       } else if (g_str_has_prefix (data_ext_x, "ALLOW-CACHE:")) {
641         self->allowcache = g_ascii_strcasecmp (data + 19, "YES") == 0;
642       } else if (g_str_has_prefix (data_ext_x, "KEY:")) {
643         gchar *v, *a;
644
645         data = data + 11;
646
647         /* IV and KEY are only valid until the next #EXT-X-KEY */
648         have_iv = FALSE;
649         g_free (current_key);
650         current_key = NULL;
651         while (data && parse_attributes (&data, &a, &v)) {
652           if (g_str_equal (a, "URI")) {
653             current_key =
654                 uri_join (self->base_uri ? self->base_uri : self->uri, v);
655           } else if (g_str_equal (a, "IV")) {
656             gchar *ivp = v;
657             gint i;
658
659             if (strlen (ivp) < 32 + 2 || (!g_str_has_prefix (ivp, "0x")
660                     && !g_str_has_prefix (ivp, "0X"))) {
661               GST_WARNING ("Can't read IV");
662               continue;
663             }
664
665             ivp += 2;
666             for (i = 0; i < 16; i++) {
667               gint h, l;
668
669               h = g_ascii_xdigit_value (*ivp);
670               ivp++;
671               l = g_ascii_xdigit_value (*ivp);
672               ivp++;
673               if (h == -1 || l == -1) {
674                 i = -1;
675                 break;
676               }
677               iv[i] = (h << 4) | l;
678             }
679
680             if (i == -1) {
681               GST_WARNING ("Can't read IV");
682               continue;
683             }
684             have_iv = TRUE;
685           } else if (g_str_equal (a, "METHOD")) {
686             if (!g_str_equal (v, "AES-128") && !g_str_equal (v, "NONE")) {
687               GST_WARNING ("Encryption method %s not supported", v);
688               continue;
689             }
690             self->ext_x_key_present = TRUE;
691           }
692         }
693       } else if (g_str_has_prefix (data_ext_x, "BYTERANGE:")) {
694         gchar *v = data + 17;
695
696         size = -1;
697         offset = -1;
698         if (int64_from_string (v, &v, &size)) {
699           if (*v == '@' && !int64_from_string (v + 1, &v, &offset))
700             goto next_line;
701           /*  */
702           if (offset == -1 && previous)
703             offset = previous->offset + previous->size;
704         } else {
705           goto next_line;
706         }
707       } else if (g_str_has_prefix (data_ext_x, "MAP:")) {
708         gchar *v, *a, *header_uri = NULL;
709
710         data = data + 11;
711
712         while (data != NULL && parse_attributes (&data, &a, &v)) {
713           if (strcmp (a, "URI") == 0) {
714             header_uri =
715                 uri_join (self->base_uri ? self->base_uri : self->uri, v);
716           } else if (strcmp (a, "BYTERANGE") == 0) {
717             if (int64_from_string (v, &v, &size)) {
718               if (*v == '@' && !int64_from_string (v + 1, &v, &offset)) {
719                 g_free (header_uri);
720                 goto next_line;
721               }
722             } else {
723               g_free (header_uri);
724               goto next_line;
725             }
726           }
727         }
728
729         if (header_uri) {
730           GstM3U8InitFile *init_file;
731           init_file = gst_m3u8_init_file_new (header_uri);
732
733           if (size != -1) {
734             init_file->size = size;
735             if (offset != -1)
736               init_file->offset = offset;
737             else
738               init_file->offset = 0;
739           } else {
740             init_file->size = -1;
741             init_file->offset = 0;
742           }
743           if (last_init_file)
744             gst_m3u8_init_file_unref (last_init_file);
745
746           last_init_file = init_file;
747         }
748       } else {
749         GST_LOG ("Ignored line: %s", data);
750       }
751     } else if (data[0]) {
752       /* Log non-empty lines */
753       GST_LOG ("Ignored line: `%s`", data);
754     }
755
756   next_line:
757     if (!end)
758       break;
759     data = g_utf8_next_char (end);      /* skip \n */
760   }
761
762   /* Clean up date that wasn't freed / handed to a segment */
763   g_free (current_key);
764   current_key = NULL;
765   if (date_time)
766     g_date_time_unref (date_time);
767   g_free (title);
768
769   g_free (input_data);
770
771   if (last_init_file)
772     gst_m3u8_init_file_unref (last_init_file);
773
774   if (self->segments->len == 0) {
775     GST_ERROR ("Invalid media playlist, it does not contain any media files");
776     gst_hls_media_playlist_unref (self);
777     return NULL;
778   }
779
780   /* Now go over the parsed data to ensure MSN and/or PDT are set */
781   if (self->ext_x_pdt_present)
782     gst_hls_media_playlist_postprocess_pdt (self);
783
784   /* If we are not live, the stream time can be directly applied */
785   if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (self)) {
786     gint iter, len = self->segments->len;
787     GstClockTimeDiff stream_time = 0;
788
789     for (iter = 0; iter < len; iter++) {
790       GstM3U8MediaSegment *segment = g_ptr_array_index (self->segments, iter);
791       segment->stream_time = stream_time;
792       stream_time += segment->duration;
793     }
794   }
795
796   gst_hls_media_playlist_dump (self);
797   return self;
798 }
799
800 /* Returns TRUE if the m3u8 as the same data as playlist_data  */
801 gboolean
802 gst_hls_media_playlist_has_same_data (GstHLSMediaPlaylist * self,
803     gchar * playlist_data)
804 {
805   gboolean ret;
806
807   GST_HLS_MEDIA_PLAYLIST_LOCK (self);
808
809   ret = self->last_data && g_str_equal (self->last_data, playlist_data);
810
811   GST_HLS_MEDIA_PLAYLIST_UNLOCK (self);
812
813   return ret;
814 }
815
816 GstM3U8MediaSegment *
817 gst_hls_media_playlist_seek (GstHLSMediaPlaylist * playlist, gboolean forward,
818     GstSeekFlags flags, GstClockTimeDiff ts)
819 {
820   gboolean snap_nearest =
821       (flags & GST_SEEK_FLAG_SNAP_NEAREST) == GST_SEEK_FLAG_SNAP_NEAREST;
822   gboolean snap_after =
823       (flags & GST_SEEK_FLAG_SNAP_AFTER) == GST_SEEK_FLAG_SNAP_AFTER;
824   guint idx;
825   GstM3U8MediaSegment *res = NULL;
826
827   GST_DEBUG ("ts:%" GST_STIME_FORMAT " forward:%d playlist uri: %s",
828       GST_STIME_ARGS (ts), forward, playlist->uri);
829
830   for (idx = 0; idx < playlist->segments->len; idx++) {
831     GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
832
833     if ((forward & snap_after) || snap_nearest) {
834       if (cand->stream_time >= ts ||
835           (snap_nearest && (ts - cand->stream_time < cand->duration / 2))) {
836         res = cand;
837         goto out;
838       }
839     } else if (!forward && snap_after) {
840       GstClockTime next_pos = cand->stream_time + cand->duration;
841
842       if (next_pos <= ts && ts < next_pos + cand->duration) {
843         res = cand;
844         goto out;
845       }
846     } else if ((cand->stream_time <= ts || idx == 0)
847         && ts < cand->stream_time + cand->duration) {
848       res = cand;
849       goto out;
850     }
851   }
852
853 out:
854   if (res) {
855     GST_DEBUG ("Returning segment sn:%" G_GINT64_FORMAT " stream_time:%"
856         GST_STIME_FORMAT " duration:%" GST_TIME_FORMAT, res->sequence,
857         GST_STIME_ARGS (res->stream_time), GST_TIME_ARGS (res->duration));
858     gst_m3u8_media_segment_ref (res);
859   } else {
860     GST_DEBUG ("Couldn't find a match");
861   }
862
863   return res;
864 }
865
866 /* Recalculate all segment DSN based on the DSN of the provided anchor segment
867  * (which must belong to the playlist). */
868 static void
869 gst_hls_media_playlist_recalculate_dsn (GstHLSMediaPlaylist * playlist,
870     GstM3U8MediaSegment * anchor)
871 {
872   guint idx;
873   gint iter;
874   GstM3U8MediaSegment *cand, *prev;
875
876   if (!g_ptr_array_find (playlist->segments, anchor, &idx)) {
877     g_assert (FALSE);
878   }
879
880   g_assert (idx != -1);
881
882   GST_DEBUG ("Re-calculating DSN from segment #%d %" G_GINT64_FORMAT,
883       idx, anchor->discont_sequence);
884
885   /* Forward */
886   prev = anchor;
887   for (iter = idx + 1; iter < playlist->segments->len; iter++) {
888     cand = g_ptr_array_index (playlist->segments, iter);
889     if (cand->discont)
890       cand->discont_sequence = prev->discont_sequence + 1;
891     else
892       cand->discont_sequence = prev->discont_sequence;
893     prev = cand;
894   }
895
896   /* Backward */
897   prev = anchor;
898   for (iter = idx - 1; iter >= 0; iter--) {
899     cand = g_ptr_array_index (playlist->segments, iter);
900     if (prev->discont)
901       cand->discont_sequence = prev->discont_sequence - 1;
902     else
903       cand->discont_sequence = prev->discont_sequence;
904     prev = cand;
905   }
906 }
907
908
909 /* Recalculate all segment stream time based on the stream time of the provided
910  * anchor segment (which must belong to the playlist) */
911 void
912 gst_hls_media_playlist_recalculate_stream_time (GstHLSMediaPlaylist * playlist,
913     GstM3U8MediaSegment * anchor)
914 {
915   guint idx;
916   gint iter;
917   GstM3U8MediaSegment *cand, *prev;
918
919   if (!g_ptr_array_find (playlist->segments, anchor, &idx)) {
920     g_assert (FALSE);
921   }
922
923   g_assert (GST_CLOCK_TIME_IS_VALID (anchor->stream_time));
924   g_assert (idx != -1);
925
926   GST_DEBUG ("Re-calculating stream times from segment #%d %" GST_TIME_FORMAT,
927       idx, GST_TIME_ARGS (anchor->stream_time));
928
929   /* Forward */
930   prev = anchor;
931   for (iter = idx + 1; iter < playlist->segments->len; iter++) {
932     cand = g_ptr_array_index (playlist->segments, iter);
933     cand->stream_time = prev->stream_time + prev->duration;
934     GST_DEBUG ("Forward iter %d %" GST_STIME_FORMAT, iter,
935         GST_STIME_ARGS (cand->stream_time));
936     prev = cand;
937   }
938
939   /* Backward */
940   prev = anchor;
941   for (iter = idx - 1; iter >= 0; iter--) {
942     cand = g_ptr_array_index (playlist->segments, iter);
943     cand->stream_time = prev->stream_time - cand->duration;
944     GST_DEBUG ("Backward iter %d %" GST_STIME_FORMAT, iter,
945         GST_STIME_ARGS (cand->stream_time));
946     prev = cand;
947   }
948 }
949
950 /* If a segment with the same URI, size, offset, SN and DSN is present in the
951  * playlist, returns that one */
952 static GstM3U8MediaSegment *
953 gst_hls_media_playlist_find_by_uri (GstHLSMediaPlaylist * playlist,
954     GstM3U8MediaSegment * segment)
955 {
956   guint idx;
957
958   for (idx = 0; idx < playlist->segments->len; idx++) {
959     GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
960
961     if (cand->sequence == segment->sequence &&
962         cand->discont_sequence == segment->discont_sequence &&
963         cand->offset == segment->offset && cand->size == segment->size &&
964         !g_strcmp0 (cand->uri, segment->uri)) {
965       return cand;
966     }
967   }
968
969   return NULL;
970 }
971
972 /* Find the equivalent segment in the given playlist.
973  *
974  * The returned segment does *NOT* have increased reference !
975  *
976  * If the provided segment is just before the first entry of the playlist, it
977  * will be added to the playlist (with a reference) and is_before will be set to
978  * TRUE.
979  */
980 static GstM3U8MediaSegment *
981 find_segment_in_playlist (GstHLSMediaPlaylist * playlist,
982     GstM3U8MediaSegment * segment, gboolean * is_before)
983 {
984   GstM3U8MediaSegment *res = NULL;
985   guint idx;
986
987   *is_before = FALSE;
988
989   /* The easy one. Happens when stream times need to be re-synced in an existing
990    * playlist */
991   if (g_ptr_array_find (playlist->segments, segment, NULL)) {
992     GST_DEBUG ("Present as-is in playlist");
993     return segment;
994   }
995
996   /* If there is an identical segment with the same URI and SN, use that one */
997   res = gst_hls_media_playlist_find_by_uri (playlist, segment);
998   if (res) {
999     GST_DEBUG ("Using same URI/DSN/SN match");
1000     return res;
1001   }
1002
1003   /* Try with PDT */
1004   if (segment->datetime && playlist->ext_x_pdt_present) {
1005 #ifndef GST_DISABLE_GST_DEBUG
1006     gchar *pdtstring = g_date_time_format_iso8601 (segment->datetime);
1007     GST_DEBUG ("Search by datetime for %s", pdtstring);
1008     g_free (pdtstring);
1009 #endif
1010     for (idx = 0; idx < playlist->segments->len; idx++) {
1011       GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1012
1013       if (idx == 0 && cand->datetime) {
1014         /* Special case for segments which are just before the 1st one (within
1015          * 20ms). We add another reference because it now also belongs to the
1016          * current playlist */
1017         GDateTime *seg_end = g_date_time_add (segment->datetime,
1018             segment->duration / GST_USECOND);
1019         GstClockTimeDiff ddiff =
1020             g_date_time_difference (cand->datetime, seg_end) * GST_USECOND;
1021         g_date_time_unref (seg_end);
1022         if (ABS (ddiff) < 20 * GST_MSECOND) {
1023           /* The reference segment ends within 20ms of the first segment, it is just before */
1024           GST_DEBUG ("Reference segment ends within %" GST_STIME_FORMAT
1025               " of first playlist segment, inserting before",
1026               GST_STIME_ARGS (ddiff));
1027           g_ptr_array_insert (playlist->segments, 0,
1028               gst_m3u8_media_segment_ref (segment));
1029           *is_before = TRUE;
1030           return segment;
1031         }
1032         if (ddiff > 0) {
1033           /* If the reference segment is completely before the first segment, bail out */
1034           GST_DEBUG ("Reference segment ends before first segment");
1035           break;
1036         }
1037       }
1038
1039       if (cand->datetime
1040           && g_date_time_difference (cand->datetime, segment->datetime) >= 0) {
1041         GST_DEBUG ("Picking by date time");
1042         return cand;
1043       }
1044     }
1045   }
1046
1047   /* If not live, we can match by stream time */
1048   if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist)) {
1049     GST_DEBUG ("Search by Stream time for %" GST_STIME_FORMAT " duration:%"
1050         GST_TIME_FORMAT, GST_STIME_ARGS (segment->stream_time),
1051         GST_TIME_ARGS (segment->duration));
1052     for (idx = 0; idx < playlist->segments->len; idx++) {
1053       GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1054
1055       /* If the candidate starts at or after the previous stream time */
1056       if (cand->stream_time >= segment->stream_time) {
1057         return cand;
1058       }
1059
1060       /* If the previous end stream time is before the candidate end stream time */
1061       if ((segment->stream_time + segment->duration) <
1062           (cand->stream_time + cand->duration)) {
1063         return cand;
1064       }
1065     }
1066   }
1067
1068   /* Fallback with MSN */
1069   GST_DEBUG ("Search by Media Sequence Number for sn:%" G_GINT64_FORMAT " dsn:%"
1070       G_GINT64_FORMAT, segment->sequence, segment->discont_sequence);
1071   for (idx = 0; idx < playlist->segments->len; idx++) {
1072     GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1073
1074     /* Ignore non-matching DSN if needed */
1075     if ((segment->discont_sequence != cand->discont_sequence)
1076         && playlist->has_ext_x_dsn)
1077       continue;
1078
1079     if (idx == 0 && cand->sequence == segment->sequence + 1) {
1080       /* Special case for segments just before the 1st one. We add another
1081        * reference because it now also belongs to the current playlist */
1082       GST_DEBUG ("reference segment is just before 1st segment, inserting");
1083       g_ptr_array_insert (playlist->segments, 0,
1084           gst_m3u8_media_segment_ref (segment));
1085       *is_before = TRUE;
1086       return segment;
1087     }
1088
1089     if (cand->sequence == segment->sequence) {
1090       return cand;
1091     }
1092   }
1093
1094   return NULL;
1095 }
1096
1097 /* Given a media segment (potentially from another media playlist), find the
1098  * equivalent media segment in this playlist.
1099  *
1100  * This will also recalculate all stream times based on that segment stream
1101  * time (i.e. "sync" the playlist to that previous time).
1102  *
1103  * If an equivalent/identical one is found it is returned with
1104  * the reference count incremented
1105  */
1106 GstM3U8MediaSegment *
1107 gst_hls_media_playlist_sync_to_segment (GstHLSMediaPlaylist * playlist,
1108     GstM3U8MediaSegment * segment)
1109 {
1110   GstM3U8MediaSegment *res = NULL;
1111   gboolean is_before;
1112 #ifndef GST_DISABLE_GST_DEBUG
1113   gchar *pdtstring;
1114 #endif
1115
1116   g_return_val_if_fail (playlist, NULL);
1117   g_return_val_if_fail (segment, NULL);
1118
1119   GST_DEBUG ("Re-syncing to segment %" GST_STIME_FORMAT " duration:%"
1120       GST_TIME_FORMAT " sn:%" G_GINT64_FORMAT "/dsn:%" G_GINT64_FORMAT
1121       " uri:%s in playlist %s", GST_STIME_ARGS (segment->stream_time),
1122       GST_TIME_ARGS (segment->duration), segment->sequence,
1123       segment->discont_sequence, segment->uri, playlist->uri);
1124
1125   res = find_segment_in_playlist (playlist, segment, &is_before);
1126
1127   /* For live playlists we re-calculate all stream times based on the existing
1128    * stream time. Non-live playlists have their stream time calculated at
1129    * parsing time. */
1130   if (res) {
1131     if (!is_before)
1132       gst_m3u8_media_segment_ref (res);
1133     if (res->stream_time == GST_CLOCK_STIME_NONE)
1134       res->stream_time = segment->stream_time;
1135     if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist))
1136       gst_hls_media_playlist_recalculate_stream_time (playlist, res);
1137     /* If the playlist didn't specify a reference discont sequence number, we
1138      * carry over the one from the reference segment */
1139     if (!playlist->has_ext_x_dsn
1140         && res->discont_sequence != segment->discont_sequence) {
1141       res->discont_sequence = segment->discont_sequence;
1142       gst_hls_media_playlist_recalculate_dsn (playlist, res);
1143     }
1144     if (is_before) {
1145       GST_DEBUG ("Dropping segment from before the playlist");
1146       g_ptr_array_remove_index (playlist->segments, 0);
1147       res = NULL;
1148     }
1149   }
1150 #ifndef GST_DISABLE_GST_DEBUG
1151   if (res) {
1152     pdtstring =
1153         res->datetime ? g_date_time_format_iso8601 (res->datetime) : NULL;
1154     GST_DEBUG ("Returning segment sn:%" G_GINT64_FORMAT " dsn:%" G_GINT64_FORMAT
1155         " stream_time:%" GST_STIME_FORMAT " duration:%" GST_TIME_FORMAT
1156         " datetime:%s", res->sequence, res->discont_sequence,
1157         GST_STIME_ARGS (res->stream_time), GST_TIME_ARGS (res->duration),
1158         pdtstring);
1159     g_free (pdtstring);
1160   } else {
1161     GST_DEBUG ("Could not find a match");
1162   }
1163 #endif
1164
1165   return res;
1166 }
1167
1168 GstM3U8MediaSegment *
1169 gst_hls_media_playlist_get_starting_segment (GstHLSMediaPlaylist * self)
1170 {
1171   GstM3U8MediaSegment *res;
1172
1173   GST_DEBUG ("playlist %s", self->uri);
1174
1175   if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (self)) {
1176     /* For non-live, we just grab the first one */
1177     res = g_ptr_array_index (self->segments, 0);
1178   } else {
1179     /* Live playlist */
1180     res =
1181         g_ptr_array_index (self->segments,
1182         MAX ((gint) self->segments->len - GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE -
1183             1, 0));
1184   }
1185
1186   if (res) {
1187     GST_DEBUG ("Using segment sn:%" G_GINT64_FORMAT " dsn:%" G_GINT64_FORMAT,
1188         res->sequence, res->discont_sequence);
1189     gst_m3u8_media_segment_ref (res);
1190   }
1191
1192   return res;
1193 }
1194
1195 /* Calls this to carry over stream time, DSN, ... from one playlist to another.
1196  *
1197  * This should be used when a reference media segment couldn't be matched in the
1198  * playlist, but we still want to carry over the information from a reference
1199  * playlist to an updated one. This can happen with live playlists where the
1200  * reference media segment is no longer present but the playlists intersect */
1201 gboolean
1202 gst_hls_media_playlist_sync_to_playlist (GstHLSMediaPlaylist * playlist,
1203     GstHLSMediaPlaylist * reference)
1204 {
1205   GstM3U8MediaSegment *res = NULL;
1206   GstM3U8MediaSegment *cand = NULL;
1207   guint idx;
1208   gboolean is_before;
1209
1210   g_return_val_if_fail (playlist && reference, FALSE);
1211
1212 retry_without_dsn:
1213   /* The new playlist is supposed to be an update of the reference playlist,
1214    * therefore we will try from the last segment of the reference playlist and
1215    * go backwards */
1216   for (idx = reference->segments->len - 1; idx; idx--) {
1217     cand = g_ptr_array_index (reference->segments, idx);
1218     res = find_segment_in_playlist (playlist, cand, &is_before);
1219     if (res)
1220       break;
1221   }
1222
1223   if (res == NULL) {
1224     if (playlist->has_ext_x_dsn) {
1225       /* There is a possibility that the server doesn't have coherent DSN
1226        * accross variants/renditions. If we reach this section, this means that
1227        * we have already attempted matching by PDT, URI, stream time. The last
1228        * matching would have been by MSN/DSN, therefore try it again without
1229        * taking DSN into account. */
1230       GST_DEBUG ("Retrying matching without taking DSN into account");
1231       playlist->has_ext_x_dsn = FALSE;
1232       goto retry_without_dsn;
1233     }
1234     GST_WARNING ("Could not synchronize media playlists");
1235     return FALSE;
1236   }
1237
1238   /* Carry over reference stream time */
1239   if (res->stream_time == GST_CLOCK_STIME_NONE)
1240     res->stream_time = cand->stream_time;
1241   if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist))
1242     gst_hls_media_playlist_recalculate_stream_time (playlist, res);
1243   /* If the playlist didn't specify a reference discont sequence number, we
1244    * carry over the one from the reference segment */
1245   if (!playlist->has_ext_x_dsn
1246       && res->discont_sequence != cand->discont_sequence) {
1247     res->discont_sequence = cand->discont_sequence;
1248     gst_hls_media_playlist_recalculate_dsn (playlist, res);
1249   }
1250   if (is_before) {
1251     g_ptr_array_remove_index (playlist->segments, 0);
1252   }
1253
1254   return TRUE;
1255 }
1256
1257 gboolean
1258 gst_hls_media_playlist_has_next_fragment (GstHLSMediaPlaylist * m3u8,
1259     GstM3U8MediaSegment * current, gboolean forward)
1260 {
1261   guint idx;
1262   gboolean have_next = TRUE;
1263
1264   g_return_val_if_fail (m3u8 != NULL, FALSE);
1265   g_return_val_if_fail (current != NULL, FALSE);
1266
1267   GST_DEBUG ("playlist %s", m3u8->uri);
1268
1269   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1270
1271   if (!g_ptr_array_find (m3u8->segments, current, &idx))
1272     have_next = FALSE;
1273   else if (idx == 0 && !forward)
1274     have_next = FALSE;
1275   else if (forward && idx == (m3u8->segments->len - 1))
1276     have_next = FALSE;
1277
1278   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1279
1280   GST_DEBUG ("Returning %d", have_next);
1281
1282   return have_next;
1283 }
1284
1285
1286 GstM3U8MediaSegment *
1287 gst_hls_media_playlist_advance_fragment (GstHLSMediaPlaylist * m3u8,
1288     GstM3U8MediaSegment * current, gboolean forward)
1289 {
1290   GstM3U8MediaSegment *file = NULL;
1291   guint idx;
1292
1293   g_return_val_if_fail (m3u8 != NULL, NULL);
1294   g_return_val_if_fail (current != NULL, NULL);
1295
1296   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1297
1298   GST_DEBUG ("playlist %s", m3u8->uri);
1299
1300   if (m3u8->segments->len < 2) {
1301     GST_DEBUG ("Playlist only contains one fragment, can't advance");
1302     goto out;
1303   }
1304
1305   if (!g_ptr_array_find (m3u8->segments, current, &idx)) {
1306     GST_ERROR ("Requested to advance froma fragment not present in playlist");
1307     goto out;
1308   }
1309
1310   if (forward && idx < (m3u8->segments->len - 1)) {
1311     file =
1312         gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1313             idx + 1));
1314   } else if (!forward && idx > 0) {
1315     file =
1316         gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1317             idx - 1));
1318   }
1319
1320   if (file)
1321     GST_DEBUG ("Advanced to segment sn:%" G_GINT64_FORMAT " dsn:%"
1322         G_GINT64_FORMAT, file->sequence, file->discont_sequence);
1323   else
1324     GST_DEBUG ("Could not find %s fragment", forward ? "next" : "previous");
1325
1326 out:
1327   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1328
1329   return file;
1330 }
1331
1332 GstClockTime
1333 gst_hls_media_playlist_get_duration (GstHLSMediaPlaylist * m3u8)
1334 {
1335   GstClockTime duration = GST_CLOCK_TIME_NONE;
1336
1337   g_return_val_if_fail (m3u8 != NULL, GST_CLOCK_TIME_NONE);
1338
1339   GST_DEBUG ("playlist %s", m3u8->uri);
1340
1341   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1342   /* We can only get the duration for on-demand streams */
1343   if (m3u8->endlist) {
1344     if (m3u8->segments->len) {
1345       GstM3U8MediaSegment *first = g_ptr_array_index (m3u8->segments, 0);
1346       GstM3U8MediaSegment *last =
1347           g_ptr_array_index (m3u8->segments, m3u8->segments->len - 1);
1348       duration = last->stream_time + last->duration - first->stream_time;
1349       if (duration != m3u8->duration)
1350         GST_ERROR ("difference in calculated duration ? %" GST_TIME_FORMAT
1351             " vs %" GST_TIME_FORMAT, GST_TIME_ARGS (duration),
1352             GST_TIME_ARGS (m3u8->duration));
1353     }
1354     duration = m3u8->duration;
1355   }
1356   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1357
1358   GST_DEBUG ("duration %" GST_TIME_FORMAT, GST_TIME_ARGS (duration));
1359
1360   return duration;
1361 }
1362
1363 gchar *
1364 gst_hls_media_playlist_get_uri (GstHLSMediaPlaylist * m3u8)
1365 {
1366   gchar *uri;
1367
1368   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1369   uri = g_strdup (m3u8->uri);
1370   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1371
1372   return uri;
1373 }
1374
1375 gboolean
1376 gst_hls_media_playlist_is_live (GstHLSMediaPlaylist * m3u8)
1377 {
1378   gboolean is_live;
1379
1380   g_return_val_if_fail (m3u8 != NULL, FALSE);
1381
1382   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1383   is_live = GST_HLS_MEDIA_PLAYLIST_IS_LIVE (m3u8);
1384   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1385
1386   return is_live;
1387 }
1388
1389 gchar *
1390 uri_join (const gchar * uri1, const gchar * uri2)
1391 {
1392   gchar *uri_copy, *tmp, *ret = NULL;
1393
1394   if (gst_uri_is_valid (uri2))
1395     return g_strdup (uri2);
1396
1397   uri_copy = g_strdup (uri1);
1398   if (uri2[0] != '/') {
1399     /* uri2 is a relative uri2 */
1400     /* look for query params */
1401     tmp = g_utf8_strchr (uri_copy, -1, '?');
1402     if (tmp) {
1403       /* find last / char, ignoring query params */
1404       tmp = g_utf8_strrchr (uri_copy, tmp - uri_copy, '/');
1405     } else {
1406       /* find last / char in URL */
1407       tmp = g_utf8_strrchr (uri_copy, -1, '/');
1408     }
1409     if (!tmp)
1410       goto out;
1411
1412
1413     *tmp = '\0';
1414     ret = g_strdup_printf ("%s/%s", uri_copy, uri2);
1415   } else {
1416     /* uri2 is an absolute uri2 */
1417     char *scheme, *hostname;
1418
1419     scheme = uri_copy;
1420     /* find the : in <scheme>:// */
1421     tmp = g_utf8_strchr (uri_copy, -1, ':');
1422     if (!tmp)
1423       goto out;
1424
1425     *tmp = '\0';
1426
1427     /* skip :// */
1428     hostname = tmp + 3;
1429
1430     tmp = g_utf8_strchr (hostname, -1, '/');
1431     if (tmp)
1432       *tmp = '\0';
1433
1434     ret = g_strdup_printf ("%s://%s%s", scheme, hostname, uri2);
1435   }
1436
1437 out:
1438   g_free (uri_copy);
1439   if (!ret)
1440     GST_WARNING ("Can't build a valid uri from '%s' '%s'", uri1, uri2);
1441
1442   return ret;
1443 }
1444
1445 gboolean
1446 gst_hls_media_playlist_has_lost_sync (GstHLSMediaPlaylist * m3u8,
1447     GstClockTime position)
1448 {
1449   GstM3U8MediaSegment *first;
1450
1451   if (m3u8->segments->len < 1)
1452     return TRUE;
1453   first = g_ptr_array_index (m3u8->segments, 0);
1454
1455   GST_DEBUG ("position %" GST_TIME_FORMAT " first %" GST_STIME_FORMAT
1456       " duration %" GST_STIME_FORMAT, GST_TIME_ARGS (position),
1457       GST_STIME_ARGS (first->stream_time), GST_STIME_ARGS (first->duration));
1458
1459   if (first->stream_time <= 0)
1460     return FALSE;
1461
1462   /* If we're definitely before the first fragment, we lost sync */
1463   if ((position + (first->duration / 2)) < first->stream_time)
1464     return TRUE;
1465   return FALSE;
1466 }
1467
1468 gboolean
1469 gst_hls_media_playlist_get_seek_range (GstHLSMediaPlaylist * m3u8,
1470     gint64 * start, gint64 * stop)
1471 {
1472   GstM3U8MediaSegment *first, *last;
1473   guint min_distance = 1;
1474
1475   g_return_val_if_fail (m3u8 != NULL, FALSE);
1476
1477   if (m3u8->segments->len < 1)
1478     return FALSE;
1479
1480   first = g_ptr_array_index (m3u8->segments, 0);
1481   *start = first->stream_time;
1482
1483   if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (m3u8) && m3u8->segments->len > 1) {
1484     /* min_distance is used to make sure the seek range is never closer than
1485        GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE fragments from the end of a live
1486        playlist - see 6.3.3. "Playing the Playlist file" of the HLS draft */
1487     min_distance =
1488         MIN (GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE, m3u8->segments->len - 1);
1489   }
1490
1491   last = g_ptr_array_index (m3u8->segments, m3u8->segments->len - min_distance);
1492   *stop = last->stream_time + last->duration;
1493
1494   return TRUE;
1495 }
1496
1497 GstClockTime
1498 gst_hls_media_playlist_recommended_buffering_threshold (GstHLSMediaPlaylist *
1499     playlist)
1500 {
1501   if (!playlist->duration || !GST_CLOCK_TIME_IS_VALID (playlist->duration)
1502       || playlist->segments->len == 0)
1503     return GST_CLOCK_TIME_NONE;
1504
1505   /* The recommended buffering threshold is 1.5 average segment duration */
1506   return 3 * (playlist->duration / playlist->segments->len) / 2;
1507 }
1508
1509 GstHLSRenditionStream *
1510 gst_hls_rendition_stream_ref (GstHLSRenditionStream * media)
1511 {
1512   g_assert (media != NULL && media->ref_count > 0);
1513   g_atomic_int_add (&media->ref_count, 1);
1514   return media;
1515 }
1516
1517 void
1518 gst_hls_rendition_stream_unref (GstHLSRenditionStream * media)
1519 {
1520   g_assert (media != NULL && media->ref_count > 0);
1521   if (g_atomic_int_dec_and_test (&media->ref_count)) {
1522     if (media->caps)
1523       gst_caps_unref (media->caps);
1524     g_free (media->group_id);
1525     g_free (media->name);
1526     g_free (media->uri);
1527     g_free (media->lang);
1528     g_free (media);
1529   }
1530 }
1531
1532 static GstHLSRenditionStreamType
1533 gst_m3u8_get_hls_media_type_from_string (const gchar * type_name)
1534 {
1535   if (strcmp (type_name, "AUDIO") == 0)
1536     return GST_HLS_RENDITION_STREAM_TYPE_AUDIO;
1537   if (strcmp (type_name, "VIDEO") == 0)
1538     return GST_HLS_RENDITION_STREAM_TYPE_VIDEO;
1539   if (strcmp (type_name, "SUBTITLES") == 0)
1540     return GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES;
1541   if (strcmp (type_name, "CLOSED_CAPTIONS") == 0)
1542     return GST_HLS_RENDITION_STREAM_TYPE_CLOSED_CAPTIONS;
1543
1544   return GST_HLS_RENDITION_STREAM_TYPE_INVALID;
1545 }
1546
1547 #define GST_HLS_RENDITION_STREAM_TYPE_NAME(mtype) gst_hls_rendition_stream_type_get_name(mtype)
1548 const gchar *
1549 gst_hls_rendition_stream_type_get_name (GstHLSRenditionStreamType mtype)
1550 {
1551   static const gchar *nicks[GST_HLS_N_MEDIA_TYPES] = { "audio", "video",
1552     "subtitle", "closed-captions"
1553   };
1554
1555   if (mtype < 0 || mtype >= GST_HLS_N_MEDIA_TYPES)
1556     return "invalid";
1557
1558   return nicks[mtype];
1559 }
1560
1561 /* returns unquoted copy of string */
1562 static gchar *
1563 gst_m3u8_unquote (const gchar * str)
1564 {
1565   const gchar *start, *end;
1566
1567   start = strchr (str, '"');
1568   if (start == NULL)
1569     return g_strdup (str);
1570   end = strchr (start + 1, '"');
1571   if (end == NULL) {
1572     GST_WARNING ("Broken quoted string [%s] - can't find end quote", str);
1573     return g_strdup (start + 1);
1574   }
1575   return g_strndup (start + 1, (gsize) (end - (start + 1)));
1576 }
1577
1578 static GstHLSRenditionStream *
1579 gst_m3u8_parse_media (gchar * desc, const gchar * base_uri)
1580 {
1581   GstHLSRenditionStream *media;
1582   gchar *a, *v;
1583
1584   media = g_new0 (GstHLSRenditionStream, 1);
1585   media->ref_count = 1;
1586   media->mtype = GST_HLS_RENDITION_STREAM_TYPE_INVALID;
1587
1588   GST_LOG ("parsing %s", desc);
1589   while (desc != NULL && parse_attributes (&desc, &a, &v)) {
1590     if (strcmp (a, "TYPE") == 0) {
1591       media->mtype = gst_m3u8_get_hls_media_type_from_string (v);
1592     } else if (strcmp (a, "GROUP-ID") == 0) {
1593       g_free (media->group_id);
1594       media->group_id = gst_m3u8_unquote (v);
1595     } else if (strcmp (a, "NAME") == 0) {
1596       g_free (media->name);
1597       media->name = gst_m3u8_unquote (v);
1598     } else if (strcmp (a, "URI") == 0) {
1599       gchar *uri;
1600
1601       g_free (media->uri);
1602       uri = gst_m3u8_unquote (v);
1603       media->uri = uri_join (base_uri, uri);
1604       g_free (uri);
1605     } else if (strcmp (a, "LANGUAGE") == 0) {
1606       g_free (media->lang);
1607       media->lang = gst_m3u8_unquote (v);
1608     } else if (strcmp (a, "DEFAULT") == 0) {
1609       media->is_default = g_ascii_strcasecmp (v, "yes") == 0;
1610     } else if (strcmp (a, "FORCED") == 0) {
1611       media->forced = g_ascii_strcasecmp (v, "yes") == 0;
1612     } else if (strcmp (a, "AUTOSELECT") == 0) {
1613       media->autoselect = g_ascii_strcasecmp (v, "yes") == 0;
1614     } else {
1615       /* unhandled: ASSOC-LANGUAGE, INSTREAM-ID, CHARACTERISTICS */
1616       GST_FIXME ("EXT-X-MEDIA: unhandled attribute: %s = %s", a, v);
1617     }
1618   }
1619
1620   if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_INVALID)
1621     goto required_attributes_missing;
1622
1623   if (media->group_id == NULL || media->name == NULL)
1624     goto required_attributes_missing;
1625
1626   if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_CLOSED_CAPTIONS)
1627     goto uri_with_cc;
1628
1629   GST_DEBUG ("media: %s, group '%s', name '%s', uri '%s', %s %s %s, lang=%s",
1630       GST_HLS_RENDITION_STREAM_TYPE_NAME (media->mtype), media->group_id,
1631       media->name, media->uri, media->is_default ? "default" : "-",
1632       media->autoselect ? "autoselect" : "-", media->forced ? "forced" : "-",
1633       media->lang ? media->lang : "??");
1634
1635   return media;
1636
1637 uri_with_cc:
1638   {
1639     GST_WARNING ("closed captions EXT-X-MEDIA should not have URI specified");
1640     goto out_error;
1641   }
1642 required_attributes_missing:
1643   {
1644     GST_WARNING ("EXT-X-MEDIA description is missing required attributes");
1645     goto out_error;
1646   }
1647
1648 out_error:
1649   {
1650     gst_hls_rendition_stream_unref (media);
1651     return NULL;
1652   }
1653 }
1654
1655 GstStreamType
1656 gst_hls_get_stream_type_from_structure (GstStructure * st)
1657 {
1658   const gchar *name = gst_structure_get_name (st);
1659
1660   if (g_str_has_prefix (name, "audio/"))
1661     return GST_STREAM_TYPE_AUDIO;
1662
1663   if (g_str_has_prefix (name, "video/"))
1664     return GST_STREAM_TYPE_VIDEO;
1665
1666   if (g_str_has_prefix (name, "application/x-subtitle"))
1667     return GST_STREAM_TYPE_TEXT;
1668
1669   return 0;
1670 }
1671
1672 GstStreamType
1673 gst_hls_get_stream_type_from_caps (GstCaps * caps)
1674 {
1675   GstStreamType ret = 0;
1676   guint i, nb;
1677   nb = gst_caps_get_size (caps);
1678   for (i = 0; i < nb; i++) {
1679     GstStructure *cand = gst_caps_get_structure (caps, i);
1680
1681     ret |= gst_hls_get_stream_type_from_structure (cand);
1682   }
1683
1684   return ret;
1685 }
1686
1687 static GstHLSVariantStream *
1688 gst_hls_variant_stream_new (void)
1689 {
1690   GstHLSVariantStream *stream;
1691
1692   stream = g_new0 (GstHLSVariantStream, 1);
1693   stream->refcount = 1;
1694   stream->codecs_stream_type = 0;
1695   return stream;
1696 }
1697
1698 GstHLSVariantStream *
1699 hls_variant_stream_ref (GstHLSVariantStream * stream)
1700 {
1701   g_atomic_int_inc (&stream->refcount);
1702   return stream;
1703 }
1704
1705 void
1706 hls_variant_stream_unref (GstHLSVariantStream * stream)
1707 {
1708   if (g_atomic_int_dec_and_test (&stream->refcount)) {
1709     gint i;
1710
1711     g_free (stream->name);
1712     g_free (stream->uri);
1713     g_free (stream->codecs);
1714     if (stream->caps)
1715       gst_caps_unref (stream->caps);
1716     for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
1717       g_free (stream->media_groups[i]);
1718     }
1719     g_list_free_full (stream->fallback, g_free);
1720     g_free (stream);
1721   }
1722 }
1723
1724 static GstHLSVariantStream *
1725 gst_hls_variant_parse (gchar * data, const gchar * base_uri)
1726 {
1727   GstHLSVariantStream *stream;
1728   gchar *v, *a;
1729
1730   stream = gst_hls_variant_stream_new ();
1731   stream->iframe = g_str_has_prefix (data, "#EXT-X-I-FRAME-STREAM-INF:");
1732   data += stream->iframe ? 26 : 18;
1733
1734   while (data && parse_attributes (&data, &a, &v)) {
1735     if (g_str_equal (a, "BANDWIDTH")) {
1736       if (!stream->bandwidth) {
1737         if (!int_from_string (v, NULL, &stream->bandwidth))
1738           GST_WARNING ("Error while reading BANDWIDTH");
1739       }
1740     } else if (g_str_equal (a, "AVERAGE-BANDWIDTH")) {
1741       GST_DEBUG
1742           ("AVERAGE-BANDWIDTH attribute available. Using it as stream bandwidth");
1743       if (!int_from_string (v, NULL, &stream->bandwidth))
1744         GST_WARNING ("Error while reading AVERAGE-BANDWIDTH");
1745     } else if (g_str_equal (a, "PROGRAM-ID")) {
1746       if (!int_from_string (v, NULL, &stream->program_id))
1747         GST_WARNING ("Error while reading PROGRAM-ID");
1748     } else if (g_str_equal (a, "CODECS")) {
1749       g_free (stream->codecs);
1750       stream->codecs = g_strdup (v);
1751       stream->caps = gst_codec_utils_caps_from_mime_codec (stream->codecs);
1752       stream->codecs_stream_type =
1753           gst_hls_get_stream_type_from_caps (stream->caps);
1754     } else if (g_str_equal (a, "RESOLUTION")) {
1755       if (!int_from_string (v, &v, &stream->width))
1756         GST_WARNING ("Error while reading RESOLUTION width");
1757       if (!v || *v != 'x') {
1758         GST_WARNING ("Missing height");
1759       } else {
1760         v = g_utf8_next_char (v);
1761         if (!int_from_string (v, NULL, &stream->height))
1762           GST_WARNING ("Error while reading RESOLUTION height");
1763       }
1764     } else if (stream->iframe && g_str_equal (a, "URI")) {
1765       stream->uri = uri_join (base_uri, v);
1766     } else if (g_str_equal (a, "AUDIO")) {
1767       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_AUDIO]);
1768       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_AUDIO] =
1769           gst_m3u8_unquote (v);
1770     } else if (g_str_equal (a, "SUBTITLES")) {
1771       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES]);
1772       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES] =
1773           gst_m3u8_unquote (v);
1774     } else if (g_str_equal (a, "VIDEO")) {
1775       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_VIDEO]);
1776       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_VIDEO] =
1777           gst_m3u8_unquote (v);
1778     } else if (g_str_equal (a, "CLOSED-CAPTIONS")) {
1779       /* closed captions will be embedded inside the video stream, ignore */
1780     }
1781   }
1782
1783   return stream;
1784 }
1785
1786 static gchar *
1787 generate_variant_stream_name (gchar * uri, gint bandwidth)
1788 {
1789   gchar *checksum = g_compute_checksum_for_string (G_CHECKSUM_SHA1, uri, -1);
1790   gchar *res = g_strdup_printf ("variant-%dbps-%s", bandwidth, checksum);
1791
1792   g_free (checksum);
1793   return res;
1794 }
1795
1796 static GstHLSVariantStream *
1797 find_variant_stream_by_name (GList * list, const gchar * name)
1798 {
1799   for (; list != NULL; list = list->next) {
1800     GstHLSVariantStream *variant_stream = list->data;
1801
1802     if (variant_stream->name != NULL && !strcmp (variant_stream->name, name))
1803       return variant_stream;
1804   }
1805   return NULL;
1806 }
1807
1808 static GstHLSVariantStream *
1809 find_variant_stream_by_uri (GList * list, const gchar * uri)
1810 {
1811   for (; list != NULL; list = list->next) {
1812     GstHLSVariantStream *variant_stream = list->data;
1813
1814     if (variant_stream->uri != NULL && !strcmp (variant_stream->uri, uri))
1815       return variant_stream;
1816   }
1817   return NULL;
1818 }
1819
1820 static GstHLSVariantStream *
1821 find_variant_stream_for_fallback (GList * list, GstHLSVariantStream * fallback)
1822 {
1823   for (; list != NULL; list = list->next) {
1824     GstHLSVariantStream *variant_stream = list->data;
1825
1826     if (variant_stream->bandwidth == fallback->bandwidth &&
1827         variant_stream->width == fallback->width &&
1828         variant_stream->height == fallback->height &&
1829         variant_stream->iframe == fallback->iframe &&
1830         !g_strcmp0 (variant_stream->codecs, fallback->codecs))
1831       return variant_stream;
1832   }
1833   return NULL;
1834 }
1835
1836 static GstHLSMasterPlaylist *
1837 gst_hls_master_playlist_new (void)
1838 {
1839   GstHLSMasterPlaylist *playlist;
1840
1841   playlist = g_new0 (GstHLSMasterPlaylist, 1);
1842   playlist->refcount = 1;
1843   playlist->is_simple = FALSE;
1844
1845   return playlist;
1846 }
1847
1848 void
1849 hls_master_playlist_unref (GstHLSMasterPlaylist * playlist)
1850 {
1851   if (g_atomic_int_dec_and_test (&playlist->refcount)) {
1852     g_list_free_full (playlist->renditions,
1853         (GDestroyNotify) gst_hls_rendition_stream_unref);
1854     g_list_free_full (playlist->variants,
1855         (GDestroyNotify) gst_hls_variant_stream_unref);
1856     g_list_free_full (playlist->iframe_variants,
1857         (GDestroyNotify) gst_hls_variant_stream_unref);
1858     if (playlist->default_variant)
1859       gst_hls_variant_stream_unref (playlist->default_variant);
1860     g_free (playlist->last_data);
1861     g_free (playlist);
1862   }
1863 }
1864
1865 static gint
1866 hls_media_compare_func (GstHLSRenditionStream * ma, GstHLSRenditionStream * mb)
1867 {
1868   if (ma->mtype != mb->mtype)
1869     return ma->mtype - mb->mtype;
1870
1871   return strcmp (ma->name, mb->name) || strcmp (ma->group_id, mb->group_id);
1872 }
1873
1874 static GstCaps *
1875 stream_get_media_caps (GstHLSVariantStream * stream,
1876     GstHLSRenditionStreamType mtype)
1877 {
1878   GstStructure *st = NULL;
1879   GstCaps *ret;
1880   guint i, nb;
1881
1882   if (stream->caps == NULL)
1883     return NULL;
1884
1885   nb = gst_caps_get_size (stream->caps);
1886   for (i = 0; i < nb; i++) {
1887     GstStructure *cand = gst_caps_get_structure (stream->caps, i);
1888     const gchar *name = gst_structure_get_name (cand);
1889     gboolean matched;
1890
1891     switch (mtype) {
1892       case GST_HLS_RENDITION_STREAM_TYPE_AUDIO:
1893         matched = g_str_has_prefix (name, "audio/");
1894         break;
1895       case GST_HLS_RENDITION_STREAM_TYPE_VIDEO:
1896         matched = g_str_has_prefix (name, "video/");
1897         break;
1898       case GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES:
1899         matched = g_str_has_prefix (name, "application/x-subtitle");
1900         break;
1901       default:
1902         matched = FALSE;
1903         break;
1904     }
1905
1906     if (!matched)
1907       continue;
1908
1909     if (st) {
1910       GST_WARNING ("More than one caps for the same type, can't match");
1911       return NULL;
1912     }
1913
1914     st = cand;
1915   }
1916
1917   if (!st)
1918     return NULL;
1919
1920   ret = gst_caps_new_empty ();
1921   gst_caps_append_structure (ret, gst_structure_copy (st));
1922   return ret;
1923
1924 }
1925
1926 static gint
1927 gst_hls_variant_stream_compare_by_bitrate (gconstpointer a, gconstpointer b)
1928 {
1929   const GstHLSVariantStream *vs_a = (const GstHLSVariantStream *) a;
1930   const GstHLSVariantStream *vs_b = (const GstHLSVariantStream *) b;
1931
1932   if (vs_a->bandwidth == vs_b->bandwidth)
1933     return g_strcmp0 (vs_a->name, vs_b->name);
1934
1935   return vs_a->bandwidth - vs_b->bandwidth;
1936 }
1937
1938 /**
1939  * gst_hls_master_playlist_new_from_data:
1940  * @data: (transfer full): The manifest to parse
1941  * @base_uri: The URI of the manifest
1942  *
1943  * Parse the provided manifest and construct the master playlist.
1944  *
1945  * Returns: The parse GstHLSMasterPlaylist , or NULL if there was an error.
1946  */
1947 GstHLSMasterPlaylist *
1948 hls_master_playlist_new_from_data (gchar * data, const gchar * base_uri)
1949 {
1950   GstHLSMasterPlaylist *playlist;
1951   GstHLSVariantStream *pending_stream, *existing_stream;
1952   gchar *end, *free_data = data;
1953   gint val;
1954   GList *tmp;
1955   GstStreamType most_seen_types = 0;
1956
1957   if (!g_str_has_prefix (data, "#EXTM3U")) {
1958     GST_WARNING ("Data doesn't start with #EXTM3U");
1959     g_free (free_data);
1960     return NULL;
1961   }
1962
1963   playlist = gst_hls_master_playlist_new ();
1964
1965   /* store data before we modify it for parsing */
1966   playlist->last_data = g_strdup (data);
1967
1968   GST_TRACE ("data:\n%s", data);
1969
1970   /* Detect early whether this manifest describes a simple media playlist or
1971    * not */
1972   if (strstr (data, "\n#EXTINF:") != NULL) {
1973     GST_INFO ("This is a simple media playlist, not a master playlist");
1974
1975     pending_stream = gst_hls_variant_stream_new ();
1976     pending_stream->name = g_strdup ("media-playlist");
1977     pending_stream->uri = g_strdup (base_uri);
1978     playlist->variants = g_list_append (playlist->variants, pending_stream);
1979     playlist->default_variant = gst_hls_variant_stream_ref (pending_stream);
1980     playlist->is_simple = TRUE;
1981
1982     return playlist;
1983   }
1984
1985   /* Beginning of the actual master playlist parsing */
1986   pending_stream = NULL;
1987   data += 7;
1988   while (TRUE) {
1989     gchar *r;
1990
1991     end = g_utf8_strchr (data, -1, '\n');
1992     if (end)
1993       *end = '\0';
1994
1995     r = g_utf8_strchr (data, -1, '\r');
1996     if (r)
1997       *r = '\0';
1998
1999     if (data[0] != '#' && data[0] != '\0') {
2000       gchar *name, *uri;
2001
2002       if (pending_stream == NULL) {
2003         GST_LOG ("%s: got non-empty line without EXT-STREAM-INF, dropping",
2004             data);
2005         goto next_line;
2006       }
2007
2008       uri = uri_join (base_uri, data);
2009       if (uri == NULL)
2010         goto next_line;
2011
2012       pending_stream->name = name =
2013           generate_variant_stream_name (uri, pending_stream->bandwidth);
2014       pending_stream->uri = uri;
2015
2016       if (find_variant_stream_by_name (playlist->variants, name)
2017           || find_variant_stream_by_uri (playlist->variants, uri)) {
2018         GST_DEBUG ("Already have a list with this name or URI: %s", name);
2019         gst_hls_variant_stream_unref (pending_stream);
2020       } else if ((existing_stream =
2021               find_variant_stream_for_fallback (playlist->variants,
2022                   pending_stream))) {
2023         GST_DEBUG ("Adding to %s fallback URI %s", existing_stream->name,
2024             pending_stream->uri);
2025         existing_stream->fallback =
2026             g_list_append (existing_stream->fallback,
2027             g_strdup (pending_stream->uri));
2028         gst_hls_variant_stream_unref (pending_stream);
2029       } else {
2030         GST_INFO ("stream %s @ %u: %s", name, pending_stream->bandwidth, uri);
2031         playlist->variants = g_list_append (playlist->variants, pending_stream);
2032         /* use first stream in the playlist as default */
2033         if (playlist->default_variant == NULL) {
2034           playlist->default_variant =
2035               gst_hls_variant_stream_ref (pending_stream);
2036         }
2037       }
2038       pending_stream = NULL;
2039     } else if (g_str_has_prefix (data, "#EXT-X-VERSION:")) {
2040       if (int_from_string (data + 15, &data, &val))
2041         playlist->version = val;
2042     } else if (g_str_has_prefix (data, "#EXT-X-STREAM-INF:") ||
2043         g_str_has_prefix (data, "#EXT-X-I-FRAME-STREAM-INF:")) {
2044       GstHLSVariantStream *stream = gst_hls_variant_parse (data, base_uri);
2045
2046       if (stream->iframe) {
2047         if (find_variant_stream_by_uri (playlist->iframe_variants, stream->uri)) {
2048           GST_DEBUG ("Already have a list with this URI");
2049           gst_hls_variant_stream_unref (stream);
2050         } else {
2051           playlist->iframe_variants =
2052               g_list_append (playlist->iframe_variants, stream);
2053         }
2054       } else {
2055         if (pending_stream != NULL) {
2056           GST_WARNING ("variant stream without uri, dropping");
2057           gst_hls_variant_stream_unref (pending_stream);
2058         }
2059         pending_stream = stream;
2060       }
2061     } else if (g_str_has_prefix (data, "#EXT-X-MEDIA:")) {
2062       GstHLSRenditionStream *media;
2063
2064       media = gst_m3u8_parse_media (data + strlen ("#EXT-X-MEDIA:"), base_uri);
2065
2066       if (media == NULL)
2067         goto next_line;
2068
2069       if (g_list_find_custom (playlist->renditions, media,
2070               (GCompareFunc) hls_media_compare_func)) {
2071         GST_DEBUG ("Dropping duplicate alternate rendition group : %s", data);
2072         gst_hls_rendition_stream_unref (media);
2073         goto next_line;
2074       }
2075       playlist->renditions = g_list_append (playlist->renditions, media);
2076       GST_INFO ("Stored media %s / group %s", media->name, media->group_id);
2077     } else if (*data != '\0') {
2078       GST_LOG ("Ignored line: %s", data);
2079     }
2080
2081   next_line:
2082     if (!end)
2083       break;
2084     data = g_utf8_next_char (end);      /* skip \n */
2085   }
2086
2087   if (pending_stream != NULL) {
2088     GST_WARNING ("#EXT-X-STREAM-INF without uri, dropping");
2089     gst_hls_variant_stream_unref (pending_stream);
2090   }
2091
2092   g_free (free_data);
2093
2094   if (playlist->variants == NULL) {
2095     GST_WARNING ("Master playlist without any media playlists!");
2096     gst_hls_master_playlist_unref (playlist);
2097     return NULL;
2098   }
2099
2100   /* reorder variants by bitrate */
2101   playlist->variants =
2102       g_list_sort (playlist->variants,
2103       (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2104
2105   playlist->iframe_variants =
2106       g_list_sort (playlist->iframe_variants,
2107       (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2108
2109 #ifndef GST_DISABLE_GST_DEBUG
2110   /* Sanity check : If there are no codecs, a stream shouldn't point to
2111    * alternate rendition groups.
2112    *
2113    * Write a warning to help with further debugging if this causes issues
2114    * later */
2115   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2116     GstHLSVariantStream *stream = tmp->data;
2117
2118     if (stream->codecs == NULL) {
2119       if (stream->media_groups[0] || stream->media_groups[1]
2120           || stream->media_groups[2] || stream->media_groups[3]) {
2121         GST_WARNING
2122             ("Variant specifies alternate rendition groups but has no codecs specified");
2123       }
2124     }
2125   }
2126 #endif
2127
2128   /* Filter out audio-only variants from audio+video stream */
2129   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2130     GstHLSVariantStream *stream = tmp->data;
2131
2132     most_seen_types |= stream->codecs_stream_type;
2133   }
2134
2135   /* Flag the playlist to indicate whether all codecs are known or not on variants */
2136   playlist->have_codecs = most_seen_types != 0;
2137
2138   GST_DEBUG ("have_codecs:%d most_seen_types:%d", playlist->have_codecs,
2139       most_seen_types);
2140
2141   /* Filter out audio-only variants from audio+video stream */
2142   if (playlist->have_codecs && most_seen_types != GST_STREAM_TYPE_AUDIO) {
2143     tmp = playlist->variants;
2144     while (tmp) {
2145       GstHLSVariantStream *stream = tmp->data;
2146
2147       if (stream->codecs_stream_type != most_seen_types &&
2148           stream->codecs_stream_type == GST_STREAM_TYPE_AUDIO) {
2149         GST_DEBUG ("Remove variant with partial stream types %s", stream->name);
2150         tmp = playlist->variants = g_list_remove (playlist->variants, stream);
2151         gst_hls_variant_stream_unref (stream);
2152       } else
2153         tmp = tmp->next;
2154     }
2155   }
2156
2157   if (playlist->renditions) {
2158     guint i;
2159     /* Assign information from variants to alternate rendition groups. Note that
2160      * at this point we know that there are caps present on the variants */
2161     for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2162       GstHLSVariantStream *stream = tmp->data;
2163
2164       GST_DEBUG ("Post-processing Variant Stream '%s'", stream->name);
2165
2166       for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
2167         gchar *alt_rend_group = stream->media_groups[i];
2168
2169         if (alt_rend_group) {
2170           gboolean alt_in_variant = FALSE;
2171           GstCaps *media_caps = stream_get_media_caps (stream, i);
2172           GList *altlist;
2173           if (!media_caps)
2174             continue;
2175           for (altlist = playlist->renditions; altlist; altlist = altlist->next) {
2176             GstHLSRenditionStream *media = altlist->data;
2177             if (media->mtype != i
2178                 || g_strcmp0 (media->group_id, alt_rend_group))
2179               continue;
2180             GST_DEBUG ("  %s caps:%" GST_PTR_FORMAT " media %s, uri: %s",
2181                 GST_HLS_RENDITION_STREAM_TYPE_NAME (i), media_caps, media->name,
2182                 media->uri);
2183             if (media->uri == NULL) {
2184               GST_DEBUG ("  Media is present in main variant stream");
2185               alt_in_variant = TRUE;
2186             } else {
2187               /* Assign caps to media */
2188               if (media->caps && !gst_caps_is_equal (media->caps, media_caps)) {
2189                 GST_ERROR ("  Media already has different caps %"
2190                     GST_PTR_FORMAT, media->caps);
2191               } else {
2192                 GST_DEBUG ("  Assigning caps %" GST_PTR_FORMAT, media_caps);
2193                 gst_caps_replace (&media->caps, media_caps);
2194               }
2195             }
2196           }
2197           if (!alt_in_variant) {
2198             GstCaps *new_caps = gst_caps_subtract (stream->caps, media_caps);
2199             gst_caps_replace (&stream->caps, new_caps);
2200             gst_caps_unref (new_caps);
2201           }
2202           gst_caps_unref (media_caps);
2203         }
2204       }
2205       GST_DEBUG ("Stream Ends up with caps %" GST_PTR_FORMAT, stream->caps);
2206     }
2207   }
2208
2209   GST_DEBUG
2210       ("parsed master playlist with %d streams, %d I-frame streams and %d alternative rendition groups",
2211       g_list_length (playlist->variants),
2212       g_list_length (playlist->iframe_variants),
2213       g_list_length (playlist->renditions));
2214
2215
2216   return playlist;
2217 }
2218
2219 GstHLSVariantStream *
2220 hls_master_playlist_get_variant_for_bitrate (GstHLSMasterPlaylist *
2221     playlist, GstHLSVariantStream * current_variant, guint bitrate,
2222     guint min_bitrate)
2223 {
2224   GstHLSVariantStream *variant = current_variant;
2225   GstHLSVariantStream *variant_by_min = current_variant;
2226   GList *l;
2227
2228   /* variant lists are sorted low to high, so iterate from highest to lowest */
2229   if (current_variant == NULL || !current_variant->iframe)
2230     l = g_list_last (playlist->variants);
2231   else
2232     l = g_list_last (playlist->iframe_variants);
2233
2234   while (l != NULL) {
2235     variant = l->data;
2236     if (variant->bandwidth >= min_bitrate)
2237       variant_by_min = variant;
2238     if (variant->bandwidth <= bitrate)
2239       break;
2240     l = l->prev;
2241   }
2242
2243   /* If variant bitrate is above the min_bitrate (or min_bitrate == 0)
2244    * return it now */
2245   if (variant && variant->bandwidth >= min_bitrate)
2246     return variant;
2247
2248   /* Otherwise, return the last (lowest bitrate) variant we saw that
2249    * was higher than the min_bitrate */
2250   return variant_by_min;
2251 }
2252
2253 static gboolean
2254 remove_uncommon (GQuark field_id, GValue * value, GstStructure * st2)
2255 {
2256   const GValue *other;
2257   GValue dest = G_VALUE_INIT;
2258
2259   other = gst_structure_id_get_value (st2, field_id);
2260
2261   if (other == NULL || (G_VALUE_TYPE (value) != G_VALUE_TYPE (other)))
2262     return FALSE;
2263
2264   if (!gst_value_intersect (&dest, value, other))
2265     return FALSE;
2266
2267   g_value_reset (value);
2268   g_value_copy (&dest, value);
2269   g_value_reset (&dest);
2270
2271   return TRUE;
2272 }
2273
2274 /* Merge all common structures from caps1 and caps2
2275  *
2276  * Returns empty caps if a structure is not present in both */
2277 static GstCaps *
2278 gst_caps_merge_common (GstCaps * caps1, GstCaps * caps2)
2279 {
2280   guint it1, it2;
2281   GstCaps *res = gst_caps_new_empty ();
2282
2283   for (it1 = 0; it1 < gst_caps_get_size (caps1); it1++) {
2284     GstStructure *st1 = gst_caps_get_structure (caps1, it1);
2285     GstStructure *merged = NULL;
2286     const gchar *name1 = gst_structure_get_name (st1);
2287
2288     for (it2 = 0; it2 < gst_caps_get_size (caps2); it2++) {
2289       GstStructure *st2 = gst_caps_get_structure (caps2, it2);
2290       if (gst_structure_has_name (st2, name1)) {
2291         if (merged == NULL)
2292           merged = gst_structure_copy (st1);
2293         gst_structure_filter_and_map_in_place (merged,
2294             (GstStructureFilterMapFunc) remove_uncommon, st2);
2295       }
2296     }
2297
2298     if (merged == NULL)
2299       goto fail;
2300     gst_caps_append_structure (res, merged);
2301   }
2302
2303   return res;
2304
2305 fail:
2306   {
2307     GST_WARNING ("Failed to create common caps of %"
2308         GST_PTR_FORMAT " and %" GST_PTR_FORMAT, caps1, caps2);
2309     gst_caps_unref (res);
2310     return NULL;
2311   }
2312 }
2313
2314 GstCaps *
2315 hls_master_playlist_get_common_caps (GstHLSMasterPlaylist * playlist)
2316 {
2317   GList *tmp;
2318   GstCaps *res = NULL;
2319
2320   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2321     GstHLSVariantStream *stream = tmp->data;
2322
2323     GST_DEBUG ("stream caps %" GST_PTR_FORMAT, stream->caps);
2324     if (!stream->caps) {
2325       /* If one of the stream doesn't have *any* caps, we can't reliably return
2326        * any common caps */
2327       if (res)
2328         gst_caps_unref (res);
2329       res = NULL;
2330       goto beach;
2331     }
2332     if (!res) {
2333       res = gst_caps_copy (stream->caps);
2334     } else {
2335       GstCaps *common_caps = gst_caps_merge_common (res, stream->caps);
2336       gst_caps_unref (res);
2337       res = common_caps;
2338       if (!res)
2339         goto beach;
2340     }
2341   }
2342
2343   res = gst_caps_simplify (res);
2344
2345 beach:
2346   GST_DEBUG ("Returning common caps %" GST_PTR_FORMAT, res);
2347
2348   return res;
2349 }
2350
2351 GstStreamType
2352 gst_stream_type_from_hls_type (GstHLSRenditionStreamType mtype)
2353 {
2354   switch (mtype) {
2355     case GST_HLS_RENDITION_STREAM_TYPE_AUDIO:
2356       return GST_STREAM_TYPE_AUDIO;
2357     case GST_HLS_RENDITION_STREAM_TYPE_VIDEO:
2358       return GST_STREAM_TYPE_VIDEO;
2359     case GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES:
2360       return GST_STREAM_TYPE_TEXT;
2361     default:
2362       return GST_STREAM_TYPE_UNKNOWN;
2363   }
2364 }