2 * Copyright (C) 2010 Marc-Andre Lureau <marcandre.lureau@gmail.com>
3 * Copyright (C) 2015 Tim-Philipp Müller <tim@centricular.com>
5 * Copyright (C) 2021-2022 Centricular Ltd
6 * Author: Edward Hervey <edward@centricular.com>
7 * Author: Jan Schmidt <jan@centricular.com>
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.
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.
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.
34 #include <gst/pbutils/pbutils.h>
36 #include "gstadaptivedemux.h"
37 #include "gsthlselements.h"
39 #define GST_CAT_DEFAULT hls2_debug
41 static gchar *uri_join (const gchar * uri, const gchar * path);
44 gst_hls_media_playlist_ref (GstHLSMediaPlaylist * m3u8)
46 g_assert (m3u8 != NULL && m3u8->ref_count > 0);
48 g_atomic_int_add (&m3u8->ref_count, 1);
53 gst_hls_media_playlist_unref (GstHLSMediaPlaylist * self)
55 g_return_if_fail (self != NULL && self->ref_count > 0);
57 if (g_atomic_int_dec_and_test (&self->ref_count)) {
59 g_free (self->base_uri);
61 g_ptr_array_free (self->segments, TRUE);
63 g_free (self->last_data);
64 g_mutex_clear (&self->lock);
69 static GstM3U8MediaSegment *
70 gst_m3u8_media_segment_new (gchar * uri, gchar * title, GstClockTime duration,
71 gint64 sequence, gint64 discont_sequence)
73 GstM3U8MediaSegment *file;
75 file = g_new0 (GstM3U8MediaSegment, 1);
78 file->duration = duration;
79 file->sequence = sequence;
80 file->discont_sequence = discont_sequence;
83 file->stream_time = GST_CLOCK_STIME_NONE;
89 gst_m3u8_media_segment_ref (GstM3U8MediaSegment * mfile)
91 g_assert (mfile != NULL && mfile->ref_count > 0);
93 g_atomic_int_add (&mfile->ref_count, 1);
98 gst_m3u8_media_segment_unref (GstM3U8MediaSegment * self)
100 g_return_if_fail (self != NULL && self->ref_count > 0);
102 if (g_atomic_int_dec_and_test (&self->ref_count)) {
104 gst_m3u8_init_file_unref (self->init_file);
105 g_free (self->title);
109 g_date_time_unref (self->datetime);
114 static GstM3U8InitFile *
115 gst_m3u8_init_file_new (gchar * uri)
117 GstM3U8InitFile *file;
119 file = g_new0 (GstM3U8InitFile, 1);
127 gst_m3u8_init_file_ref (GstM3U8InitFile * ifile)
129 g_assert (ifile != NULL && ifile->ref_count > 0);
131 g_atomic_int_add (&ifile->ref_count, 1);
136 gst_m3u8_init_file_unref (GstM3U8InitFile * self)
138 g_return_if_fail (self != NULL && self->ref_count > 0);
140 if (g_atomic_int_dec_and_test (&self->ref_count)) {
147 gst_m3u8_init_file_equal (const GstM3U8InitFile * ifile1,
148 const GstM3U8InitFile * ifile2)
150 if (ifile1 == ifile2)
153 if (ifile1 == NULL && ifile2 != NULL)
155 if (ifile1 != NULL && ifile2 == NULL)
158 if (!g_str_equal (ifile1->uri, ifile2->uri))
160 if (ifile1->offset != ifile2->offset)
162 if (ifile1->size != ifile2->size)
169 int_from_string (gchar * ptr, gchar ** endptr, gint * val)
174 g_return_val_if_fail (ptr != NULL, FALSE);
175 g_return_val_if_fail (val != NULL, FALSE);
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));
185 if (ret > G_MAXINT || ret < G_MININT) {
186 GST_WARNING ("%s", g_strerror (ERANGE));
199 int64_from_string (gchar * ptr, gchar ** endptr, gint64 * val)
204 g_return_val_if_fail (ptr != NULL, FALSE);
205 g_return_val_if_fail (val != NULL, FALSE);
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));
224 double_from_string (gchar * ptr, gchar ** endptr, gdouble * val)
229 g_return_val_if_fail (ptr != NULL, FALSE);
230 g_return_val_if_fail (val != NULL, FALSE);
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));
240 if (!isfinite (ret)) {
241 GST_WARNING ("%s", g_strerror (ERANGE));
248 *val = (gdouble) ret;
254 parse_attributes (gchar ** ptr, gchar ** a, gchar ** v)
256 gchar *end = NULL, *p, *ve;
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);
263 /* [attribute=value,]* */
266 end = p = g_utf8_strchr (*ptr, -1, ',');
268 gchar *q = g_utf8_strchr (*ptr, -1, '"');
270 /* special case, such as CODECS="avc1.77.30, mp4a.40.2" */
271 q = g_utf8_next_char (q);
273 q = g_utf8_strchr (q, -1, '"');
276 end = p = g_utf8_strchr (q, -1, ',');
282 end = g_utf8_next_char (end);
283 } while (end && *end == ' ');
287 *v = p = g_utf8_strchr (*ptr, -1, '=');
290 *v = g_utf8_next_char (*v);
292 ve = g_utf8_next_char (*v);
294 ve = g_utf8_strchr (ve, -1, '"');
297 *v = g_utf8_next_char (*v);
300 GST_WARNING ("Cannot remove quotation marks from %s", *a);
304 GST_WARNING ("missing = after attribute");
312 GstHLSMediaPlaylist *
313 gst_hls_media_playlist_new (const gchar * uri, const gchar * base_uri)
315 GstHLSMediaPlaylist *m3u8;
317 m3u8 = g_new0 (GstHLSMediaPlaylist, 1);
319 m3u8->uri = g_strdup (uri);
320 m3u8->base_uri = g_strdup (base_uri);
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;
331 m3u8->ext_x_key_present = FALSE;
332 m3u8->ext_x_pdt_present = FALSE;
335 g_ptr_array_new_full (16, (GDestroyNotify) gst_m3u8_media_segment_unref);
339 g_mutex_init (&m3u8->lock);
346 gst_hls_media_playlist_dump (GstHLSMediaPlaylist * self)
348 #ifndef GST_DISABLE_GST_DEBUG
352 GST_DEBUG ("uri : %s", self->uri);
353 GST_DEBUG ("base_uri : %s", self->base_uri);
355 GST_DEBUG ("version : %d", self->version);
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);
362 GST_DEBUG ("endlist : %s",
363 self->endlist ? "present" : "NOT present");
364 GST_DEBUG ("i_frame : %s", self->i_frame ? "YES" : "NO");
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");
371 GST_DEBUG ("duration : %" GST_TIME_FORMAT,
372 GST_TIME_ARGS (self->duration));
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);
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));
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);
392 GST_DEBUG (" uri : %s %" G_GUINT64_FORMAT " %" G_GINT64_FORMAT,
393 segment->uri, segment->offset, segment->size);
399 gst_hls_media_playlist_postprocess_pdt (GstHLSMediaPlaylist * self)
401 gint idx, len = self->segments->len;
403 GstM3U8MediaSegment *previous = NULL;
404 GstM3U8MediaSegment *segment = NULL;
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);
410 #define ABSDIFF(a,b) ((a) > (b) ? (a) - (b) : (b) - (a))
412 if (segment->datetime) {
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);
424 g_date_time_add (previous->datetime,
425 previous->duration / GST_USECOND);
429 if (segment->discont) {
430 GST_WARNING ("Discont segment doesn't have a PDT !");
431 } else if (previous) {
432 if (previous->datetime) {
434 g_date_time_add (previous->datetime,
435 previous->duration / GST_USECOND);
437 ("Generated new PDT based on previous segment PDT and duration");
439 GST_LOG ("Missing PDT, but can't generate it from previous one");
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) {
450 segment = g_ptr_array_index (self->segments, idx);
451 if (!segment->datetime && previous->datetime) {
453 g_date_time_add (previous->datetime,
454 -(segment->duration / GST_USECOND));
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)
466 gchar *input_data = data;
467 GstHLSMediaPlaylist *self;
469 GstClockTime duration;
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;
478 GDateTime *date_time = NULL;
479 GstM3U8InitFile *last_init_file = NULL;
480 GstM3U8MediaSegment *previous = NULL;
482 GST_LOG ("uri: %s", uri);
483 GST_LOG ("base_uri: %s", base_uri);
484 GST_TRACE ("data:\n%s", data);
486 if (!g_str_has_prefix (data, "#EXTM3U")) {
487 GST_WARNING ("Data doesn't start with #EXTM3U");
492 if (g_strrstr (data, "\n#EXT-X-STREAM-INF:") != NULL) {
493 GST_WARNING ("Not a media playlist, but a master playlist!");
498 self = gst_hls_media_playlist_new (uri, base_uri);
500 /* Store a copy of the data */
501 self->last_data = g_strdup (data);
509 end = g_utf8_strchr (data, -1, '\n');
513 r = g_utf8_strchr (data, -1, '\r');
517 if (data[0] != '#' && data[0] != '\0') {
519 GST_LOG ("%s: got line without EXTINF, dropping", data);
523 data = uri_join (self->base_uri ? self->base_uri : self->uri, data);
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");
535 discontinuity = FALSE;
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. */
545 gst_m3u8_media_segment_new (data, title, duration, mediasequence++,
547 self->duration += duration;
549 /* set encryption params */
550 file->key = current_key ? g_strdup (current_key) : NULL;
553 memcpy (file->iv, iv, sizeof (iv));
555 guint8 *iv = file->iv + 12;
556 GST_WRITE_UINT32_BE (iv, file->sequence);
563 file->offset = offset;
572 file->datetime = date_time;
573 file->discont = discontinuity;
575 file->init_file = gst_m3u8_init_file_ref (last_init_file);
577 date_time = NULL; /* Ownership was passed to the segment */
579 title = NULL; /* Ownership was passed to the segment */
580 discontinuity = FALSE;
582 g_ptr_array_add (self->segments, file);
586 } else if (g_str_has_prefix (data, "#EXTINF:")) {
588 if (!double_from_string (data + 8, &data, &fval)) {
589 GST_WARNING ("Can't read EXTINF duration");
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));
598 if (!data || *data != ',')
600 data = g_utf8_next_char (data);
603 title = g_strdup (data);
605 } else if (g_str_has_prefix (data, "#EXT-X-")) {
606 gchar *data_ext_x = data + 7;
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))
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;
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;
633 } else if (g_str_has_prefix (data_ext_x, "DISCONTINUITY")) {
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);
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:")) {
647 /* IV and KEY are only valid until the next #EXT-X-KEY */
649 g_free (current_key);
651 while (data && parse_attributes (&data, &a, &v)) {
652 if (g_str_equal (a, "URI")) {
654 uri_join (self->base_uri ? self->base_uri : self->uri, v);
655 } else if (g_str_equal (a, "IV")) {
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");
666 for (i = 0; i < 16; i++) {
669 h = g_ascii_xdigit_value (*ivp);
671 l = g_ascii_xdigit_value (*ivp);
673 if (h == -1 || l == -1) {
677 iv[i] = (h << 4) | l;
681 GST_WARNING ("Can't read IV");
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);
690 self->ext_x_key_present = TRUE;
693 } else if (g_str_has_prefix (data_ext_x, "BYTERANGE:")) {
694 gchar *v = data + 17;
698 if (int64_from_string (v, &v, &size)) {
699 if (*v == '@' && !int64_from_string (v + 1, &v, &offset))
702 if (offset == -1 && previous)
703 offset = previous->offset + previous->size;
707 } else if (g_str_has_prefix (data_ext_x, "MAP:")) {
708 gchar *v, *a, *header_uri = NULL;
712 while (data != NULL && parse_attributes (&data, &a, &v)) {
713 if (strcmp (a, "URI") == 0) {
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)) {
730 GstM3U8InitFile *init_file;
731 init_file = gst_m3u8_init_file_new (header_uri);
734 init_file->size = size;
736 init_file->offset = offset;
738 init_file->offset = 0;
740 init_file->size = -1;
741 init_file->offset = 0;
744 gst_m3u8_init_file_unref (last_init_file);
746 last_init_file = init_file;
749 GST_LOG ("Ignored line: %s", data);
751 } else if (data[0]) {
752 /* Log non-empty lines */
753 GST_LOG ("Ignored line: `%s`", data);
759 data = g_utf8_next_char (end); /* skip \n */
762 /* Clean up date that wasn't freed / handed to a segment */
763 g_free (current_key);
766 g_date_time_unref (date_time);
772 gst_m3u8_init_file_unref (last_init_file);
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);
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);
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;
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;
796 gst_hls_media_playlist_dump (self);
800 /* Returns TRUE if the m3u8 as the same data as playlist_data */
802 gst_hls_media_playlist_has_same_data (GstHLSMediaPlaylist * self,
803 gchar * playlist_data)
807 GST_HLS_MEDIA_PLAYLIST_LOCK (self);
809 ret = self->last_data && g_str_equal (self->last_data, playlist_data);
811 GST_HLS_MEDIA_PLAYLIST_UNLOCK (self);
816 GstM3U8MediaSegment *
817 gst_hls_media_playlist_seek (GstHLSMediaPlaylist * playlist, gboolean forward,
818 GstSeekFlags flags, GstClockTimeDiff ts)
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;
825 GstM3U8MediaSegment *res = NULL;
827 GST_DEBUG ("ts:%" GST_STIME_FORMAT " forward:%d playlist uri: %s",
828 GST_STIME_ARGS (ts), forward, playlist->uri);
830 for (idx = 0; idx < playlist->segments->len; idx++) {
831 GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
833 if ((forward & snap_after) || snap_nearest) {
834 if (cand->stream_time >= ts ||
835 (snap_nearest && (ts - cand->stream_time < cand->duration / 2))) {
839 } else if (!forward && snap_after) {
840 GstClockTime next_pos = cand->stream_time + cand->duration;
842 if (next_pos <= ts && ts < next_pos + cand->duration) {
846 } else if ((cand->stream_time <= ts || idx == 0)
847 && ts < cand->stream_time + cand->duration) {
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);
860 GST_DEBUG ("Couldn't find a match");
866 /* Recalculate all segment DSN based on the DSN of the provided anchor segment
867 * (which must belong to the playlist). */
869 gst_hls_media_playlist_recalculate_dsn (GstHLSMediaPlaylist * playlist,
870 GstM3U8MediaSegment * anchor)
874 GstM3U8MediaSegment *cand, *prev;
876 if (!g_ptr_array_find (playlist->segments, anchor, &idx)) {
880 g_assert (idx != -1);
882 GST_DEBUG ("Re-calculating DSN from segment #%d %" G_GINT64_FORMAT,
883 idx, anchor->discont_sequence);
887 for (iter = idx + 1; iter < playlist->segments->len; iter++) {
888 cand = g_ptr_array_index (playlist->segments, iter);
890 cand->discont_sequence = prev->discont_sequence + 1;
892 cand->discont_sequence = prev->discont_sequence;
898 for (iter = idx - 1; iter >= 0; iter--) {
899 cand = g_ptr_array_index (playlist->segments, iter);
901 cand->discont_sequence = prev->discont_sequence - 1;
903 cand->discont_sequence = prev->discont_sequence;
909 /* Recalculate all segment stream time based on the stream time of the provided
910 * anchor segment (which must belong to the playlist) */
912 gst_hls_media_playlist_recalculate_stream_time (GstHLSMediaPlaylist * playlist,
913 GstM3U8MediaSegment * anchor)
917 GstM3U8MediaSegment *cand, *prev;
919 if (!g_ptr_array_find (playlist->segments, anchor, &idx)) {
923 g_assert (GST_CLOCK_TIME_IS_VALID (anchor->stream_time));
924 g_assert (idx != -1);
926 GST_DEBUG ("Re-calculating stream times from segment #%d %" GST_TIME_FORMAT,
927 idx, GST_TIME_ARGS (anchor->stream_time));
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));
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));
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)
958 for (idx = 0; idx < playlist->segments->len; idx++) {
959 GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
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)) {
972 /* Find the equivalent segment in the given playlist.
974 * The returned segment does *NOT* have increased reference !
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
980 static GstM3U8MediaSegment *
981 find_segment_in_playlist (GstHLSMediaPlaylist * playlist,
982 GstM3U8MediaSegment * segment, gboolean * is_before)
984 GstM3U8MediaSegment *res = NULL;
989 /* The easy one. Happens when stream times need to be re-synced in an existing
991 if (g_ptr_array_find (playlist->segments, segment, NULL)) {
992 GST_DEBUG ("Present as-is in playlist");
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);
999 GST_DEBUG ("Using same URI/DSN/SN match");
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);
1010 for (idx = 0; idx < playlist->segments->len; idx++) {
1011 GstM3U8MediaSegment *cand = g_ptr_array_index (playlist->segments, idx);
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));
1033 /* If the reference segment is completely before the first segment, bail out */
1034 GST_DEBUG ("Reference segment ends before first segment");
1040 && g_date_time_difference (cand->datetime, segment->datetime) >= 0) {
1041 GST_DEBUG ("Picking by date time");
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);
1055 /* If the candidate starts at or after the previous stream time */
1056 if (cand->stream_time >= segment->stream_time) {
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)) {
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);
1074 /* Ignore non-matching DSN if needed */
1075 if ((segment->discont_sequence != cand->discont_sequence)
1076 && playlist->has_ext_x_dsn)
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));
1089 if (cand->sequence == segment->sequence) {
1097 /* Given a media segment (potentially from another media playlist), find the
1098 * equivalent media segment in this playlist.
1100 * This will also recalculate all stream times based on that segment stream
1101 * time (i.e. "sync" the playlist to that previous time).
1103 * If an equivalent/identical one is found it is returned with
1104 * the reference count incremented
1106 GstM3U8MediaSegment *
1107 gst_hls_media_playlist_sync_to_segment (GstHLSMediaPlaylist * playlist,
1108 GstM3U8MediaSegment * segment)
1110 GstM3U8MediaSegment *res = NULL;
1112 #ifndef GST_DISABLE_GST_DEBUG
1116 g_return_val_if_fail (playlist, NULL);
1117 g_return_val_if_fail (segment, NULL);
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);
1125 res = find_segment_in_playlist (playlist, segment, &is_before);
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
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);
1145 GST_DEBUG ("Dropping segment from before the playlist");
1146 g_ptr_array_remove_index (playlist->segments, 0);
1150 #ifndef GST_DISABLE_GST_DEBUG
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),
1161 GST_DEBUG ("Could not find a match");
1168 GstM3U8MediaSegment *
1169 gst_hls_media_playlist_get_starting_segment (GstHLSMediaPlaylist * self)
1171 GstM3U8MediaSegment *res;
1173 GST_DEBUG ("playlist %s", self->uri);
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);
1181 g_ptr_array_index (self->segments,
1182 MAX ((gint) self->segments->len - GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE -
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);
1195 /* Calls this to carry over stream time, DSN, ... from one playlist to another.
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 */
1202 gst_hls_media_playlist_sync_to_playlist (GstHLSMediaPlaylist * playlist,
1203 GstHLSMediaPlaylist * reference)
1205 GstM3U8MediaSegment *res = NULL;
1206 GstM3U8MediaSegment *cand = NULL;
1210 g_return_val_if_fail (playlist && reference, FALSE);
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
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);
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;
1234 GST_WARNING ("Could not synchronize media playlists");
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);
1251 g_ptr_array_remove_index (playlist->segments, 0);
1258 gst_hls_media_playlist_has_next_fragment (GstHLSMediaPlaylist * m3u8,
1259 GstM3U8MediaSegment * current, gboolean forward)
1262 gboolean have_next = TRUE;
1264 g_return_val_if_fail (m3u8 != NULL, FALSE);
1265 g_return_val_if_fail (current != NULL, FALSE);
1267 GST_DEBUG ("playlist %s", m3u8->uri);
1269 GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1271 if (!g_ptr_array_find (m3u8->segments, current, &idx))
1273 else if (idx == 0 && !forward)
1275 else if (forward && idx == (m3u8->segments->len - 1))
1278 GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1280 GST_DEBUG ("Returning %d", have_next);
1286 GstM3U8MediaSegment *
1287 gst_hls_media_playlist_advance_fragment (GstHLSMediaPlaylist * m3u8,
1288 GstM3U8MediaSegment * current, gboolean forward)
1290 GstM3U8MediaSegment *file = NULL;
1293 g_return_val_if_fail (m3u8 != NULL, NULL);
1294 g_return_val_if_fail (current != NULL, NULL);
1296 GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1298 GST_DEBUG ("playlist %s", m3u8->uri);
1300 if (m3u8->segments->len < 2) {
1301 GST_DEBUG ("Playlist only contains one fragment, can't advance");
1305 if (!g_ptr_array_find (m3u8->segments, current, &idx)) {
1306 GST_ERROR ("Requested to advance froma fragment not present in playlist");
1310 if (forward && idx < (m3u8->segments->len - 1)) {
1312 gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1314 } else if (!forward && idx > 0) {
1316 gst_m3u8_media_segment_ref (g_ptr_array_index (m3u8->segments,
1321 GST_DEBUG ("Advanced to segment sn:%" G_GINT64_FORMAT " dsn:%"
1322 G_GINT64_FORMAT, file->sequence, file->discont_sequence);
1324 GST_DEBUG ("Could not find %s fragment", forward ? "next" : "previous");
1327 GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1333 gst_hls_media_playlist_get_duration (GstHLSMediaPlaylist * m3u8)
1335 GstClockTime duration = GST_CLOCK_TIME_NONE;
1337 g_return_val_if_fail (m3u8 != NULL, GST_CLOCK_TIME_NONE);
1339 GST_DEBUG ("playlist %s", m3u8->uri);
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));
1354 duration = m3u8->duration;
1356 GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1358 GST_DEBUG ("duration %" GST_TIME_FORMAT, GST_TIME_ARGS (duration));
1364 gst_hls_media_playlist_get_uri (GstHLSMediaPlaylist * m3u8)
1368 GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1369 uri = g_strdup (m3u8->uri);
1370 GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1376 gst_hls_media_playlist_is_live (GstHLSMediaPlaylist * m3u8)
1380 g_return_val_if_fail (m3u8 != NULL, FALSE);
1382 GST_HLS_MEDIA_PLAYLIST_LOCK (m3u8);
1383 is_live = GST_HLS_MEDIA_PLAYLIST_IS_LIVE (m3u8);
1384 GST_HLS_MEDIA_PLAYLIST_UNLOCK (m3u8);
1390 uri_join (const gchar * uri1, const gchar * uri2)
1392 gchar *uri_copy, *tmp, *ret = NULL;
1394 if (gst_uri_is_valid (uri2))
1395 return g_strdup (uri2);
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, '?');
1403 /* find last / char, ignoring query params */
1404 tmp = g_utf8_strrchr (uri_copy, tmp - uri_copy, '/');
1406 /* find last / char in URL */
1407 tmp = g_utf8_strrchr (uri_copy, -1, '/');
1414 ret = g_strdup_printf ("%s/%s", uri_copy, uri2);
1416 /* uri2 is an absolute uri2 */
1417 char *scheme, *hostname;
1420 /* find the : in <scheme>:// */
1421 tmp = g_utf8_strchr (uri_copy, -1, ':');
1430 tmp = g_utf8_strchr (hostname, -1, '/');
1434 ret = g_strdup_printf ("%s://%s%s", scheme, hostname, uri2);
1440 GST_WARNING ("Can't build a valid uri from '%s' '%s'", uri1, uri2);
1446 gst_hls_media_playlist_has_lost_sync (GstHLSMediaPlaylist * m3u8,
1447 GstClockTime position)
1449 GstM3U8MediaSegment *first;
1451 if (m3u8->segments->len < 1)
1453 first = g_ptr_array_index (m3u8->segments, 0);
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));
1459 if (first->stream_time <= 0)
1462 /* If we're definitely before the first fragment, we lost sync */
1463 if ((position + (first->duration / 2)) < first->stream_time)
1469 gst_hls_media_playlist_get_seek_range (GstHLSMediaPlaylist * m3u8,
1470 gint64 * start, gint64 * stop)
1472 GstM3U8MediaSegment *first, *last;
1473 guint min_distance = 1;
1475 g_return_val_if_fail (m3u8 != NULL, FALSE);
1477 if (m3u8->segments->len < 1)
1480 first = g_ptr_array_index (m3u8->segments, 0);
1481 *start = first->stream_time;
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 */
1488 MIN (GST_M3U8_LIVE_MIN_FRAGMENT_DISTANCE, m3u8->segments->len - 1);
1491 last = g_ptr_array_index (m3u8->segments, m3u8->segments->len - min_distance);
1492 *stop = last->stream_time + last->duration;
1498 gst_hls_media_playlist_recommended_buffering_threshold (GstHLSMediaPlaylist *
1501 if (!playlist->duration || !GST_CLOCK_TIME_IS_VALID (playlist->duration)
1502 || playlist->segments->len == 0)
1503 return GST_CLOCK_TIME_NONE;
1505 /* The recommended buffering threshold is 1.5 average segment duration */
1506 return 3 * (playlist->duration / playlist->segments->len) / 2;
1509 GstHLSRenditionStream *
1510 gst_hls_rendition_stream_ref (GstHLSRenditionStream * media)
1512 g_assert (media != NULL && media->ref_count > 0);
1513 g_atomic_int_add (&media->ref_count, 1);
1518 gst_hls_rendition_stream_unref (GstHLSRenditionStream * media)
1520 g_assert (media != NULL && media->ref_count > 0);
1521 if (g_atomic_int_dec_and_test (&media->ref_count)) {
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);
1532 static GstHLSRenditionStreamType
1533 gst_m3u8_get_hls_media_type_from_string (const gchar * type_name)
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;
1544 return GST_HLS_RENDITION_STREAM_TYPE_INVALID;
1547 #define GST_HLS_RENDITION_STREAM_TYPE_NAME(mtype) gst_hls_rendition_stream_type_get_name(mtype)
1549 gst_hls_rendition_stream_type_get_name (GstHLSRenditionStreamType mtype)
1551 static const gchar *nicks[GST_HLS_N_MEDIA_TYPES] = { "audio", "video",
1552 "subtitle", "closed-captions"
1555 if (mtype < 0 || mtype >= GST_HLS_N_MEDIA_TYPES)
1558 return nicks[mtype];
1561 /* returns unquoted copy of string */
1563 gst_m3u8_unquote (const gchar * str)
1565 const gchar *start, *end;
1567 start = strchr (str, '"');
1569 return g_strdup (str);
1570 end = strchr (start + 1, '"');
1572 GST_WARNING ("Broken quoted string [%s] - can't find end quote", str);
1573 return g_strdup (start + 1);
1575 return g_strndup (start + 1, (gsize) (end - (start + 1)));
1578 static GstHLSRenditionStream *
1579 gst_m3u8_parse_media (gchar * desc, const gchar * base_uri)
1581 GstHLSRenditionStream *media;
1584 media = g_new0 (GstHLSRenditionStream, 1);
1585 media->ref_count = 1;
1586 media->mtype = GST_HLS_RENDITION_STREAM_TYPE_INVALID;
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) {
1601 g_free (media->uri);
1602 uri = gst_m3u8_unquote (v);
1603 media->uri = uri_join (base_uri, 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;
1615 /* unhandled: ASSOC-LANGUAGE, INSTREAM-ID, CHARACTERISTICS */
1616 GST_FIXME ("EXT-X-MEDIA: unhandled attribute: %s = %s", a, v);
1620 if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_INVALID)
1621 goto required_attributes_missing;
1623 if (media->group_id == NULL || media->name == NULL)
1624 goto required_attributes_missing;
1626 if (media->mtype == GST_HLS_RENDITION_STREAM_TYPE_CLOSED_CAPTIONS)
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 : "??");
1639 GST_WARNING ("closed captions EXT-X-MEDIA should not have URI specified");
1642 required_attributes_missing:
1644 GST_WARNING ("EXT-X-MEDIA description is missing required attributes");
1650 gst_hls_rendition_stream_unref (media);
1656 gst_hls_get_stream_type_from_structure (GstStructure * st)
1658 const gchar *name = gst_structure_get_name (st);
1660 if (g_str_has_prefix (name, "audio/"))
1661 return GST_STREAM_TYPE_AUDIO;
1663 if (g_str_has_prefix (name, "video/"))
1664 return GST_STREAM_TYPE_VIDEO;
1666 if (g_str_has_prefix (name, "application/x-subtitle"))
1667 return GST_STREAM_TYPE_TEXT;
1673 gst_hls_get_stream_type_from_caps (GstCaps * caps)
1675 GstStreamType ret = 0;
1677 nb = gst_caps_get_size (caps);
1678 for (i = 0; i < nb; i++) {
1679 GstStructure *cand = gst_caps_get_structure (caps, i);
1681 ret |= gst_hls_get_stream_type_from_structure (cand);
1687 static GstHLSVariantStream *
1688 gst_hls_variant_stream_new (void)
1690 GstHLSVariantStream *stream;
1692 stream = g_new0 (GstHLSVariantStream, 1);
1693 stream->refcount = 1;
1694 stream->codecs_stream_type = 0;
1698 GstHLSVariantStream *
1699 hls_variant_stream_ref (GstHLSVariantStream * stream)
1701 g_atomic_int_inc (&stream->refcount);
1706 hls_variant_stream_unref (GstHLSVariantStream * stream)
1708 if (g_atomic_int_dec_and_test (&stream->refcount)) {
1711 g_free (stream->name);
1712 g_free (stream->uri);
1713 g_free (stream->codecs);
1715 gst_caps_unref (stream->caps);
1716 for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
1717 g_free (stream->media_groups[i]);
1719 g_list_free_full (stream->fallback, g_free);
1724 static GstHLSVariantStream *
1725 gst_hls_variant_parse (gchar * data, const gchar * base_uri)
1727 GstHLSVariantStream *stream;
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;
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");
1740 } else if (g_str_equal (a, "AVERAGE-BANDWIDTH")) {
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");
1760 v = g_utf8_next_char (v);
1761 if (!int_from_string (v, NULL, &stream->height))
1762 GST_WARNING ("Error while reading RESOLUTION height");
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 */
1787 generate_variant_stream_name (gchar * uri, gint bandwidth)
1789 gchar *checksum = g_compute_checksum_for_string (G_CHECKSUM_SHA1, uri, -1);
1790 gchar *res = g_strdup_printf ("variant-%dbps-%s", bandwidth, checksum);
1796 static GstHLSVariantStream *
1797 find_variant_stream_by_name (GList * list, const gchar * name)
1799 for (; list != NULL; list = list->next) {
1800 GstHLSVariantStream *variant_stream = list->data;
1802 if (variant_stream->name != NULL && !strcmp (variant_stream->name, name))
1803 return variant_stream;
1808 static GstHLSVariantStream *
1809 find_variant_stream_by_uri (GList * list, const gchar * uri)
1811 for (; list != NULL; list = list->next) {
1812 GstHLSVariantStream *variant_stream = list->data;
1814 if (variant_stream->uri != NULL && !strcmp (variant_stream->uri, uri))
1815 return variant_stream;
1820 static GstHLSVariantStream *
1821 find_variant_stream_for_fallback (GList * list, GstHLSVariantStream * fallback)
1823 for (; list != NULL; list = list->next) {
1824 GstHLSVariantStream *variant_stream = list->data;
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;
1836 static GstHLSMasterPlaylist *
1837 gst_hls_master_playlist_new (void)
1839 GstHLSMasterPlaylist *playlist;
1841 playlist = g_new0 (GstHLSMasterPlaylist, 1);
1842 playlist->refcount = 1;
1843 playlist->is_simple = FALSE;
1849 hls_master_playlist_unref (GstHLSMasterPlaylist * playlist)
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);
1866 hls_media_compare_func (GstHLSRenditionStream * ma, GstHLSRenditionStream * mb)
1868 if (ma->mtype != mb->mtype)
1869 return ma->mtype - mb->mtype;
1871 return strcmp (ma->name, mb->name) || strcmp (ma->group_id, mb->group_id);
1875 stream_get_media_caps (GstHLSVariantStream * stream,
1876 GstHLSRenditionStreamType mtype)
1878 GstStructure *st = NULL;
1882 if (stream->caps == NULL)
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);
1892 case GST_HLS_RENDITION_STREAM_TYPE_AUDIO:
1893 matched = g_str_has_prefix (name, "audio/");
1895 case GST_HLS_RENDITION_STREAM_TYPE_VIDEO:
1896 matched = g_str_has_prefix (name, "video/");
1898 case GST_HLS_RENDITION_STREAM_TYPE_SUBTITLES:
1899 matched = g_str_has_prefix (name, "application/x-subtitle");
1910 GST_WARNING ("More than one caps for the same type, can't match");
1920 ret = gst_caps_new_empty ();
1921 gst_caps_append_structure (ret, gst_structure_copy (st));
1927 gst_hls_variant_stream_compare_by_bitrate (gconstpointer a, gconstpointer b)
1929 const GstHLSVariantStream *vs_a = (const GstHLSVariantStream *) a;
1930 const GstHLSVariantStream *vs_b = (const GstHLSVariantStream *) b;
1932 if (vs_a->bandwidth == vs_b->bandwidth)
1933 return g_strcmp0 (vs_a->name, vs_b->name);
1935 return vs_a->bandwidth - vs_b->bandwidth;
1939 * gst_hls_master_playlist_new_from_data:
1940 * @data: (transfer full): The manifest to parse
1941 * @base_uri: The URI of the manifest
1943 * Parse the provided manifest and construct the master playlist.
1945 * Returns: The parse GstHLSMasterPlaylist , or NULL if there was an error.
1947 GstHLSMasterPlaylist *
1948 hls_master_playlist_new_from_data (gchar * data, const gchar * base_uri)
1950 GstHLSMasterPlaylist *playlist;
1951 GstHLSVariantStream *pending_stream, *existing_stream;
1952 gchar *end, *free_data = data;
1955 GstStreamType most_seen_types = 0;
1957 if (!g_str_has_prefix (data, "#EXTM3U")) {
1958 GST_WARNING ("Data doesn't start with #EXTM3U");
1963 playlist = gst_hls_master_playlist_new ();
1965 /* store data before we modify it for parsing */
1966 playlist->last_data = g_strdup (data);
1968 GST_TRACE ("data:\n%s", data);
1970 /* Detect early whether this manifest describes a simple media playlist or
1972 if (strstr (data, "\n#EXTINF:") != NULL) {
1973 GST_INFO ("This is a simple media playlist, not a master playlist");
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;
1985 /* Beginning of the actual master playlist parsing */
1986 pending_stream = NULL;
1991 end = g_utf8_strchr (data, -1, '\n');
1995 r = g_utf8_strchr (data, -1, '\r');
1999 if (data[0] != '#' && data[0] != '\0') {
2002 if (pending_stream == NULL) {
2003 GST_LOG ("%s: got non-empty line without EXT-STREAM-INF, dropping",
2008 uri = uri_join (base_uri, data);
2012 pending_stream->name = name =
2013 generate_variant_stream_name (uri, pending_stream->bandwidth);
2014 pending_stream->uri = uri;
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,
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);
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);
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);
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);
2051 playlist->iframe_variants =
2052 g_list_append (playlist->iframe_variants, stream);
2055 if (pending_stream != NULL) {
2056 GST_WARNING ("variant stream without uri, dropping");
2057 gst_hls_variant_stream_unref (pending_stream);
2059 pending_stream = stream;
2061 } else if (g_str_has_prefix (data, "#EXT-X-MEDIA:")) {
2062 GstHLSRenditionStream *media;
2064 media = gst_m3u8_parse_media (data + strlen ("#EXT-X-MEDIA:"), base_uri);
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);
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);
2084 data = g_utf8_next_char (end); /* skip \n */
2087 if (pending_stream != NULL) {
2088 GST_WARNING ("#EXT-X-STREAM-INF without uri, dropping");
2089 gst_hls_variant_stream_unref (pending_stream);
2094 if (playlist->variants == NULL) {
2095 GST_WARNING ("Master playlist without any media playlists!");
2096 gst_hls_master_playlist_unref (playlist);
2100 /* reorder variants by bitrate */
2101 playlist->variants =
2102 g_list_sort (playlist->variants,
2103 (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2105 playlist->iframe_variants =
2106 g_list_sort (playlist->iframe_variants,
2107 (GCompareFunc) gst_hls_variant_stream_compare_by_bitrate);
2109 #ifndef GST_DISABLE_GST_DEBUG
2110 /* Sanity check : If there are no codecs, a stream shouldn't point to
2111 * alternate rendition groups.
2113 * Write a warning to help with further debugging if this causes issues
2115 for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2116 GstHLSVariantStream *stream = tmp->data;
2118 if (stream->codecs == NULL) {
2119 if (stream->media_groups[0] || stream->media_groups[1]
2120 || stream->media_groups[2] || stream->media_groups[3]) {
2122 ("Variant specifies alternate rendition groups but has no codecs specified");
2128 /* Filter out audio-only variants from audio+video stream */
2129 for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2130 GstHLSVariantStream *stream = tmp->data;
2132 most_seen_types |= stream->codecs_stream_type;
2135 /* Flag the playlist to indicate whether all codecs are known or not on variants */
2136 playlist->have_codecs = most_seen_types != 0;
2138 GST_DEBUG ("have_codecs:%d most_seen_types:%d", playlist->have_codecs,
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;
2145 GstHLSVariantStream *stream = tmp->data;
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);
2157 if (playlist->renditions) {
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;
2164 GST_DEBUG ("Post-processing Variant Stream '%s'", stream->name);
2166 for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
2167 gchar *alt_rend_group = stream->media_groups[i];
2169 if (alt_rend_group) {
2170 gboolean alt_in_variant = FALSE;
2171 GstCaps *media_caps = stream_get_media_caps (stream, i);
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))
2180 GST_DEBUG (" %s caps:%" GST_PTR_FORMAT " media %s, uri: %s",
2181 GST_HLS_RENDITION_STREAM_TYPE_NAME (i), media_caps, media->name,
2183 if (media->uri == NULL) {
2184 GST_DEBUG (" Media is present in main variant stream");
2185 alt_in_variant = TRUE;
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);
2192 GST_DEBUG (" Assigning caps %" GST_PTR_FORMAT, media_caps);
2193 gst_caps_replace (&media->caps, media_caps);
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);
2202 gst_caps_unref (media_caps);
2205 GST_DEBUG ("Stream Ends up with caps %" GST_PTR_FORMAT, stream->caps);
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));
2219 GstHLSVariantStream *
2220 hls_master_playlist_get_variant_for_bitrate (GstHLSMasterPlaylist *
2221 playlist, GstHLSVariantStream * current_variant, guint bitrate,
2224 GstHLSVariantStream *variant = current_variant;
2225 GstHLSVariantStream *variant_by_min = current_variant;
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);
2232 l = g_list_last (playlist->iframe_variants);
2236 if (variant->bandwidth >= min_bitrate)
2237 variant_by_min = variant;
2238 if (variant->bandwidth <= bitrate)
2243 /* If variant bitrate is above the min_bitrate (or min_bitrate == 0)
2245 if (variant && variant->bandwidth >= min_bitrate)
2248 /* Otherwise, return the last (lowest bitrate) variant we saw that
2249 * was higher than the min_bitrate */
2250 return variant_by_min;
2254 remove_uncommon (GQuark field_id, GValue * value, GstStructure * st2)
2256 const GValue *other;
2257 GValue dest = G_VALUE_INIT;
2259 other = gst_structure_id_get_value (st2, field_id);
2261 if (other == NULL || (G_VALUE_TYPE (value) != G_VALUE_TYPE (other)))
2264 if (!gst_value_intersect (&dest, value, other))
2267 g_value_reset (value);
2268 g_value_copy (&dest, value);
2269 g_value_reset (&dest);
2274 /* Merge all common structures from caps1 and caps2
2276 * Returns empty caps if a structure is not present in both */
2278 gst_caps_merge_common (GstCaps * caps1, GstCaps * caps2)
2281 GstCaps *res = gst_caps_new_empty ();
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);
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)) {
2292 merged = gst_structure_copy (st1);
2293 gst_structure_filter_and_map_in_place (merged,
2294 (GstStructureFilterMapFunc) remove_uncommon, st2);
2300 gst_caps_append_structure (res, merged);
2307 GST_WARNING ("Failed to create common caps of %"
2308 GST_PTR_FORMAT " and %" GST_PTR_FORMAT, caps1, caps2);
2309 gst_caps_unref (res);
2315 hls_master_playlist_get_common_caps (GstHLSMasterPlaylist * playlist)
2318 GstCaps *res = NULL;
2320 for (tmp = playlist->variants; tmp; tmp = tmp->next) {
2321 GstHLSVariantStream *stream = tmp->data;
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 */
2328 gst_caps_unref (res);
2333 res = gst_caps_copy (stream->caps);
2335 GstCaps *common_caps = gst_caps_merge_common (res, stream->caps);
2336 gst_caps_unref (res);
2343 res = gst_caps_simplify (res);
2346 GST_DEBUG ("Returning common caps %" GST_PTR_FORMAT, res);
2352 gst_stream_type_from_hls_type (GstHLSRenditionStreamType 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;
2362 return GST_STREAM_TYPE_UNKNOWN;