hlsdemux2: m3u8: Use PDT to offset stream time when aligning playlist
[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, gboolean * matched_pdt)
983 {
984   GstM3U8MediaSegment *res = NULL;
985   guint idx;
986
987   *is_before = FALSE;
988   *matched_pdt = FALSE;
989
990   /* The easy one. Happens when stream times need to be re-synced in an existing
991    * playlist */
992   if (g_ptr_array_find (playlist->segments, segment, NULL)) {
993     GST_DEBUG ("Present as-is in playlist");
994     return segment;
995   }
996
997   /* If there is an identical segment with the same URI and SN, use that one */
998   res = gst_hls_media_playlist_find_by_uri (playlist, segment);
999   if (res) {
1000     GST_DEBUG ("Using same URI/DSN/SN match");
1001     return res;
1002   }
1003
1004   /* Try with PDT */
1005   if (segment->datetime && playlist->ext_x_pdt_present) {
1006 #ifndef GST_DISABLE_GST_DEBUG
1007     gchar *pdtstring = g_date_time_format_iso8601 (segment->datetime);
1008     GST_DEBUG ("Search by datetime for %s", pdtstring);
1009     g_free (pdtstring);
1010 #endif
1011     for (idx = 0; idx < playlist->segments->len; idx++) {
1012       GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1013
1014       if (idx == 0 && cand->datetime) {
1015         /* Special case for segments which are just before the 1st one (within
1016          * 20ms). We add another reference because it now also belongs to the
1017          * current playlist */
1018         GDateTime *seg_end = g_date_time_add (segment->datetime,
1019             segment->duration / GST_USECOND);
1020         GstClockTimeDiff ddiff =
1021             g_date_time_difference (cand->datetime, seg_end) * GST_USECOND;
1022         g_date_time_unref (seg_end);
1023         if (ABS (ddiff) < 20 * GST_MSECOND) {
1024           /* The reference segment ends within 20ms of the first segment, it is just before */
1025           GST_DEBUG ("Reference segment ends within %" GST_STIME_FORMAT
1026               " of first playlist segment, inserting before",
1027               GST_STIME_ARGS (ddiff));
1028           g_ptr_array_insert (playlist->segments, 0,
1029               gst_m3u8_media_segment_ref (segment));
1030           *is_before = TRUE;
1031           *matched_pdt = TRUE;
1032           return segment;
1033         }
1034         if (ddiff > 0) {
1035           /* If the reference segment is completely before the first segment, bail out */
1036           GST_DEBUG ("Reference segment ends before first segment");
1037           break;
1038         }
1039       }
1040
1041       if (cand->datetime
1042           && g_date_time_difference (cand->datetime, segment->datetime) >= 0) {
1043         GST_DEBUG ("Picking by date time");
1044         *matched_pdt = TRUE;
1045         return cand;
1046       }
1047     }
1048   }
1049
1050   /* If not live, we can match by stream time */
1051   if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist)) {
1052     GST_DEBUG ("Search by Stream time for %" GST_STIME_FORMAT " duration:%"
1053         GST_TIME_FORMAT, GST_STIME_ARGS (segment->stream_time),
1054         GST_TIME_ARGS (segment->duration));
1055     for (idx = 0; idx < playlist->segments->len; idx++) {
1056       GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1057
1058       /* If the candidate starts at or after the previous stream time */
1059       if (cand->stream_time >= segment->stream_time) {
1060         return cand;
1061       }
1062
1063       /* If the previous end stream time is before the candidate end stream time */
1064       if ((segment->stream_time + segment->duration) <
1065           (cand->stream_time + cand->duration)) {
1066         return cand;
1067       }
1068     }
1069   }
1070
1071   /* Fallback with MSN */
1072   GST_DEBUG ("Search by Media Sequence Number for sn:%" G_GINT64_FORMAT " dsn:%"
1073       G_GINT64_FORMAT, segment->sequence, segment->discont_sequence);
1074   for (idx = 0; idx < playlist->segments->len; idx++) {
1075     GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
1076
1077     /* Ignore non-matching DSN if needed */
1078     if ((segment->discont_sequence != cand->discont_sequence)
1079         && playlist->has_ext_x_dsn)
1080       continue;
1081
1082     if (idx == 0 && cand->sequence == segment->sequence + 1) {
1083       /* Special case for segments just before the 1st one. We add another
1084        * reference because it now also belongs to the current playlist */
1085       GST_DEBUG ("reference segment is just before 1st segment, inserting");
1086       g_ptr_array_insert (playlist->segments, 0,
1087           gst_m3u8_media_segment_ref (segment));
1088       *is_before = TRUE;
1089       return segment;
1090     }
1091
1092     if (cand->sequence == segment->sequence) {
1093       return cand;
1094     }
1095   }
1096
1097   return NULL;
1098 }
1099
1100 /* Given a media segment (potentially from another media playlist), find the
1101  * equivalent media segment in this playlist.
1102  *
1103  * This will also recalculate all stream times based on that segment stream
1104  * time (i.e. "sync" the playlist to that previous time).
1105  *
1106  * If an equivalent/identical one is found it is returned with
1107  * the reference count incremented
1108  */
1109 GstM3U8MediaSegment *
1110 gst_hls_media_playlist_sync_to_segment (GstHLSMediaPlaylist * playlist,
1111     GstM3U8MediaSegment * segment)
1112 {
1113   GstM3U8MediaSegment *res = NULL;
1114   gboolean is_before;
1115 #ifndef GST_DISABLE_GST_DEBUG
1116   gchar *pdtstring;
1117 #endif
1118
1119   g_return_val_if_fail (playlist, NULL);
1120   g_return_val_if_fail (segment, NULL);
1121
1122   GST_DEBUG ("Re-syncing to segment %" GST_STIME_FORMAT " duration:%"
1123       GST_TIME_FORMAT " sn:%" G_GINT64_FORMAT "/dsn:%" G_GINT64_FORMAT
1124       " uri:%s in playlist %s", GST_STIME_ARGS (segment->stream_time),
1125       GST_TIME_ARGS (segment->duration), segment->sequence,
1126       segment->discont_sequence, segment->uri, playlist->uri);
1127
1128   gboolean matched_pdt = FALSE;
1129   res = find_segment_in_playlist (playlist, segment, &is_before, &matched_pdt);
1130
1131   /* For live playlists we re-calculate all stream times based on the existing
1132    * stream time. Non-live playlists have their stream time calculated at
1133    * parsing time. */
1134   if (res) {
1135     if (!is_before)
1136       gst_m3u8_media_segment_ref (res);
1137     if (res->stream_time == GST_CLOCK_STIME_NONE) {
1138       GstClockTimeDiff stream_time_offset = 0;
1139       /* If there is a PDT on both segments, adjust the stream time
1140        * by the difference to align them precisely (hopefully).
1141        */
1142       if (matched_pdt) {
1143         /* If matched_pdt is TRUE, there must be PDT present in both segments */
1144         g_assert (res->datetime);
1145         g_assert (segment->datetime);
1146
1147         stream_time_offset =
1148             g_date_time_difference (res->datetime,
1149             segment->datetime) * GST_USECOND;
1150
1151         GST_DEBUG ("Transferring stream time %" GST_STIMEP_FORMAT
1152             " adjusted by PDT offset %" GST_STIMEP_FORMAT,
1153             &segment->stream_time, &stream_time_offset);
1154       }
1155       res->stream_time = segment->stream_time + stream_time_offset;
1156     }
1157     if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist))
1158       gst_hls_media_playlist_recalculate_stream_time (playlist, res);
1159     /* If the playlist didn't specify a reference discont sequence number, we
1160      * carry over the one from the reference segment */
1161     if (!playlist->has_ext_x_dsn
1162         && res->discont_sequence != segment->discont_sequence) {
1163       res->discont_sequence = segment->discont_sequence;
1164       gst_hls_media_playlist_recalculate_dsn (playlist, res);
1165     }
1166     if (is_before) {
1167       GST_DEBUG ("Dropping segment from before the playlist");
1168       g_ptr_array_remove_index (playlist->segments, 0);
1169       res = NULL;
1170     }
1171   }
1172 #ifndef GST_DISABLE_GST_DEBUG
1173   if (res) {
1174     pdtstring =
1175         res->datetime ? g_date_time_format_iso8601 (res->datetime) : NULL;
1176     GST_DEBUG ("Returning segment sn:%" G_GINT64_FORMAT " dsn:%" G_GINT64_FORMAT
1177         " stream_time:%" GST_STIME_FORMAT " duration:%" GST_TIME_FORMAT
1178         " datetime:%s", res->sequence, res->discont_sequence,
1179         GST_STIME_ARGS (res->stream_time), GST_TIME_ARGS (res->duration),
1180         pdtstring);
1181     g_free (pdtstring);
1182   } else {
1183     GST_DEBUG ("Could not find a match");
1184   }
1185 #endif
1186
1187   return res;
1188 }
1189
1190 GstM3U8MediaSegment *
1191 gst_hls_media_playlist_get_starting_segment (GstHLSMediaPlaylist * self)
1192 {
1193   GstM3U8MediaSegment *res;
1194
1195   GST_DEBUG ("playlist %s", self->uri);
1196
1197   if (!GST_HLS_MEDIA_PLAYLIST_IS_LIVE (self)) {
1198     /* For non-live, we just grab the first one */
1199     res = g_ptr_array_index (self->segments, 0);
1200   } else {
1201     /* Live playlist */
1202     res =
1203         g_ptr_array_index (self->segments,
1204         MAX ((gint) self->segments->len - GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE -
1205             1, 0));
1206   }
1207
1208   if (res) {
1209     GST_DEBUG ("Using segment sn:%" G_GINT64_FORMAT " dsn:%" G_GINT64_FORMAT,
1210         res->sequence, res->discont_sequence);
1211     gst_m3u8_media_segment_ref (res);
1212   }
1213
1214   return res;
1215 }
1216
1217 /* Calls this to carry over stream time, DSN, ... from one playlist to another.
1218  *
1219  * This should be used when a reference media segment couldn't be matched in the
1220  * playlist, but we still want to carry over the information from a reference
1221  * playlist to an updated one. This can happen with live playlists where the
1222  * reference media segment is no longer present but the playlists intersect */
1223 gboolean
1224 gst_hls_media_playlist_sync_to_playlist (GstHLSMediaPlaylist * playlist,
1225     GstHLSMediaPlaylist * reference)
1226 {
1227   GstM3U8MediaSegment *res = NULL;
1228   GstM3U8MediaSegment *cand = NULL;
1229   guint idx;
1230   gboolean is_before;
1231   gboolean matched_pdt = FALSE;
1232
1233   g_return_val_if_fail (playlist && reference, FALSE);
1234
1235 retry_without_dsn:
1236   /* The new playlist is supposed to be an update of the reference playlist,
1237    * therefore we will try from the last segment of the reference playlist and
1238    * go backwards */
1239   for (idx = reference->segments->len - 1; idx; idx--) {
1240     cand = g_ptr_array_index (reference->segments, idx);
1241     res = find_segment_in_playlist (playlist, cand, &is_before, &matched_pdt);
1242     if (res)
1243       break;
1244   }
1245
1246   if (res == NULL) {
1247     if (playlist->has_ext_x_dsn) {
1248       /* There is a possibility that the server doesn't have coherent DSN
1249        * across variants/renditions. If we reach this section, this means that
1250        * we have already attempted matching by PDT, URI, stream time. The last
1251        * matching would have been by MSN/DSN, therefore try it again without
1252        * taking DSN into account. */
1253       GST_DEBUG ("Retrying matching without taking DSN into account");
1254       playlist->has_ext_x_dsn = FALSE;
1255       goto retry_without_dsn;
1256     }
1257     GST_WARNING ("Could not synchronize media playlists");
1258     return FALSE;
1259   }
1260
1261   /* Carry over reference stream time */
1262   if (res->stream_time == GST_CLOCK_STIME_NONE) {
1263     GstClockTimeDiff stream_time_offset = 0;
1264     /* If there is a PDT on both segments, adjust the stream time
1265      * by the difference to align them precisely (hopefully).
1266      */
1267     if (matched_pdt) {
1268       /* If matched_pdt is TRUE, there must be PDT present in both segments */
1269       g_assert (playlist->ext_x_pdt_present && res->datetime);
1270       g_assert (reference->ext_x_pdt_present && cand->datetime);
1271
1272       stream_time_offset =
1273           g_date_time_difference (res->datetime, cand->datetime) * GST_USECOND;
1274       GST_DEBUG ("Transferring stream time %" GST_STIMEP_FORMAT
1275           " adjusted by PDT offset %" GST_STIMEP_FORMAT, &cand->stream_time,
1276           &stream_time_offset);
1277
1278     }
1279     res->stream_time = cand->stream_time + stream_time_offset;
1280   }
1281
1282   if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (playlist))
1283     gst_hls_media_playlist_recalculate_stream_time (playlist, res);
1284   /* If the playlist didn't specify a reference discont sequence number, we
1285    * carry over the one from the reference segment */
1286   if (!playlist->has_ext_x_dsn
1287       && res->discont_sequence != cand->discont_sequence) {
1288     res->discont_sequence = cand->discont_sequence;
1289     gst_hls_media_playlist_recalculate_dsn (playlist, res);
1290   }
1291   if (is_before) {
1292     g_ptr_array_remove_index (playlist->segments, 0);
1293   }
1294
1295   return TRUE;
1296 }
1297
1298 gboolean
1299 gst_hls_media_playlist_has_next_fragment (GstHLSMediaPlaylist * m3u8,
1300     GstM3U8MediaSegment * current, gboolean forward)
1301 {
1302   guint idx;
1303   gboolean have_next = TRUE;
1304
1305   g_return_val_if_fail (m3u8 != NULL, FALSE);
1306   g_return_val_if_fail (current != NULL, FALSE);
1307
1308   GST_DEBUG ("playlist %s", m3u8->uri);
1309
1310   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1311
1312   if (!g_ptr_array_find (m3u8->segments, current, &idx))
1313     have_next = FALSE;
1314   else if (idx == 0 && !forward)
1315     have_next = FALSE;
1316   else if (forward && idx == (m3u8->segments->len - 1))
1317     have_next = FALSE;
1318
1319   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1320
1321   GST_DEBUG ("Returning %d", have_next);
1322
1323   return have_next;
1324 }
1325
1326
1327 GstM3U8MediaSegment *
1328 gst_hls_media_playlist_advance_fragment (GstHLSMediaPlaylist * m3u8,
1329     GstM3U8MediaSegment * current, gboolean forward)
1330 {
1331   GstM3U8MediaSegment *file = NULL;
1332   guint idx;
1333
1334   g_return_val_if_fail (m3u8 != NULL, NULL);
1335   g_return_val_if_fail (current != NULL, NULL);
1336
1337   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1338
1339   GST_DEBUG ("playlist %s", m3u8->uri);
1340
1341   if (m3u8->segments->len < 2) {
1342     GST_DEBUG ("Playlist only contains one fragment, can't advance");
1343     goto out;
1344   }
1345
1346   if (!g_ptr_array_find (m3u8->segments, current, &idx)) {
1347     GST_ERROR ("Requested to advance froma fragment not present in playlist");
1348     goto out;
1349   }
1350
1351   if (forward && idx < (m3u8->segments->len - 1)) {
1352     file =
1353         gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1354             idx + 1));
1355   } else if (!forward && idx > 0) {
1356     file =
1357         gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1358             idx - 1));
1359   }
1360
1361   if (file)
1362     GST_DEBUG ("Advanced to segment sn:%" G_GINT64_FORMAT " dsn:%"
1363         G_GINT64_FORMAT, file->sequence, file->discont_sequence);
1364   else
1365     GST_DEBUG ("Could not find %s fragment", forward ? "next" : "previous");
1366
1367 out:
1368   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1369
1370   return file;
1371 }
1372
1373 GstClockTime
1374 gst_hls_media_playlist_get_duration (GstHLSMediaPlaylist * m3u8)
1375 {
1376   GstClockTime duration = GST_CLOCK_TIME_NONE;
1377
1378   g_return_val_if_fail (m3u8 != NULL, GST_CLOCK_TIME_NONE);
1379
1380   GST_DEBUG ("playlist %s", m3u8->uri);
1381
1382   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1383   /* We can only get the duration for on-demand streams */
1384   if (m3u8->endlist) {
1385     if (m3u8->segments->len) {
1386       GstM3U8MediaSegment *first = g_ptr_array_index (m3u8->segments, 0);
1387       GstM3U8MediaSegment *last =
1388           g_ptr_array_index (m3u8->segments, m3u8->segments->len - 1);
1389       duration = last->stream_time + last->duration - first->stream_time;
1390       if (duration != m3u8->duration)
1391         GST_ERROR ("difference in calculated duration ? %" GST_TIME_FORMAT
1392             " vs %" GST_TIME_FORMAT, GST_TIME_ARGS (duration),
1393             GST_TIME_ARGS (m3u8->duration));
1394     }
1395     duration = m3u8->duration;
1396   }
1397   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1398
1399   GST_DEBUG ("duration %" GST_TIME_FORMAT, GST_TIME_ARGS (duration));
1400
1401   return duration;
1402 }
1403
1404 gchar *
1405 gst_hls_media_playlist_get_uri (GstHLSMediaPlaylist * m3u8)
1406 {
1407   gchar *uri;
1408
1409   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1410   uri = g_strdup (m3u8->uri);
1411   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1412
1413   return uri;
1414 }
1415
1416 gboolean
1417 gst_hls_media_playlist_is_live (GstHLSMediaPlaylist * m3u8)
1418 {
1419   gboolean is_live;
1420
1421   g_return_val_if_fail (m3u8 != NULL, FALSE);
1422
1423   GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1424   is_live = GST_HLS_MEDIA_PLAYLIST_IS_LIVE (m3u8);
1425   GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1426
1427   return is_live;
1428 }
1429
1430 gchar *
1431 uri_join (const gchar * uri1, const gchar * uri2)
1432 {
1433   gchar *uri_copy, *tmp, *ret = NULL;
1434
1435   if (gst_uri_is_valid (uri2))
1436     return g_strdup (uri2);
1437
1438   uri_copy = g_strdup (uri1);
1439   if (uri2[0] != '/') {
1440     /* uri2 is a relative uri2 */
1441     /* look for query params */
1442     tmp = g_utf8_strchr (uri_copy, -1, '?');
1443     if (tmp) {
1444       /* find last / char, ignoring query params */
1445       tmp = g_utf8_strrchr (uri_copy, tmp - uri_copy, '/');
1446     } else {
1447       /* find last / char in URL */
1448       tmp = g_utf8_strrchr (uri_copy, -1, '/');
1449     }
1450     if (!tmp)
1451       goto out;
1452
1453
1454     *tmp = '\0';
1455     ret = g_strdup_printf ("%s/%s", uri_copy, uri2);
1456   } else {
1457     /* uri2 is an absolute uri2 */
1458     char *scheme, *hostname;
1459
1460     scheme = uri_copy;
1461     /* find the : in <scheme>:// */
1462     tmp = g_utf8_strchr (uri_copy, -1, ':');
1463     if (!tmp)
1464       goto out;
1465
1466     *tmp = '\0';
1467
1468     /* skip :// */
1469     hostname = tmp + 3;
1470
1471     tmp = g_utf8_strchr (hostname, -1, '/');
1472     if (tmp)
1473       *tmp = '\0';
1474
1475     ret = g_strdup_printf ("%s://%s%s", scheme, hostname, uri2);
1476   }
1477
1478 out:
1479   g_free (uri_copy);
1480   if (!ret)
1481     GST_WARNING ("Can't build a valid uri from '%s' '%s'", uri1, uri2);
1482
1483   return ret;
1484 }
1485
1486 gboolean
1487 gst_hls_media_playlist_has_lost_sync (GstHLSMediaPlaylist * m3u8,
1488     GstClockTime position)
1489 {
1490   GstM3U8MediaSegment *first;
1491
1492   if (m3u8->segments->len < 1)
1493     return TRUE;
1494   first = g_ptr_array_index (m3u8->segments, 0);
1495
1496   GST_DEBUG ("position %" GST_TIME_FORMAT " first %" GST_STIME_FORMAT
1497       " duration %" GST_STIME_FORMAT, GST_TIME_ARGS (position),
1498       GST_STIME_ARGS (first->stream_time), GST_STIME_ARGS (first->duration));
1499
1500   if (first->stream_time <= 0)
1501     return FALSE;
1502
1503   /* If we're definitely before the first fragment, we lost sync */
1504   if ((position + (first->duration / 2)) < first->stream_time)
1505     return TRUE;
1506   return FALSE;
1507 }
1508
1509 gboolean
1510 gst_hls_media_playlist_get_seek_range (GstHLSMediaPlaylist * m3u8,
1511     gint64 * start, gint64 * stop)
1512 {
1513   GstM3U8MediaSegment *first, *last;
1514   guint min_distance = 1;
1515
1516   g_return_val_if_fail (m3u8 != NULL, FALSE);
1517
1518   if (m3u8->segments->len < 1)
1519     return FALSE;
1520
1521   first = g_ptr_array_index (m3u8->segments, 0);
1522   *start = first->stream_time;
1523
1524   if (GST_HLS_MEDIA_PLAYLIST_IS_LIVE (m3u8) && m3u8->segments->len > 1) {
1525     /* min_distance is used to make sure the seek range is never closer than
1526        GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE fragments from the end of a live
1527        playlist - see 6.3.3. "Playing the Playlist file" of the HLS draft */
1528     min_distance =
1529         MIN (GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE, m3u8->segments->len - 1);
1530   }
1531
1532   last = g_ptr_array_index (m3u8->segments, m3u8->segments->len - min_distance);
1533   *stop = last->stream_time + last->duration;
1534
1535   return TRUE;
1536 }
1537
1538 GstClockTime
1539 gst_hls_media_playlist_recommended_buffering_threshold (GstHLSMediaPlaylist *
1540     playlist)
1541 {
1542   if (!playlist->duration || !GST_CLOCK_TIME_IS_VALID (playlist->duration)
1543       || playlist->segments->len == 0)
1544     return GST_CLOCK_TIME_NONE;
1545
1546   /* The recommended buffering threshold is 1.5 average segment duration */
1547   return 3 * (playlist->duration / playlist->segments->len) / 2;
1548 }
1549
1550 GstHLSRenditionStream *
1551 gst_hls_rendition_stream_ref (GstHLSRenditionStream * media)
1552 {
1553   g_assert (media != NULL && media->ref_count > 0);
1554   g_atomic_int_add (&media->ref_count, 1);
1555   return media;
1556 }
1557
1558 void
1559 gst_hls_rendition_stream_unref (GstHLSRenditionStream * media)
1560 {
1561   g_assert (media != NULL && media->ref_count > 0);
1562   if (g_atomic_int_dec_and_test (&media->ref_count)) {
1563     if (media->caps)
1564       gst_caps_unref (media->caps);
1565     g_free (media->group_id);
1566     g_free (media->name);
1567     g_free (media->uri);
1568     g_free (media->lang);
1569     g_free (media);
1570   }
1571 }
1572
1573 static GstHLSRenditionStreamType
1574 gst_m3u8_get_hls_media_type_from_string (const gchar * type_name)
1575 {
1576   if (strcmp (type_name, "AUDIO") == 0)
1577     return GST_HLS_RENDITION_STREAM_TYPE_AUDIO;
1578   if (strcmp (type_name, "VIDEO") == 0)
1579     return GST_HLS_RENDITION_STREAM_TYPE_VIDEO;
1580   if (strcmp (type_name, "SUBTITLES") == 0)
1581     return GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES;
1582   if (strcmp (type_name, "CLOSED_CAPTIONS") == 0)
1583     return GST_HLS_RENDITION_STREAM_TYPE_CLOSED_CAPTIONS;
1584
1585   return GST_HLS_RENDITION_STREAM_TYPE_INVALID;
1586 }
1587
1588 #define GST_HLS_RENDITION_STREAM_TYPE_NAME(mtype) gst_hls_rendition_stream_type_get_name(mtype)
1589 const gchar *
1590 gst_hls_rendition_stream_type_get_name (GstHLSRenditionStreamType mtype)
1591 {
1592   static const gchar *nicks[GST_HLS_N_MEDIA_TYPES] = { "audio", "video",
1593     "subtitle", "closed-captions"
1594   };
1595
1596   if (mtype < 0 || mtype >= GST_HLS_N_MEDIA_TYPES)
1597     return "invalid";
1598
1599   return nicks[mtype];
1600 }
1601
1602 /* returns unquoted copy of string */
1603 static gchar *
1604 gst_m3u8_unquote (const gchar * str)
1605 {
1606   const gchar *start, *end;
1607
1608   start = strchr (str, '"');
1609   if (start == NULL)
1610     return g_strdup (str);
1611   end = strchr (start + 1, '"');
1612   if (end == NULL) {
1613     GST_WARNING ("Broken quoted string [%s] - can't find end quote", str);
1614     return g_strdup (start + 1);
1615   }
1616   return g_strndup (start + 1, (gsize) (end - (start + 1)));
1617 }
1618
1619 static GstHLSRenditionStream *
1620 gst_m3u8_parse_media (gchar * desc, const gchar * base_uri)
1621 {
1622   GstHLSRenditionStream *media;
1623   gchar *a, *v;
1624
1625   media = g_new0 (GstHLSRenditionStream, 1);
1626   media->ref_count = 1;
1627   media->mtype = GST_HLS_RENDITION_STREAM_TYPE_INVALID;
1628
1629   GST_LOG ("parsing %s", desc);
1630   while (desc != NULL && parse_attributes (&desc, &a, &v)) {
1631     if (strcmp (a, "TYPE") == 0) {
1632       media->mtype = gst_m3u8_get_hls_media_type_from_string (v);
1633     } else if (strcmp (a, "GROUP-ID") == 0) {
1634       g_free (media->group_id);
1635       media->group_id = gst_m3u8_unquote (v);
1636     } else if (strcmp (a, "NAME") == 0) {
1637       g_free (media->name);
1638       media->name = gst_m3u8_unquote (v);
1639     } else if (strcmp (a, "URI") == 0) {
1640       gchar *uri;
1641
1642       g_free (media->uri);
1643       uri = gst_m3u8_unquote (v);
1644       media->uri = uri_join (base_uri, uri);
1645       g_free (uri);
1646     } else if (strcmp (a, "LANGUAGE") == 0) {
1647       g_free (media->lang);
1648       media->lang = gst_m3u8_unquote (v);
1649     } else if (strcmp (a, "DEFAULT") == 0) {
1650       media->is_default = g_ascii_strcasecmp (v, "yes") == 0;
1651     } else if (strcmp (a, "FORCED") == 0) {
1652       media->forced = g_ascii_strcasecmp (v, "yes") == 0;
1653     } else if (strcmp (a, "AUTOSELECT") == 0) {
1654       media->autoselect = g_ascii_strcasecmp (v, "yes") == 0;
1655     } else {
1656       /* unhandled: ASSOC-LANGUAGE, INSTREAM-ID, CHARACTERISTICS */
1657       GST_FIXME ("EXT-X-MEDIA: unhandled attribute: %s = %s", a, v);
1658     }
1659   }
1660
1661   if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_INVALID)
1662     goto required_attributes_missing;
1663
1664   if (media->group_id == NULL || media->name == NULL)
1665     goto required_attributes_missing;
1666
1667   if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_CLOSED_CAPTIONS)
1668     goto uri_with_cc;
1669
1670   GST_DEBUG ("media: %s, group '%s', name '%s', uri '%s', %s %s %s, lang=%s",
1671       GST_HLS_RENDITION_STREAM_TYPE_NAME (media->mtype), media->group_id,
1672       media->name, media->uri, media->is_default ? "default" : "-",
1673       media->autoselect ? "autoselect" : "-", media->forced ? "forced" : "-",
1674       media->lang ? media->lang : "??");
1675
1676   return media;
1677
1678 uri_with_cc:
1679   {
1680     GST_WARNING ("closed captions EXT-X-MEDIA should not have URI specified");
1681     goto out_error;
1682   }
1683 required_attributes_missing:
1684   {
1685     GST_WARNING ("EXT-X-MEDIA description is missing required attributes");
1686     goto out_error;
1687   }
1688
1689 out_error:
1690   {
1691     gst_hls_rendition_stream_unref (media);
1692     return NULL;
1693   }
1694 }
1695
1696 GstStreamType
1697 gst_hls_get_stream_type_from_structure (GstStructure * st)
1698 {
1699   const gchar *name = gst_structure_get_name (st);
1700
1701   if (g_str_has_prefix (name, "audio/"))
1702     return GST_STREAM_TYPE_AUDIO;
1703
1704   if (g_str_has_prefix (name, "video/"))
1705     return GST_STREAM_TYPE_VIDEO;
1706
1707   if (g_str_has_prefix (name, "application/x-subtitle"))
1708     return GST_STREAM_TYPE_TEXT;
1709
1710   return 0;
1711 }
1712
1713 GstStreamType
1714 gst_hls_get_stream_type_from_caps (GstCaps * caps)
1715 {
1716   GstStreamType ret = 0;
1717   guint i, nb;
1718   nb = gst_caps_get_size (caps);
1719   for (i = 0; i < nb; i++) {
1720     GstStructure *cand = gst_caps_get_structure (caps, i);
1721
1722     ret |= gst_hls_get_stream_type_from_structure (cand);
1723   }
1724
1725   return ret;
1726 }
1727
1728 static GstHLSVariantStream *
1729 gst_hls_variant_stream_new (void)
1730 {
1731   GstHLSVariantStream *stream;
1732
1733   stream = g_new0 (GstHLSVariantStream, 1);
1734   stream->refcount = 1;
1735   stream->codecs_stream_type = 0;
1736   return stream;
1737 }
1738
1739 GstHLSVariantStream *
1740 hls_variant_stream_ref (GstHLSVariantStream * stream)
1741 {
1742   g_atomic_int_inc (&stream->refcount);
1743   return stream;
1744 }
1745
1746 void
1747 hls_variant_stream_unref (GstHLSVariantStream * stream)
1748 {
1749   if (g_atomic_int_dec_and_test (&stream->refcount)) {
1750     gint i;
1751
1752     g_free (stream->name);
1753     g_free (stream->uri);
1754     g_free (stream->codecs);
1755     if (stream->caps)
1756       gst_caps_unref (stream->caps);
1757     for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
1758       g_free (stream->media_groups[i]);
1759     }
1760     g_list_free_full (stream->fallback, g_free);
1761     g_free (stream);
1762   }
1763 }
1764
1765 static GstHLSVariantStream *
1766 gst_hls_variant_parse (gchar * data, const gchar * base_uri)
1767 {
1768   GstHLSVariantStream *stream;
1769   gchar *v, *a;
1770
1771   stream = gst_hls_variant_stream_new ();
1772   stream->iframe = g_str_has_prefix (data, "#EXT-X-I-FRAME-STREAM-INF:");
1773   data += stream->iframe ? 26 : 18;
1774
1775   while (data && parse_attributes (&data, &a, &v)) {
1776     if (g_str_equal (a, "BANDWIDTH")) {
1777       if (!stream->bandwidth) {
1778         if (!int_from_string (v, NULL, &stream->bandwidth))
1779           GST_WARNING ("Error while reading BANDWIDTH");
1780       }
1781     } else if (g_str_equal (a, "AVERAGE-BANDWIDTH")) {
1782       GST_DEBUG
1783           ("AVERAGE-BANDWIDTH attribute available. Using it as stream bandwidth");
1784       if (!int_from_string (v, NULL, &stream->bandwidth))
1785         GST_WARNING ("Error while reading AVERAGE-BANDWIDTH");
1786     } else if (g_str_equal (a, "PROGRAM-ID")) {
1787       if (!int_from_string (v, NULL, &stream->program_id))
1788         GST_WARNING ("Error while reading PROGRAM-ID");
1789     } else if (g_str_equal (a, "CODECS")) {
1790       g_free (stream->codecs);
1791       stream->codecs = g_strdup (v);
1792       stream->caps = gst_codec_utils_caps_from_mime_codec (stream->codecs);
1793       stream->codecs_stream_type =
1794           gst_hls_get_stream_type_from_caps (stream->caps);
1795     } else if (g_str_equal (a, "RESOLUTION")) {
1796       if (!int_from_string (v, &v, &stream->width))
1797         GST_WARNING ("Error while reading RESOLUTION width");
1798       if (!v || *v != 'x') {
1799         GST_WARNING ("Missing height");
1800       } else {
1801         v = g_utf8_next_char (v);
1802         if (!int_from_string (v, NULL, &stream->height))
1803           GST_WARNING ("Error while reading RESOLUTION height");
1804       }
1805     } else if (stream->iframe && g_str_equal (a, "URI")) {
1806       stream->uri = uri_join (base_uri, v);
1807     } else if (g_str_equal (a, "AUDIO")) {
1808       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_AUDIO]);
1809       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_AUDIO] =
1810           gst_m3u8_unquote (v);
1811     } else if (g_str_equal (a, "SUBTITLES")) {
1812       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES]);
1813       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES] =
1814           gst_m3u8_unquote (v);
1815     } else if (g_str_equal (a, "VIDEO")) {
1816       g_free (stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_VIDEO]);
1817       stream->media_groups[GST_HLS_RENDITION_STREAM_TYPE_VIDEO] =
1818           gst_m3u8_unquote (v);
1819     } else if (g_str_equal (a, "CLOSED-CAPTIONS")) {
1820       /* closed captions will be embedded inside the video stream, ignore */
1821     }
1822   }
1823
1824   return stream;
1825 }
1826
1827 static gchar *
1828 generate_variant_stream_name (gchar * uri, gint bandwidth)
1829 {
1830   gchar *checksum = g_compute_checksum_for_string (G_CHECKSUM_SHA1, uri, -1);
1831   gchar *res = g_strdup_printf ("variant-%dbps-%s", bandwidth, checksum);
1832
1833   g_free (checksum);
1834   return res;
1835 }
1836
1837 static GstHLSVariantStream *
1838 find_variant_stream_by_name (GList * list, const gchar * name)
1839 {
1840   for (; list != NULL; list = list->next) {
1841     GstHLSVariantStream *variant_stream = list->data;
1842
1843     if (variant_stream->name != NULL && !strcmp (variant_stream->name, name))
1844       return variant_stream;
1845   }
1846   return NULL;
1847 }
1848
1849 static GstHLSVariantStream *
1850 find_variant_stream_by_uri (GList * list, const gchar * uri)
1851 {
1852   for (; list != NULL; list = list->next) {
1853     GstHLSVariantStream *variant_stream = list->data;
1854
1855     if (variant_stream->uri != NULL && !strcmp (variant_stream->uri, uri))
1856       return variant_stream;
1857   }
1858   return NULL;
1859 }
1860
1861 static GstHLSVariantStream *
1862 find_variant_stream_for_fallback (GList * list, GstHLSVariantStream * fallback)
1863 {
1864   for (; list != NULL; list = list->next) {
1865     GstHLSVariantStream *variant_stream = list->data;
1866
1867     if (variant_stream->bandwidth == fallback->bandwidth &&
1868         variant_stream->width == fallback->width &&
1869         variant_stream->height == fallback->height &&
1870         variant_stream->iframe == fallback->iframe &&
1871         !g_strcmp0 (variant_stream->codecs, fallback->codecs))
1872       return variant_stream;
1873   }
1874   return NULL;
1875 }
1876
1877 static GstHLSMasterPlaylist *
1878 gst_hls_master_playlist_new (void)
1879 {
1880   GstHLSMasterPlaylist *playlist;
1881
1882   playlist = g_new0 (GstHLSMasterPlaylist, 1);
1883   playlist->refcount = 1;
1884   playlist->is_simple = FALSE;
1885
1886   return playlist;
1887 }
1888
1889 void
1890 hls_master_playlist_unref (GstHLSMasterPlaylist * playlist)
1891 {
1892   if (g_atomic_int_dec_and_test (&playlist->refcount)) {
1893     g_list_free_full (playlist->renditions,
1894         (GDestroyNotify) gst_hls_rendition_stream_unref);
1895     g_list_free_full (playlist->variants,
1896         (GDestroyNotify) gst_hls_variant_stream_unref);
1897     g_list_free_full (playlist->iframe_variants,
1898         (GDestroyNotify) gst_hls_variant_stream_unref);
1899     if (playlist->default_variant)
1900       gst_hls_variant_stream_unref (playlist->default_variant);
1901     g_free (playlist->last_data);
1902     g_free (playlist);
1903   }
1904 }
1905
1906 static gint
1907 hls_media_compare_func (GstHLSRenditionStream * ma, GstHLSRenditionStream * mb)
1908 {
1909   if (ma->mtype != mb->mtype)
1910     return ma->mtype - mb->mtype;
1911
1912   return strcmp (ma->name, mb->name) || strcmp (ma->group_id, mb->group_id);
1913 }
1914
1915 static GstCaps *
1916 stream_get_media_caps (GstHLSVariantStream * stream,
1917     GstHLSRenditionStreamType mtype)
1918 {
1919   GstStructure *st = NULL;
1920   GstCaps *ret;
1921   guint i, nb;
1922
1923   if (stream->caps == NULL)
1924     return NULL;
1925
1926   nb = gst_caps_get_size (stream->caps);
1927   for (i = 0; i < nb; i++) {
1928     GstStructure *cand = gst_caps_get_structure (stream->caps, i);
1929     const gchar *name = gst_structure_get_name (cand);
1930     gboolean matched;
1931
1932     switch (mtype) {
1933       case GST_HLS_RENDITION_STREAM_TYPE_AUDIO:
1934         matched = g_str_has_prefix (name, "audio/");
1935         break;
1936       case GST_HLS_RENDITION_STREAM_TYPE_VIDEO:
1937         matched = g_str_has_prefix (name, "video/");
1938         break;
1939       case GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES:
1940         matched = g_str_has_prefix (name, "application/x-subtitle");
1941         break;
1942       default:
1943         matched = FALSE;
1944         break;
1945     }
1946
1947     if (!matched)
1948       continue;
1949
1950     if (st) {
1951       GST_WARNING ("More than one caps for the same type, can't match");
1952       return NULL;
1953     }
1954
1955     st = cand;
1956   }
1957
1958   if (!st)
1959     return NULL;
1960
1961   ret = gst_caps_new_empty ();
1962   gst_caps_append_structure (ret, gst_structure_copy (st));
1963   return ret;
1964
1965 }
1966
1967 static gint
1968 gst_hls_variant_stream_compare_by_bitrate (gconstpointer a, gconstpointer b)
1969 {
1970   const GstHLSVariantStream *vs_a = (const GstHLSVariantStream *) a;
1971   const GstHLSVariantStream *vs_b = (const GstHLSVariantStream *) b;
1972
1973   if (vs_a->bandwidth == vs_b->bandwidth)
1974     return g_strcmp0 (vs_a->name, vs_b->name);
1975
1976   return vs_a->bandwidth - vs_b->bandwidth;
1977 }
1978
1979 /**
1980  * gst_hls_master_playlist_new_from_data:
1981  * @data: (transfer full): The manifest to parse
1982  * @base_uri: The URI of the manifest
1983  *
1984  * Parse the provided manifest and construct the master playlist.
1985  *
1986  * Returns: The parse GstHLSMasterPlaylist , or NULL if there was an error.
1987  */
1988 GstHLSMasterPlaylist *
1989 hls_master_playlist_new_from_data (gchar * data, const gchar * base_uri)
1990 {
1991   GstHLSMasterPlaylist *playlist;
1992   GstHLSVariantStream *pending_stream, *existing_stream;
1993   gchar *end, *free_data = data;
1994   gint val;
1995   GList *tmp;
1996   GstStreamType most_seen_types = 0;
1997
1998   if (!g_str_has_prefix (data, "#EXTM3U")) {
1999     GST_WARNING ("Data doesn't start with #EXTM3U");
2000     g_free (free_data);
2001     return NULL;
2002   }
2003
2004   playlist = gst_hls_master_playlist_new ();
2005
2006   /* store data before we modify it for parsing */
2007   playlist->last_data = g_strdup (data);
2008
2009   GST_TRACE ("data:\n%s", data);
2010
2011   /* Detect early whether this manifest describes a simple media playlist or
2012    * not */
2013   if (strstr (data, "\n#EXTINF:") != NULL) {
2014     GST_INFO ("This is a simple media playlist, not a master playlist");
2015
2016     pending_stream = gst_hls_variant_stream_new ();
2017     pending_stream->name = g_strdup ("media-playlist");
2018     pending_stream->uri = g_strdup (base_uri);
2019     playlist->variants = g_list_append (playlist->variants, pending_stream);
2020     playlist->default_variant = gst_hls_variant_stream_ref (pending_stream);
2021     playlist->is_simple = TRUE;
2022
2023     return playlist;
2024   }
2025
2026   /* Beginning of the actual master playlist parsing */
2027   pending_stream = NULL;
2028   data += 7;
2029   while (TRUE) {
2030     gchar *r;
2031
2032     end = g_utf8_strchr (data, -1, '\n');
2033     if (end)
2034       *end = '\0';
2035
2036     r = g_utf8_strchr (data, -1, '\r');
2037     if (r)
2038       *r = '\0';
2039
2040     if (data[0] != '#' && data[0] != '\0') {
2041       gchar *name, *uri;
2042
2043       if (pending_stream == NULL) {
2044         GST_LOG ("%s: got non-empty line without EXT-STREAM-INF, dropping",
2045             data);
2046         goto next_line;
2047       }
2048
2049       uri = uri_join (base_uri, data);
2050       if (uri == NULL)
2051         goto next_line;
2052
2053       pending_stream->name = name =
2054           generate_variant_stream_name (uri, pending_stream->bandwidth);
2055       pending_stream->uri = uri;
2056
2057       if (find_variant_stream_by_name (playlist->variants, name)
2058           || find_variant_stream_by_uri (playlist->variants, uri)) {
2059         GST_DEBUG ("Already have a list with this name or URI: %s", name);
2060         gst_hls_variant_stream_unref (pending_stream);
2061       } else if ((existing_stream =
2062               find_variant_stream_for_fallback (playlist->variants,
2063                   pending_stream))) {
2064         GST_DEBUG ("Adding to %s fallback URI %s", existing_stream->name,
2065             pending_stream->uri);
2066         existing_stream->fallback =
2067             g_list_append (existing_stream->fallback,
2068             g_strdup (pending_stream->uri));
2069         gst_hls_variant_stream_unref (pending_stream);
2070       } else {
2071         GST_INFO ("stream %s @ %u: %s", name, pending_stream->bandwidth, uri);
2072         playlist->variants = g_list_append (playlist->variants, pending_stream);
2073         /* use first stream in the playlist as default */
2074         if (playlist->default_variant == NULL) {
2075           playlist->default_variant =
2076               gst_hls_variant_stream_ref (pending_stream);
2077         }
2078       }
2079       pending_stream = NULL;
2080     } else if (g_str_has_prefix (data, "#EXT-X-VERSION:")) {
2081       if (int_from_string (data + 15, &data, &val))
2082         playlist->version = val;
2083     } else if (g_str_has_prefix (data, "#EXT-X-STREAM-INF:") ||
2084         g_str_has_prefix (data, "#EXT-X-I-FRAME-STREAM-INF:")) {
2085       GstHLSVariantStream *stream = gst_hls_variant_parse (data, base_uri);
2086
2087       if (stream->iframe) {
2088         if (find_variant_stream_by_uri (playlist->iframe_variants, stream->uri)) {
2089           GST_DEBUG ("Already have a list with this URI");
2090           gst_hls_variant_stream_unref (stream);
2091         } else {
2092           playlist->iframe_variants =
2093               g_list_append (playlist->iframe_variants, stream);
2094         }
2095       } else {
2096         if (pending_stream != NULL) {
2097           GST_WARNING ("variant stream without uri, dropping");
2098           gst_hls_variant_stream_unref (pending_stream);
2099         }
2100         pending_stream = stream;
2101       }
2102     } else if (g_str_has_prefix (data, "#EXT-X-MEDIA:")) {
2103       GstHLSRenditionStream *media;
2104
2105       media = gst_m3u8_parse_media (data + strlen ("#EXT-X-MEDIA:"), base_uri);
2106
2107       if (media == NULL)
2108         goto next_line;
2109
2110       if (g_list_find_custom (playlist->renditions, media,
2111               (GCompareFunc) hls_media_compare_func)) {
2112         GST_DEBUG ("Dropping duplicate alternate rendition group : %s", data);
2113         gst_hls_rendition_stream_unref (media);
2114         goto next_line;
2115       }
2116       playlist->renditions = g_list_append (playlist->renditions, media);
2117       GST_INFO ("Stored media %s / group %s", media->name, media->group_id);
2118     } else if (*data != '\0') {
2119       GST_LOG ("Ignored line: %s", data);
2120     }
2121
2122   next_line:
2123     if (!end)
2124       break;
2125     data = g_utf8_next_char (end);      /* skip \n */
2126   }
2127
2128   if (pending_stream != NULL) {
2129     GST_WARNING ("#EXT-X-STREAM-INF without uri, dropping");
2130     gst_hls_variant_stream_unref (pending_stream);
2131   }
2132
2133   g_free (free_data);
2134
2135   if (playlist->variants == NULL) {
2136     GST_WARNING ("Master playlist without any media playlists!");
2137     gst_hls_master_playlist_unref (playlist);
2138     return NULL;
2139   }
2140
2141   /* reorder variants by bitrate */
2142   playlist->variants =
2143       g_list_sort (playlist->variants,
2144       (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2145
2146   playlist->iframe_variants =
2147       g_list_sort (playlist->iframe_variants,
2148       (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2149
2150 #ifndef GST_DISABLE_GST_DEBUG
2151   /* Sanity check : If there are no codecs, a stream shouldn't point to
2152    * alternate rendition groups.
2153    *
2154    * Write a warning to help with further debugging if this causes issues
2155    * later */
2156   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2157     GstHLSVariantStream *stream = tmp->data;
2158
2159     if (stream->codecs == NULL) {
2160       if (stream->media_groups[0] || stream->media_groups[1]
2161           || stream->media_groups[2] || stream->media_groups[3]) {
2162         GST_WARNING
2163             ("Variant specifies alternate rendition groups but has no codecs specified");
2164       }
2165     }
2166   }
2167 #endif
2168
2169   /* Filter out audio-only variants from audio+video stream */
2170   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2171     GstHLSVariantStream *stream = tmp->data;
2172
2173     most_seen_types |= stream->codecs_stream_type;
2174   }
2175
2176   /* Flag the playlist to indicate whether all codecs are known or not on variants */
2177   playlist->have_codecs = most_seen_types != 0;
2178
2179   GST_DEBUG ("have_codecs:%d most_seen_types:%d", playlist->have_codecs,
2180       most_seen_types);
2181
2182   /* Filter out audio-only variants from audio+video stream */
2183   if (playlist->have_codecs && most_seen_types != GST_STREAM_TYPE_AUDIO) {
2184     tmp = playlist->variants;
2185     while (tmp) {
2186       GstHLSVariantStream *stream = tmp->data;
2187
2188       if (stream->codecs_stream_type != most_seen_types &&
2189           stream->codecs_stream_type == GST_STREAM_TYPE_AUDIO) {
2190         GST_DEBUG ("Remove variant with partial stream types %s", stream->name);
2191         tmp = playlist->variants = g_list_remove (playlist->variants, stream);
2192         gst_hls_variant_stream_unref (stream);
2193       } else
2194         tmp = tmp->next;
2195     }
2196   }
2197
2198   if (playlist->renditions) {
2199     guint i;
2200     /* Assign information from variants to alternate rendition groups. Note that
2201      * at this point we know that there are caps present on the variants */
2202     for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2203       GstHLSVariantStream *stream = tmp->data;
2204
2205       GST_DEBUG ("Post-processing Variant Stream '%s'", stream->name);
2206
2207       for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
2208         gchar *alt_rend_group = stream->media_groups[i];
2209
2210         if (alt_rend_group) {
2211           gboolean alt_in_variant = FALSE;
2212           GstCaps *media_caps = stream_get_media_caps (stream, i);
2213           GList *altlist;
2214           if (!media_caps)
2215             continue;
2216           for (altlist = playlist->renditions; altlist; altlist = altlist->next) {
2217             GstHLSRenditionStream *media = altlist->data;
2218             if (media->mtype != i
2219                 || g_strcmp0 (media->group_id, alt_rend_group))
2220               continue;
2221             GST_DEBUG ("  %s caps:%" GST_PTR_FORMAT " media %s, uri: %s",
2222                 GST_HLS_RENDITION_STREAM_TYPE_NAME (i), media_caps, media->name,
2223                 media->uri);
2224             if (media->uri == NULL) {
2225               GST_DEBUG ("  Media is present in main variant stream");
2226               alt_in_variant = TRUE;
2227             } else {
2228               /* Assign caps to media */
2229               if (media->caps && !gst_caps_is_equal (media->caps, media_caps)) {
2230                 GST_ERROR ("  Media already has different caps %"
2231                     GST_PTR_FORMAT, media->caps);
2232               } else {
2233                 GST_DEBUG ("  Assigning caps %" GST_PTR_FORMAT, media_caps);
2234                 gst_caps_replace (&media->caps, media_caps);
2235               }
2236             }
2237           }
2238           if (!alt_in_variant) {
2239             GstCaps *new_caps = gst_caps_subtract (stream->caps, media_caps);
2240             gst_caps_replace (&stream->caps, new_caps);
2241             gst_caps_unref (new_caps);
2242           }
2243           gst_caps_unref (media_caps);
2244         }
2245       }
2246       GST_DEBUG ("Stream Ends up with caps %" GST_PTR_FORMAT, stream->caps);
2247     }
2248   }
2249
2250   GST_DEBUG
2251       ("parsed master playlist with %d streams, %d I-frame streams and %d alternative rendition groups",
2252       g_list_length (playlist->variants),
2253       g_list_length (playlist->iframe_variants),
2254       g_list_length (playlist->renditions));
2255
2256
2257   return playlist;
2258 }
2259
2260 GstHLSVariantStream *
2261 hls_master_playlist_get_variant_for_bitrate (GstHLSMasterPlaylist *
2262     playlist, GstHLSVariantStream * current_variant, guint bitrate,
2263     guint min_bitrate)
2264 {
2265   GstHLSVariantStream *variant = current_variant;
2266   GstHLSVariantStream *variant_by_min = current_variant;
2267   GList *l;
2268
2269   /* variant lists are sorted low to high, so iterate from highest to lowest */
2270   if (current_variant == NULL || !current_variant->iframe)
2271     l = g_list_last (playlist->variants);
2272   else
2273     l = g_list_last (playlist->iframe_variants);
2274
2275   while (l != NULL) {
2276     variant = l->data;
2277     if (variant->bandwidth >= min_bitrate)
2278       variant_by_min = variant;
2279     if (variant->bandwidth <= bitrate)
2280       break;
2281     l = l->prev;
2282   }
2283
2284   /* If variant bitrate is above the min_bitrate (or min_bitrate == 0)
2285    * return it now */
2286   if (variant && variant->bandwidth >= min_bitrate)
2287     return variant;
2288
2289   /* Otherwise, return the last (lowest bitrate) variant we saw that
2290    * was higher than the min_bitrate */
2291   return variant_by_min;
2292 }
2293
2294 static gboolean
2295 remove_uncommon (GQuark field_id, GValue * value, GstStructure * st2)
2296 {
2297   const GValue *other;
2298   GValue dest = G_VALUE_INIT;
2299
2300   other = gst_structure_id_get_value (st2, field_id);
2301
2302   if (other == NULL || (G_VALUE_TYPE (value) != G_VALUE_TYPE (other)))
2303     return FALSE;
2304
2305   if (!gst_value_intersect (&dest, value, other))
2306     return FALSE;
2307
2308   g_value_reset (value);
2309   g_value_copy (&dest, value);
2310   g_value_reset (&dest);
2311
2312   return TRUE;
2313 }
2314
2315 /* Merge all common structures from caps1 and caps2
2316  *
2317  * Returns empty caps if a structure is not present in both */
2318 static GstCaps *
2319 gst_caps_merge_common (GstCaps * caps1, GstCaps * caps2)
2320 {
2321   guint it1, it2;
2322   GstCaps *res = gst_caps_new_empty ();
2323
2324   for (it1 = 0; it1 < gst_caps_get_size (caps1); it1++) {
2325     GstStructure *st1 = gst_caps_get_structure (caps1, it1);
2326     GstStructure *merged = NULL;
2327     const gchar *name1 = gst_structure_get_name (st1);
2328
2329     for (it2 = 0; it2 < gst_caps_get_size (caps2); it2++) {
2330       GstStructure *st2 = gst_caps_get_structure (caps2, it2);
2331       if (gst_structure_has_name (st2, name1)) {
2332         if (merged == NULL)
2333           merged = gst_structure_copy (st1);
2334         gst_structure_filter_and_map_in_place (merged,
2335             (GstStructureFilterMapFunc) remove_uncommon, st2);
2336       }
2337     }
2338
2339     if (merged == NULL)
2340       goto fail;
2341     gst_caps_append_structure (res, merged);
2342   }
2343
2344   return res;
2345
2346 fail:
2347   {
2348     GST_WARNING ("Failed to create common caps of %"
2349         GST_PTR_FORMAT " and %" GST_PTR_FORMAT, caps1, caps2);
2350     gst_caps_unref (res);
2351     return NULL;
2352   }
2353 }
2354
2355 GstCaps *
2356 hls_master_playlist_get_common_caps (GstHLSMasterPlaylist * playlist)
2357 {
2358   GList *tmp;
2359   GstCaps *res = NULL;
2360
2361   for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2362     GstHLSVariantStream *stream = tmp->data;
2363
2364     GST_DEBUG ("stream caps %" GST_PTR_FORMAT, stream->caps);
2365     if (!stream->caps) {
2366       /* If one of the stream doesn't have *any* caps, we can't reliably return
2367        * any common caps */
2368       if (res)
2369         gst_caps_unref (res);
2370       res = NULL;
2371       goto beach;
2372     }
2373     if (!res) {
2374       res = gst_caps_copy (stream->caps);
2375     } else {
2376       GstCaps *common_caps = gst_caps_merge_common (res, stream->caps);
2377       gst_caps_unref (res);
2378       res = common_caps;
2379       if (!res)
2380         goto beach;
2381     }
2382   }
2383
2384   res = gst_caps_simplify (res);
2385
2386 beach:
2387   GST_DEBUG ("Returning common caps %" GST_PTR_FORMAT, res);
2388
2389   return res;
2390 }
2391
2392 GstStreamType
2393 gst_stream_type_from_hls_type (GstHLSRenditionStreamType mtype)
2394 {
2395   switch (mtype) {
2396     case GST_HLS_RENDITION_STREAM_TYPE_AUDIO:
2397       return GST_STREAM_TYPE_AUDIO;
2398     case GST_HLS_RENDITION_STREAM_TYPE_VIDEO:
2399       return GST_STREAM_TYPE_VIDEO;
2400     case GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES:
2401       return GST_STREAM_TYPE_TEXT;
2402     default:
2403       return GST_STREAM_TYPE_UNKNOWN;
2404   }
2405 }