1a5c6103f35bc1060f48df2235ee3cf57c4780c4
[platform/upstream/gstreamer.git] / ext / hls / gsthlsdemux.c
1 /* GStreamer
2  * Copyright (C) 2010 Marc-Andre Lureau <marcandre.lureau@gmail.com>
3  * Copyright (C) 2010 Andoni Morales Alastruey <ylatuya@gmail.com>
4  * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
5  *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
6  *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
7  * Copyright (C) 2014 Sebastian Dröge <sebastian@centricular.com>
8  * Copyright (C) 2015 Tim-Philipp Müller <tim@centricular.com>
9  *
10  * Gsthlsdemux.c:
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Library General Public
14  * License as published by the Free Software Foundation; either
15  * version 2 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with this library; if not, write to the
24  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
25  * Boston, MA 02110-1301, USA.
26  */
27 /**
28  * SECTION:element-hlsdemux
29  *
30  * HTTP Live Streaming demuxer element.
31  *
32  * <refsect2>
33  * <title>Example launch line</title>
34  * |[
35  * gst-launch-1.0 souphttpsrc location=http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8 ! hlsdemux ! decodebin ! videoconvert ! videoscale ! autovideosink
36  * ]|
37  * </refsect2>
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #  include "config.h"
42 #endif
43
44 #include <string.h>
45 #include <gst/base/gsttypefindhelper.h>
46 #include "gsthlsdemux.h"
47
48 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
49     GST_PAD_SRC,
50     GST_PAD_SOMETIMES,
51     GST_STATIC_CAPS_ANY);
52
53 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
54     GST_PAD_SINK,
55     GST_PAD_ALWAYS,
56     GST_STATIC_CAPS ("application/x-hls"));
57
58 GST_DEBUG_CATEGORY_STATIC (gst_hls_demux_debug);
59 #define GST_CAT_DEFAULT gst_hls_demux_debug
60
61 #define GST_M3U8_CLIENT_LOCK(l) /* FIXME */
62 #define GST_M3U8_CLIENT_UNLOCK(l)       /* FIXME */
63
64 /* GObject */
65 static void gst_hls_demux_finalize (GObject * obj);
66
67 /* GstElement */
68 static GstStateChangeReturn
69 gst_hls_demux_change_state (GstElement * element, GstStateChange transition);
70
71 /* GstHLSDemux */
72 static gboolean gst_hls_demux_update_playlist (GstHLSDemux * demux,
73     gboolean update, GError ** err);
74 static gchar *gst_hls_src_buf_to_utf8_playlist (GstBuffer * buf);
75
76 static gboolean gst_hls_demux_change_playlist (GstHLSDemux * demux,
77     guint max_bitrate, gboolean * changed);
78 static GstBuffer *gst_hls_demux_decrypt_fragment (GstHLSDemux * demux,
79     GstHLSDemuxStream * stream, GstBuffer * encrypted_buffer, GError ** err);
80 static gboolean
81 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
82     const guint8 * key_data, const guint8 * iv_data);
83 static void gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream);
84
85 static gboolean gst_hls_demux_is_live (GstAdaptiveDemux * demux);
86 static GstClockTime gst_hls_demux_get_duration (GstAdaptiveDemux * demux);
87 static gint64 gst_hls_demux_get_manifest_update_interval (GstAdaptiveDemux *
88     demux);
89 static gboolean gst_hls_demux_process_manifest (GstAdaptiveDemux * demux,
90     GstBuffer * buf);
91 static GstFlowReturn gst_hls_demux_update_manifest (GstAdaptiveDemux * demux);
92 static gboolean gst_hls_demux_seek (GstAdaptiveDemux * demux, GstEvent * seek);
93 static gboolean
94 gst_hls_demux_start_fragment (GstAdaptiveDemux * demux,
95     GstAdaptiveDemuxStream * stream);
96 static GstFlowReturn gst_hls_demux_finish_fragment (GstAdaptiveDemux * demux,
97     GstAdaptiveDemuxStream * stream);
98 static GstFlowReturn gst_hls_demux_data_received (GstAdaptiveDemux * demux,
99     GstAdaptiveDemuxStream * stream, GstBuffer * buffer);
100 static void gst_hls_demux_stream_free (GstAdaptiveDemuxStream * stream);
101 static gboolean gst_hls_demux_stream_has_next_fragment (GstAdaptiveDemuxStream *
102     stream);
103 static GstFlowReturn gst_hls_demux_advance_fragment (GstAdaptiveDemuxStream *
104     stream);
105 static GstFlowReturn gst_hls_demux_update_fragment_info (GstAdaptiveDemuxStream
106     * stream);
107 static gboolean gst_hls_demux_select_bitrate (GstAdaptiveDemuxStream * stream,
108     guint64 bitrate);
109 static void gst_hls_demux_reset (GstAdaptiveDemux * demux);
110 static gboolean gst_hls_demux_get_live_seek_range (GstAdaptiveDemux * demux,
111     gint64 * start, gint64 * stop);
112 static GstM3U8 *gst_hls_demux_stream_get_m3u8 (GstHLSDemuxStream * hls_stream);
113 static void gst_hls_demux_set_current_variant (GstHLSDemux * hlsdemux,
114     GstHLSVariantStream * variant);
115
116 #define gst_hls_demux_parent_class parent_class
117 G_DEFINE_TYPE (GstHLSDemux, gst_hls_demux, GST_TYPE_ADAPTIVE_DEMUX);
118
119 static void
120 gst_hls_demux_finalize (GObject * obj)
121 {
122   GstHLSDemux *demux = GST_HLS_DEMUX (obj);
123
124   gst_hls_demux_reset (GST_ADAPTIVE_DEMUX_CAST (demux));
125   g_mutex_clear (&demux->keys_lock);
126
127   G_OBJECT_CLASS (parent_class)->finalize (obj);
128 }
129
130 static void
131 gst_hls_demux_class_init (GstHLSDemuxClass * klass)
132 {
133   GObjectClass *gobject_class;
134   GstElementClass *element_class;
135   GstAdaptiveDemuxClass *adaptivedemux_class;
136
137   gobject_class = (GObjectClass *) klass;
138   element_class = (GstElementClass *) klass;
139   adaptivedemux_class = (GstAdaptiveDemuxClass *) klass;
140
141   gobject_class->finalize = gst_hls_demux_finalize;
142
143   element_class->change_state = GST_DEBUG_FUNCPTR (gst_hls_demux_change_state);
144
145   gst_element_class_add_static_pad_template (element_class, &srctemplate);
146   gst_element_class_add_static_pad_template (element_class, &sinktemplate);
147
148   gst_element_class_set_static_metadata (element_class,
149       "HLS Demuxer",
150       "Codec/Demuxer/Adaptive",
151       "HTTP Live Streaming demuxer",
152       "Marc-Andre Lureau <marcandre.lureau@gmail.com>\n"
153       "Andoni Morales Alastruey <ylatuya@gmail.com>");
154
155   adaptivedemux_class->is_live = gst_hls_demux_is_live;
156   adaptivedemux_class->get_live_seek_range = gst_hls_demux_get_live_seek_range;
157   adaptivedemux_class->get_duration = gst_hls_demux_get_duration;
158   adaptivedemux_class->get_manifest_update_interval =
159       gst_hls_demux_get_manifest_update_interval;
160   adaptivedemux_class->process_manifest = gst_hls_demux_process_manifest;
161   adaptivedemux_class->update_manifest = gst_hls_demux_update_manifest;
162   adaptivedemux_class->reset = gst_hls_demux_reset;
163   adaptivedemux_class->seek = gst_hls_demux_seek;
164   adaptivedemux_class->stream_has_next_fragment =
165       gst_hls_demux_stream_has_next_fragment;
166   adaptivedemux_class->stream_advance_fragment = gst_hls_demux_advance_fragment;
167   adaptivedemux_class->stream_update_fragment_info =
168       gst_hls_demux_update_fragment_info;
169   adaptivedemux_class->stream_select_bitrate = gst_hls_demux_select_bitrate;
170   adaptivedemux_class->stream_free = gst_hls_demux_stream_free;
171
172   adaptivedemux_class->start_fragment = gst_hls_demux_start_fragment;
173   adaptivedemux_class->finish_fragment = gst_hls_demux_finish_fragment;
174   adaptivedemux_class->data_received = gst_hls_demux_data_received;
175
176   GST_DEBUG_CATEGORY_INIT (gst_hls_demux_debug, "hlsdemux", 0,
177       "hlsdemux element");
178 }
179
180 static void
181 gst_hls_demux_init (GstHLSDemux * demux)
182 {
183   gst_adaptive_demux_set_stream_struct_size (GST_ADAPTIVE_DEMUX_CAST (demux),
184       sizeof (GstHLSDemuxStream));
185
186   demux->keys = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
187   g_mutex_init (&demux->keys_lock);
188 }
189
190 static GstStateChangeReturn
191 gst_hls_demux_change_state (GstElement * element, GstStateChange transition)
192 {
193   GstStateChangeReturn ret;
194   GstHLSDemux *demux = GST_HLS_DEMUX (element);
195
196   switch (transition) {
197     case GST_STATE_CHANGE_READY_TO_PAUSED:
198       gst_hls_demux_reset (GST_ADAPTIVE_DEMUX_CAST (demux));
199       break;
200     default:
201       break;
202   }
203
204   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
205
206   switch (transition) {
207     case GST_STATE_CHANGE_PAUSED_TO_READY:
208       gst_hls_demux_reset (GST_ADAPTIVE_DEMUX_CAST (demux));
209       g_hash_table_remove_all (demux->keys);
210       break;
211     default:
212       break;
213   }
214   return ret;
215 }
216
217 static GstPad *
218 gst_hls_demux_create_pad (GstHLSDemux * hlsdemux)
219 {
220   gchar *name;
221   GstPad *pad;
222
223   name = g_strdup_printf ("src_%u", hlsdemux->srcpad_counter++);
224   pad = gst_pad_new_from_static_template (&srctemplate, name);
225   g_free (name);
226
227   return pad;
228 }
229
230 static guint64
231 gst_hls_demux_get_bitrate (GstHLSDemux * hlsdemux)
232 {
233   GstAdaptiveDemux *demux = GST_ADAPTIVE_DEMUX_CAST (hlsdemux);
234
235   /* Valid because hlsdemux only has a single output */
236   if (demux->streams) {
237     GstAdaptiveDemuxStream *stream = demux->streams->data;
238     return stream->current_download_rate;
239   }
240
241   return 0;
242 }
243
244 static void
245 gst_hls_demux_stream_clear_pending_data (GstHLSDemuxStream * hls_stream)
246 {
247   if (hls_stream->pending_encrypted_data)
248     gst_adapter_clear (hls_stream->pending_encrypted_data);
249   gst_buffer_replace (&hls_stream->pending_decrypted_buffer, NULL);
250   gst_buffer_replace (&hls_stream->pending_typefind_buffer, NULL);
251   hls_stream->current_offset = -1;
252   gst_hls_demux_stream_decrypt_end (hls_stream);
253 }
254
255 static void
256 gst_hls_demux_clear_all_pending_data (GstHLSDemux * hlsdemux)
257 {
258   GstAdaptiveDemux *demux = (GstAdaptiveDemux *) hlsdemux;
259   GList *walk;
260
261   for (walk = demux->streams; walk != NULL; walk = walk->next) {
262     GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (walk->data);
263     gst_hls_demux_stream_clear_pending_data (hls_stream);
264   }
265 }
266
267 #if 0
268 static void
269 gst_hls_demux_set_current (GstHLSDemux * self, GstM3U8 * m3u8)
270 {
271   GST_M3U8_CLIENT_LOCK (self);
272   if (m3u8 != self->current) {
273     self->current = m3u8;
274     self->current->duration = GST_CLOCK_TIME_NONE;
275     self->current->current_file = NULL;
276
277 #if 0
278     // FIXME: this makes no sense after we just set self->current=m3u8 above (tpm)
279     // also, these values don't necessarily align between different lists
280     m3u8->current_file_duration = self->current->current_file_duration;
281     m3u8->sequence = self->current->sequence;
282     m3u8->sequence_position = self->current->sequence_position;
283     m3u8->highest_sequence_number = self->current->highest_sequence_number;
284     m3u8->first_file_start = self->current->first_file_start;
285     m3u8->last_file_end = self->current->last_file_end;
286 #endif
287   }
288   GST_M3U8_CLIENT_UNLOCK (self);
289 }
290 #endif
291
292 static gboolean
293 gst_hls_demux_seek (GstAdaptiveDemux * demux, GstEvent * seek)
294 {
295   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
296   GstFormat format;
297   GstSeekFlags flags;
298   GstSeekType start_type, stop_type;
299   gint64 start, stop;
300   gdouble rate, old_rate;
301   GList *walk, *current_file = NULL;
302   GstClockTime current_pos, target_pos;
303   gint64 current_sequence;
304   GstM3U8MediaFile *file;
305   guint64 bitrate;
306   gboolean snap_before, snap_after, snap_nearest, keyunit;
307   gboolean reverse;
308
309   old_rate = demux->segment.rate;
310
311   gst_event_parse_seek (seek, &rate, &format, &flags, &start_type, &start,
312       &stop_type, &stop);
313
314   bitrate = gst_hls_demux_get_bitrate (hlsdemux);
315
316   /* properly cleanup pending decryption status */
317   if (flags & GST_SEEK_FLAG_FLUSH) {
318     gst_hls_demux_clear_all_pending_data (hlsdemux);
319   }
320
321   /* Use I-frame variants for trick modes */
322   if (hlsdemux->master->iframe_variants != NULL
323       && rate < -1.0 && old_rate >= -1.0 && old_rate <= 1.0) {
324     GError *err = NULL;
325
326     /* Switch to I-frame variant */
327     gst_hls_demux_set_current_variant (hlsdemux,
328         hlsdemux->master->iframe_variants->data);
329     gst_uri_downloader_reset (demux->downloader);
330     if (!gst_hls_demux_update_playlist (hlsdemux, FALSE, &err)) {
331       GST_ELEMENT_ERROR_FROM_ERROR (hlsdemux, "Could not switch playlist", err);
332       return FALSE;
333     }
334     //hlsdemux->discont = TRUE;
335
336     gst_hls_demux_change_playlist (hlsdemux, bitrate / ABS (rate), NULL);
337   } else if (rate > -1.0 && rate <= 1.0 && (old_rate < -1.0 || old_rate > 1.0)) {
338     GError *err = NULL;
339     /* Switch to normal variant */
340     gst_hls_demux_set_current_variant (hlsdemux,
341         hlsdemux->master->variants->data);
342     gst_uri_downloader_reset (demux->downloader);
343     if (!gst_hls_demux_update_playlist (hlsdemux, FALSE, &err)) {
344       GST_ELEMENT_ERROR_FROM_ERROR (hlsdemux, "Could not switch playlist", err);
345       return FALSE;
346     }
347     //hlsdemux->discont = TRUE;
348     /* TODO why not continue using the same? that was being used up to now? */
349     gst_hls_demux_change_playlist (hlsdemux, bitrate, NULL);
350   }
351   GST_M3U8_CLIENT_LOCK (hlsdemux->client);
352   file = GST_M3U8_MEDIA_FILE (hlsdemux->current_variant->m3u8->files->data);
353   current_sequence = file->sequence;
354   current_pos = 0;
355   reverse = rate < 0;
356   target_pos = reverse ? stop : start;
357
358   /* Snap to segment boundary. Improves seek performance on slow machines. */
359   keyunit = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
360   snap_nearest =
361       (flags & GST_SEEK_FLAG_SNAP_NEAREST) == GST_SEEK_FLAG_SNAP_NEAREST;
362   snap_before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
363   snap_after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
364
365   /* FIXME: Here we need proper discont handling */
366   for (walk = hlsdemux->current_variant->m3u8->files; walk; walk = walk->next) {
367     file = walk->data;
368
369     current_sequence = file->sequence;
370     current_file = walk;
371     if ((!reverse && snap_after) || snap_nearest) {
372       if (current_pos >= target_pos)
373         break;
374       if (snap_nearest && target_pos - current_pos < file->duration / 2)
375         break;
376     } else if (reverse && snap_after) {
377       /* check if the next fragment is our target, in this case we want to
378        * start from the previous fragment */
379       GstClockTime next_pos = current_pos + file->duration;
380
381       if (next_pos <= target_pos && target_pos < next_pos + file->duration) {
382         break;
383       }
384     } else if (current_pos <= target_pos
385         && target_pos < current_pos + file->duration) {
386       break;
387     }
388     current_pos += file->duration;
389   }
390
391   if (walk == NULL) {
392     GST_DEBUG_OBJECT (demux, "seeking further than track duration");
393     current_sequence++;
394   }
395
396   GST_DEBUG_OBJECT (demux, "seeking to sequence %u", (guint) current_sequence);
397   for (walk = demux->streams; walk != NULL; walk = walk->next)
398     GST_HLS_DEMUX_STREAM_CAST (walk->data)->reset_pts = TRUE;
399   hlsdemux->current_variant->m3u8->sequence = current_sequence;
400   hlsdemux->current_variant->m3u8->current_file =
401       current_file ? current_file : hlsdemux->current_variant->m3u8->files;
402   hlsdemux->current_variant->m3u8->sequence_position = current_pos;
403   GST_M3U8_CLIENT_UNLOCK (hlsdemux->client);
404
405   /* Play from the end of the current selected segment */
406   if (reverse && (snap_before || snap_after || snap_nearest))
407     current_pos += file->duration;
408
409   if (keyunit || snap_before || snap_after || snap_nearest) {
410     if (!reverse)
411       gst_segment_do_seek (&demux->segment, rate, format, flags, start_type,
412           current_pos, stop_type, stop, NULL);
413     else
414       gst_segment_do_seek (&demux->segment, rate, format, flags, start_type,
415           start, stop_type, current_pos, NULL);
416   }
417
418   return TRUE;
419 }
420
421 static GstFlowReturn
422 gst_hls_demux_update_manifest (GstAdaptiveDemux * demux)
423 {
424   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
425   if (!gst_hls_demux_update_playlist (hlsdemux, TRUE, NULL))
426     return GST_FLOW_ERROR;
427
428   return GST_FLOW_OK;
429 }
430
431 static gboolean
432 gst_hls_demux_setup_streams (GstAdaptiveDemux * demux)
433 {
434   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
435   GstAdaptiveDemuxStream *stream;
436   GstHLSDemuxStream *hlsdemux_stream;
437
438   /* only 1 output supported */
439   gst_hls_demux_clear_all_pending_data (hlsdemux);
440   stream = gst_adaptive_demux_stream_new (demux,
441       gst_hls_demux_create_pad (hlsdemux));
442
443   hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
444
445   hlsdemux_stream->do_typefind = TRUE;
446   hlsdemux_stream->reset_pts = TRUE;
447
448   return TRUE;
449 }
450
451 static const gchar *
452 gst_adaptive_demux_get_manifest_ref_uri (GstAdaptiveDemux * d)
453 {
454   return d->manifest_base_uri ? d->manifest_base_uri : d->manifest_uri;
455 }
456
457 static void
458 gst_hls_demux_set_current_variant (GstHLSDemux * hlsdemux,
459     GstHLSVariantStream * variant)
460 {
461   if (hlsdemux->current_variant == variant || variant == NULL)
462     return;
463
464   if (hlsdemux->current_variant != NULL) {
465     gint i;
466
467     //#warning FIXME: Synching fragments across variants
468     //  should be done based on media timestamps, and
469     //  discont-sequence-numbers not sequence numbers.
470     variant->m3u8->sequence_position =
471         hlsdemux->current_variant->m3u8->sequence_position;
472     variant->m3u8->sequence = hlsdemux->current_variant->m3u8->sequence;
473
474     GST_DEBUG_OBJECT (hlsdemux,
475         "Switching Variant. Copying over sequence %" G_GINT64_FORMAT
476         " and sequence_pos %" GST_TIME_FORMAT, variant->m3u8->sequence,
477         GST_TIME_ARGS (variant->m3u8->sequence_position));
478
479     for (i = 0; i < GST_HLS_N_MEDIA_TYPES; ++i) {
480       GList *mlist = hlsdemux->current_variant->media[i];
481
482       while (mlist != NULL) {
483         GstHLSMedia *old_media = mlist->data;
484         GstHLSMedia *new_media =
485             gst_hls_variant_find_matching_media (variant, old_media);
486
487         if (new_media) {
488           new_media->playlist->sequence = old_media->playlist->sequence;
489           new_media->playlist->sequence_position =
490               old_media->playlist->sequence_position;
491         }
492         mlist = mlist->next;
493       }
494     }
495
496     gst_hls_variant_stream_unref (hlsdemux->current_variant);
497   }
498
499   hlsdemux->current_variant = gst_hls_variant_stream_ref (variant);
500
501 }
502
503 static gboolean
504 gst_hls_demux_process_manifest (GstAdaptiveDemux * demux, GstBuffer * buf)
505 {
506   GstHLSVariantStream *variant;
507   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
508   gchar *playlist = NULL;
509
510   GST_INFO_OBJECT (demux, "Initial playlist location: %s (base uri: %s)",
511       demux->manifest_uri, demux->manifest_base_uri);
512
513   playlist = gst_hls_src_buf_to_utf8_playlist (buf);
514   if (playlist == NULL) {
515     GST_WARNING_OBJECT (demux, "Error validating initial playlist");
516     return FALSE;
517   }
518
519   hlsdemux->master = gst_hls_master_playlist_new_from_data (playlist,
520       gst_adaptive_demux_get_manifest_ref_uri (demux));
521
522   if (hlsdemux->master == NULL || hlsdemux->master->variants == NULL) {
523     /* In most cases, this will happen if we set a wrong url in the
524      * source element and we have received the 404 HTML response instead of
525      * the playlist */
526     GST_ELEMENT_ERROR (demux, STREAM, DECODE, ("Invalid playlist."),
527         ("Could not parse playlist. Check if the URL is correct."));
528     return FALSE;
529   }
530
531   /* select the initial variant stream */
532   if (demux->connection_speed == 0) {
533     variant = hlsdemux->master->default_variant;
534   } else {
535     variant =
536         gst_hls_master_playlist_get_variant_for_bitrate (hlsdemux->master,
537         NULL, demux->connection_speed);
538   }
539
540   GST_INFO_OBJECT (hlsdemux, "selected %s", variant->name);
541   gst_hls_demux_set_current_variant (hlsdemux, variant);        // FIXME: inline?
542
543   /* get the selected media playlist (unless the inital list was one already) */
544   if (!hlsdemux->master->is_simple) {
545     GError *err = NULL;
546
547     if (!gst_hls_demux_update_playlist (hlsdemux, FALSE, &err)) {
548       GST_ELEMENT_ERROR_FROM_ERROR (demux, "Could not fetch media playlist",
549           err);
550       return FALSE;
551     }
552   }
553
554   return gst_hls_demux_setup_streams (demux);
555 }
556
557 static GstClockTime
558 gst_hls_demux_get_duration (GstAdaptiveDemux * demux)
559 {
560   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
561   GstClockTime duration = GST_CLOCK_TIME_NONE;
562
563   if (hlsdemux->current_variant != NULL)
564     duration = gst_m3u8_get_duration (hlsdemux->current_variant->m3u8);
565
566   return duration;
567 }
568
569 static gboolean
570 gst_hls_demux_is_live (GstAdaptiveDemux * demux)
571 {
572   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
573   gboolean is_live = FALSE;
574
575   if (hlsdemux->current_variant)
576     is_live = gst_hls_variant_stream_is_live (hlsdemux->current_variant);
577
578   return is_live;
579 }
580
581 static const GstHLSKey *
582 gst_hls_demux_get_key (GstHLSDemux * demux, const gchar * key_url,
583     const gchar * referer, gboolean allow_cache)
584 {
585   GstFragment *key_fragment;
586   GstBuffer *key_buffer;
587   GstHLSKey *key;
588   GError *err = NULL;
589
590   GST_LOG_OBJECT (demux, "Looking up key for key url %s", key_url);
591
592   g_mutex_lock (&demux->keys_lock);
593
594   key = g_hash_table_lookup (demux->keys, key_url);
595
596   if (key != NULL) {
597     GST_LOG_OBJECT (demux, "Found key for key url %s in key cache", key_url);
598     goto out;
599   }
600
601   GST_INFO_OBJECT (demux, "Fetching key %s", key_url);
602
603   key_fragment =
604       gst_uri_downloader_fetch_uri (GST_ADAPTIVE_DEMUX (demux)->downloader,
605       key_url, referer, FALSE, FALSE, allow_cache, &err);
606
607   if (key_fragment == NULL) {
608     GST_WARNING_OBJECT (demux, "Failed to download key to decrypt data: %s",
609         err ? err->message : "error");
610     g_clear_error (&err);
611     goto out;
612   }
613
614   key_buffer = gst_fragment_get_buffer (key_fragment);
615
616   key = g_new0 (GstHLSKey, 1);
617   if (gst_buffer_extract (key_buffer, 0, key->data, 16) < 16)
618     GST_WARNING_OBJECT (demux, "Download decryption key is too short!");
619
620   g_hash_table_insert (demux->keys, g_strdup (key_url), key);
621
622   gst_buffer_unref (key_buffer);
623   g_object_unref (key_fragment);
624
625 out:
626
627   g_mutex_unlock (&demux->keys_lock);
628
629   if (key != NULL)
630     GST_MEMDUMP_OBJECT (demux, "Key", key->data, 16);
631
632   return key;
633 }
634
635 static gboolean
636 gst_hls_demux_start_fragment (GstAdaptiveDemux * demux,
637     GstAdaptiveDemuxStream * stream)
638 {
639   GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
640   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
641   const GstHLSKey *key;
642   GstM3U8 *m3u8;
643
644   gst_hls_demux_stream_clear_pending_data (hls_stream);
645
646   /* If no decryption is needed, there's nothing to be done here */
647   if (hls_stream->current_key == NULL)
648     return TRUE;
649
650   m3u8 = gst_hls_demux_stream_get_m3u8 (hls_stream);
651
652   key = gst_hls_demux_get_key (hlsdemux, hls_stream->current_key,
653       m3u8->uri, m3u8->allowcache);
654
655   if (key == NULL)
656     goto key_failed;
657
658   gst_hls_demux_stream_decrypt_start (hls_stream, key->data,
659       hls_stream->current_iv);
660
661   return TRUE;
662
663 key_failed:
664   {
665     GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
666         ("Couldn't retrieve key for decryption"), (NULL));
667     GST_WARNING_OBJECT (demux, "Failed to decrypt data");
668     return FALSE;
669   }
670 }
671
672 static GstFlowReturn
673 gst_hls_demux_handle_buffer (GstAdaptiveDemux * demux,
674     GstAdaptiveDemuxStream * stream, GstBuffer * buffer, gboolean force)
675 {
676   GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);   // FIXME: pass HlsStream into function
677   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
678
679   if (buffer == NULL)
680     return GST_FLOW_OK;
681
682   if (G_UNLIKELY (hls_stream->do_typefind)) {
683     GstCaps *caps = NULL;
684     GstMapInfo info;
685     guint buffer_size;
686     GstTypeFindProbability prob = GST_TYPE_FIND_NONE;
687
688     if (hls_stream->pending_typefind_buffer)
689       buffer = gst_buffer_append (hls_stream->pending_typefind_buffer, buffer);
690     hls_stream->pending_typefind_buffer = NULL;
691
692     gst_buffer_map (buffer, &info, GST_MAP_READ);
693     buffer_size = info.size;
694
695     /* Typefind could miss if buffer is too small. In this case we
696      * will retry later */
697     if (buffer_size >= (2 * 1024)) {
698       caps =
699           gst_type_find_helper_for_data (GST_OBJECT_CAST (hlsdemux), info.data,
700           info.size, &prob);
701     }
702     gst_buffer_unmap (buffer, &info);
703
704     if (G_UNLIKELY (!caps)) {
705       /* Only fail typefinding if we already a good amount of data
706        * and we still don't know the type */
707       if (buffer_size > (2 * 1024 * 1024) || force) {
708         GST_ELEMENT_ERROR (hlsdemux, STREAM, TYPE_NOT_FOUND,
709             ("Could not determine type of stream"), (NULL));
710         gst_buffer_unref (buffer);
711         return GST_FLOW_NOT_NEGOTIATED;
712       }
713
714       hls_stream->pending_typefind_buffer = buffer;
715
716       return GST_FLOW_OK;
717     }
718
719     GST_DEBUG_OBJECT (hlsdemux, "Typefind result: %" GST_PTR_FORMAT " prob:%d",
720         caps, prob);
721
722     gst_adaptive_demux_stream_set_caps (stream, caps);
723     hls_stream->do_typefind = FALSE;
724   }
725   g_assert (hls_stream->pending_typefind_buffer == NULL);
726
727   if (buffer) {
728     buffer = gst_buffer_make_writable (buffer);
729     GST_BUFFER_OFFSET (buffer) = hls_stream->current_offset;
730     hls_stream->current_offset += gst_buffer_get_size (buffer);
731     GST_BUFFER_OFFSET_END (buffer) = hls_stream->current_offset;
732     return gst_adaptive_demux_stream_push_buffer (stream, buffer);
733   }
734   return GST_FLOW_OK;
735 }
736
737 static GstFlowReturn
738 gst_hls_demux_finish_fragment (GstAdaptiveDemux * demux,
739     GstAdaptiveDemuxStream * stream)
740 {
741   GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);   // FIXME: pass HlsStream into function
742   GstFlowReturn ret = GST_FLOW_OK;
743
744   if (hls_stream->current_key)
745     gst_hls_demux_stream_decrypt_end (hls_stream);
746
747   if (stream->last_ret == GST_FLOW_OK) {
748     if (hls_stream->pending_decrypted_buffer) {
749       if (hls_stream->current_key) {
750         GstMapInfo info;
751         gssize unpadded_size;
752
753         /* Handle pkcs7 unpadding here */
754         gst_buffer_map (hls_stream->pending_decrypted_buffer, &info,
755             GST_MAP_READ);
756         unpadded_size = info.size - info.data[info.size - 1];
757         gst_buffer_unmap (hls_stream->pending_decrypted_buffer, &info);
758
759         gst_buffer_resize (hls_stream->pending_decrypted_buffer, 0,
760             unpadded_size);
761       }
762
763       ret =
764           gst_hls_demux_handle_buffer (demux, stream,
765           hls_stream->pending_decrypted_buffer, TRUE);
766       hls_stream->pending_decrypted_buffer = NULL;
767     }
768   }
769   gst_hls_demux_stream_clear_pending_data (hls_stream);
770
771   if (ret == GST_FLOW_OK || ret == GST_FLOW_NOT_LINKED)
772     return gst_adaptive_demux_stream_advance_fragment (demux, stream,
773         stream->fragment.duration);
774   return ret;
775 }
776
777 static GstFlowReturn
778 gst_hls_demux_data_received (GstAdaptiveDemux * demux,
779     GstAdaptiveDemuxStream * stream, GstBuffer * buffer)
780 {
781   GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
782   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
783
784   if (hls_stream->current_offset == -1)
785     hls_stream->current_offset = 0;
786
787   /* Is it encrypted? */
788   if (hls_stream->current_key) {
789     GError *err = NULL;
790     gsize size;
791     GstBuffer *tmp_buffer;
792
793     if (hls_stream->pending_encrypted_data == NULL)
794       hls_stream->pending_encrypted_data = gst_adapter_new ();
795
796     gst_adapter_push (hls_stream->pending_encrypted_data, buffer);
797     size = gst_adapter_available (hls_stream->pending_encrypted_data);
798
799     /* must be a multiple of 16 */
800     size &= (~0xF);
801
802     if (size == 0) {
803       return GST_FLOW_OK;
804     }
805
806     buffer = gst_adapter_take_buffer (hls_stream->pending_encrypted_data, size);
807     buffer =
808         gst_hls_demux_decrypt_fragment (hlsdemux, hls_stream, buffer, &err);
809     if (buffer == NULL) {
810       GST_ELEMENT_ERROR (demux, STREAM, DECODE, ("Failed to decrypt buffer"),
811           ("decryption failed %s", err->message));
812       g_error_free (err);
813       return GST_FLOW_ERROR;
814     }
815
816     tmp_buffer = hls_stream->pending_decrypted_buffer;
817     hls_stream->pending_decrypted_buffer = buffer;
818     buffer = tmp_buffer;
819   }
820
821   return gst_hls_demux_handle_buffer (demux, stream, buffer, FALSE);
822 }
823
824 static void
825 gst_hls_demux_stream_free (GstAdaptiveDemuxStream * stream)
826 {
827   GstHLSDemuxStream *hls_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
828
829   if (hls_stream->pending_encrypted_data)
830     g_object_unref (hls_stream->pending_encrypted_data);
831
832   gst_buffer_replace (&hls_stream->pending_decrypted_buffer, NULL);
833   gst_buffer_replace (&hls_stream->pending_typefind_buffer, NULL);
834
835   if (hls_stream->current_key) {
836     g_free (hls_stream->current_key);
837     hls_stream->current_key = NULL;
838   }
839   if (hls_stream->current_iv) {
840     g_free (hls_stream->current_iv);
841     hls_stream->current_iv = NULL;
842   }
843   gst_hls_demux_stream_decrypt_end (hls_stream);
844 }
845
846 static GstM3U8 *
847 gst_hls_demux_stream_get_m3u8 (GstHLSDemuxStream * hlsdemux_stream)
848 {
849   GstAdaptiveDemuxStream *stream = (GstAdaptiveDemuxStream *) hlsdemux_stream;
850   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
851   GstM3U8 *m3u8;
852
853   g_assert (hlsdemux->current_variant != NULL);
854
855   // FIXME: what about locking? should always be called with lock
856   // that makes sure playlist aren't changed while we do things
857   m3u8 = hlsdemux->current_variant->m3u8;
858
859   return m3u8;
860 }
861
862 static gboolean
863 gst_hls_demux_stream_has_next_fragment (GstAdaptiveDemuxStream * stream)
864 {
865   gboolean has_next;
866   GstM3U8 *m3u8;
867
868   m3u8 = gst_hls_demux_stream_get_m3u8 (GST_HLS_DEMUX_STREAM_CAST (stream));
869
870   has_next = gst_m3u8_has_next_fragment (m3u8, stream->demux->segment.rate > 0);
871
872   return has_next;
873 }
874
875 static GstFlowReturn
876 gst_hls_demux_advance_fragment (GstAdaptiveDemuxStream * stream)
877 {
878   GstHLSDemuxStream *hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
879   GstM3U8 *m3u8;
880
881   m3u8 = gst_hls_demux_stream_get_m3u8 (hlsdemux_stream);
882
883   gst_m3u8_advance_fragment (m3u8, stream->demux->segment.rate > 0);
884   hlsdemux_stream->reset_pts = FALSE;
885
886   return GST_FLOW_OK;
887 }
888
889 static GstFlowReturn
890 gst_hls_demux_update_fragment_info (GstAdaptiveDemuxStream * stream)
891 {
892   GstHLSDemuxStream *hlsdemux_stream = GST_HLS_DEMUX_STREAM_CAST (stream);
893   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
894   GstM3U8MediaFile *file;
895   GstClockTime sequence_pos;
896   gboolean discont, forward;
897   GstM3U8 *m3u8;
898
899   m3u8 = gst_hls_demux_stream_get_m3u8 (hlsdemux_stream);
900
901   forward = (stream->demux->segment.rate > 0);
902   file = gst_m3u8_get_next_fragment (m3u8, forward, &sequence_pos, &discont);
903
904   if (file == NULL) {
905     GST_INFO_OBJECT (hlsdemux, "This playlist doesn't contain more fragments");
906     return GST_FLOW_EOS;
907   }
908
909   if (stream->discont)
910     discont = TRUE;
911
912   /* set up our source for download */
913   if (hlsdemux_stream->reset_pts || discont
914       || stream->demux->segment.rate < 0.0) {
915     stream->fragment.timestamp = sequence_pos;
916   } else {
917     stream->fragment.timestamp = GST_CLOCK_TIME_NONE;
918   }
919
920   g_free (hlsdemux_stream->current_key);
921   hlsdemux_stream->current_key = g_strdup (file->key);
922   g_free (hlsdemux_stream->current_iv);
923   hlsdemux_stream->current_iv = g_memdup (file->iv, sizeof (file->iv));
924
925   g_free (stream->fragment.uri);
926   stream->fragment.uri = g_strdup (file->uri);
927
928   GST_DEBUG_OBJECT (stream, "URI now %s", file->uri);
929
930   stream->fragment.range_start = file->offset;
931   if (file->size != -1)
932     stream->fragment.range_end = file->offset + file->size - 1;
933   else
934     stream->fragment.range_end = -1;
935
936   stream->fragment.duration = file->duration;
937
938   if (discont)
939     stream->discont = TRUE;
940
941   return GST_FLOW_OK;
942 }
943
944 static gboolean
945 gst_hls_demux_select_bitrate (GstAdaptiveDemuxStream * stream, guint64 bitrate)
946 {
947   GstAdaptiveDemux *demux = GST_ADAPTIVE_DEMUX_CAST (stream->demux);
948   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (stream->demux);
949   gboolean changed = FALSE;
950
951   GST_M3U8_CLIENT_LOCK (hlsdemux->client);
952   if (hlsdemux->master->is_simple) {
953     GST_M3U8_CLIENT_UNLOCK (hlsdemux->client);
954     return FALSE;
955   }
956   GST_M3U8_CLIENT_UNLOCK (hlsdemux->client);
957
958   /* Bitrate adaptation during trick modes does not work well */
959   if (demux->segment.rate != 1.0)
960     return FALSE;
961
962   gst_hls_demux_change_playlist (hlsdemux, bitrate, &changed);
963   if (changed)
964     gst_hls_demux_setup_streams (GST_ADAPTIVE_DEMUX_CAST (hlsdemux));
965   return changed;
966 }
967
968 static void
969 gst_hls_demux_reset (GstAdaptiveDemux * ademux)
970 {
971   GstHLSDemux *demux = GST_HLS_DEMUX_CAST (ademux);
972
973   if (demux->master) {
974     gst_hls_master_playlist_unref (demux->master);
975     demux->master = NULL;
976   }
977   if (demux->current_variant != NULL) {
978     gst_hls_variant_stream_unref (demux->current_variant);
979     demux->current_variant = NULL;
980   }
981   demux->srcpad_counter = 0;
982
983   gst_hls_demux_clear_all_pending_data (demux);
984 }
985
986 static gchar *
987 gst_hls_src_buf_to_utf8_playlist (GstBuffer * buf)
988 {
989   GstMapInfo info;
990   gchar *playlist;
991
992   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
993     goto map_error;
994
995   if (!g_utf8_validate ((gchar *) info.data, info.size, NULL))
996     goto validate_error;
997
998   /* alloc size + 1 to end with a null character */
999   playlist = g_malloc0 (info.size + 1);
1000   memcpy (playlist, info.data, info.size);
1001
1002   gst_buffer_unmap (buf, &info);
1003   return playlist;
1004
1005 validate_error:
1006   gst_buffer_unmap (buf, &info);
1007 map_error:
1008   return NULL;
1009 }
1010
1011 static gint
1012 gst_hls_demux_find_variant_match (const GstHLSVariantStream * a,
1013     const GstHLSVariantStream * b)
1014 {
1015   if (g_strcmp0 (a->name, b->name) == 0 &&
1016       a->bandwidth == b->bandwidth &&
1017       a->program_id == b->program_id &&
1018       g_strcmp0 (a->codecs, b->codecs) == 0 &&
1019       a->width == b->width &&
1020       a->height == b->height && a->iframe == b->iframe) {
1021     return 0;
1022   }
1023
1024   return 1;
1025 }
1026
1027 static gboolean
1028 gst_hls_demux_update_variant_playlist (GstHLSDemux * hlsdemux, gchar * data,
1029     const gchar * uri, const gchar * base_uri)
1030 {
1031   GstHLSMasterPlaylist *new_master, *old;
1032   gboolean ret = FALSE;
1033   GList *l, *unmatched_lists;
1034   GstHLSVariantStream *new_variant;
1035
1036   new_master = gst_hls_master_playlist_new_from_data (data, base_uri ? base_uri : uri); // FIXME: check which uri to use here
1037
1038   if (new_master == NULL)
1039     return ret;
1040
1041   if (new_master->is_simple) {
1042     // FIXME: we should be able to support this though, in the unlikely
1043     // case that it changed?
1044     GST_ERROR
1045         ("Cannot update variant playlist: New playlist is not a variant playlist");
1046     gst_hls_master_playlist_unref (new_master);
1047     return FALSE;
1048   }
1049
1050   GST_M3U8_CLIENT_LOCK (self);
1051
1052   if (hlsdemux->master->is_simple) {
1053     GST_ERROR
1054         ("Cannot update variant playlist: Current playlist is not a variant playlist");
1055     goto out;
1056   }
1057
1058   /* Now see if the variant playlist still has the same lists */
1059   unmatched_lists = g_list_copy (hlsdemux->master->variants);
1060   for (l = new_master->variants; l != NULL; l = l->next) {
1061     GList *match = g_list_find_custom (unmatched_lists, l->data,
1062         (GCompareFunc) gst_hls_demux_find_variant_match);
1063
1064     if (match) {
1065       GstHLSVariantStream *variant = l->data;
1066       GstHLSVariantStream *old = match->data;
1067
1068       unmatched_lists = g_list_delete_link (unmatched_lists, match);
1069       /* FIXME: Deal with losing position due to missing an update */
1070       variant->m3u8->sequence_position = old->m3u8->sequence_position;
1071       variant->m3u8->sequence = old->m3u8->sequence;
1072     }
1073   }
1074
1075   if (unmatched_lists != NULL) {
1076     GST_WARNING ("Unable to match all playlists");
1077
1078     for (l = unmatched_lists; l != NULL; l = l->next) {
1079       if (l->data == hlsdemux->current_variant) {
1080         GST_WARNING ("Unable to match current playlist");
1081       }
1082     }
1083
1084     g_list_free (unmatched_lists);
1085   }
1086
1087   /* Switch out the variant playlist */
1088   old = hlsdemux->master;
1089
1090   // FIXME: check all this and also switch of variants, if anything needs updating
1091   hlsdemux->master = new_master;
1092
1093   if (hlsdemux->current_variant == NULL) {
1094     new_variant = new_master->default_variant;
1095   } else {
1096     /* Find the same variant in the new playlist */
1097     new_variant =
1098         gst_hls_master_playlist_get_matching_variant (new_master,
1099         hlsdemux->current_variant);
1100   }
1101
1102   /* Use the function to set the current variant, as it copies over data */
1103   if (new_variant != NULL)
1104     gst_hls_demux_set_current_variant (hlsdemux, new_variant);
1105
1106   gst_hls_master_playlist_unref (old);
1107
1108   ret = (hlsdemux->current_variant != NULL);
1109 out:
1110   GST_M3U8_CLIENT_UNLOCK (self);
1111
1112   return ret;
1113 }
1114
1115 static gboolean
1116 gst_hls_demux_update_playlist (GstHLSDemux * demux, gboolean update,
1117     GError ** err)
1118 {
1119   GstAdaptiveDemux *adaptive_demux = GST_ADAPTIVE_DEMUX (demux);
1120   GstFragment *download;
1121   GstBuffer *buf;
1122   gchar *playlist;
1123   gboolean main_checked = FALSE;
1124   const gchar *main_uri;
1125   GstM3U8 *m3u8;
1126   gchar *uri;
1127
1128 retry:
1129   uri = gst_m3u8_get_uri (demux->current_variant->m3u8);
1130   main_uri = gst_adaptive_demux_get_manifest_ref_uri (adaptive_demux);
1131   download =
1132       gst_uri_downloader_fetch_uri (adaptive_demux->downloader, uri, main_uri,
1133       TRUE, TRUE, TRUE, err);
1134   if (download == NULL) {
1135     gchar *base_uri;
1136
1137     if (!update || main_checked || demux->master->is_simple) {
1138       g_free (uri);
1139       return FALSE;
1140     }
1141     g_clear_error (err);
1142     GST_INFO_OBJECT (demux,
1143         "Updating playlist %s failed, attempt to refresh variant playlist %s",
1144         uri, main_uri);
1145     download =
1146         gst_uri_downloader_fetch_uri (adaptive_demux->downloader,
1147         main_uri, NULL, TRUE, TRUE, TRUE, err);
1148     if (download == NULL) {
1149       g_free (uri);
1150       return FALSE;
1151     }
1152
1153     buf = gst_fragment_get_buffer (download);
1154     playlist = gst_hls_src_buf_to_utf8_playlist (buf);
1155     gst_buffer_unref (buf);
1156
1157     if (playlist == NULL) {
1158       GST_WARNING_OBJECT (demux,
1159           "Failed to validate variant playlist encoding");
1160       g_free (uri);
1161       g_object_unref (download);
1162       g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_WRONG_TYPE,
1163           "Couldn't validate playlist encoding");
1164       return FALSE;
1165     }
1166
1167     g_free (uri);
1168     if (download->redirect_permanent && download->redirect_uri) {
1169       uri = download->redirect_uri;
1170       base_uri = NULL;
1171     } else {
1172       uri = download->uri;
1173       base_uri = download->redirect_uri;
1174     }
1175
1176     if (!gst_hls_demux_update_variant_playlist (demux, playlist, uri, base_uri)) {
1177       GST_WARNING_OBJECT (demux, "Failed to update the variant playlist");
1178       g_object_unref (download);
1179       g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_FAILED,
1180           "Couldn't update playlist");
1181       return FALSE;
1182     }
1183
1184     g_object_unref (download);
1185
1186     main_checked = TRUE;
1187     goto retry;
1188   }
1189   g_free (uri);
1190
1191   m3u8 = demux->current_variant->m3u8;
1192
1193   /* Set the base URI of the playlist to the redirect target if any */
1194   if (download->redirect_permanent && download->redirect_uri) {
1195     gst_m3u8_set_uri (m3u8, download->redirect_uri, NULL,
1196         demux->current_variant->name);
1197   } else {
1198     gst_m3u8_set_uri (m3u8, download->uri, download->redirect_uri,
1199         demux->current_variant->name);
1200   }
1201
1202   buf = gst_fragment_get_buffer (download);
1203   playlist = gst_hls_src_buf_to_utf8_playlist (buf);
1204   gst_buffer_unref (buf);
1205   g_object_unref (download);
1206
1207   if (playlist == NULL) {
1208     GST_WARNING_OBJECT (demux, "Couldn't validate playlist encoding");
1209     g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_WRONG_TYPE,
1210         "Couldn't validate playlist encoding");
1211     return FALSE;
1212   }
1213
1214   if (!gst_m3u8_update (m3u8, playlist)) {
1215     GST_WARNING_OBJECT (demux, "Couldn't update playlist");
1216     g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_FAILED,
1217         "Couldn't update playlist");
1218     return FALSE;
1219   }
1220
1221   /* If it's a live source, do not let the sequence number go beyond
1222    * three fragments before the end of the list */
1223   if (update == FALSE && gst_m3u8_is_live (m3u8)) {
1224     gint64 last_sequence, first_sequence;
1225
1226     GST_M3U8_CLIENT_LOCK (demux->client);
1227     last_sequence =
1228         GST_M3U8_MEDIA_FILE (g_list_last (m3u8->files)->data)->sequence;
1229     first_sequence =
1230         GST_M3U8_MEDIA_FILE (g_list_first (m3u8->files)->data)->sequence;
1231
1232     GST_DEBUG_OBJECT (demux,
1233         "sequence:%" G_GINT64_FORMAT " , first_sequence:%" G_GINT64_FORMAT
1234         " , last_sequence:%" G_GINT64_FORMAT, m3u8->sequence,
1235         first_sequence, last_sequence);
1236     if (m3u8->sequence >= last_sequence - 3) {
1237       //demux->need_segment = TRUE;
1238       /* Make sure we never go below the minimum sequence number */
1239       m3u8->sequence = MAX (first_sequence, last_sequence - 3);
1240       GST_DEBUG_OBJECT (demux,
1241           "Sequence is beyond playlist. Moving back to %" G_GINT64_FORMAT,
1242           m3u8->sequence);
1243     }
1244     GST_M3U8_CLIENT_UNLOCK (demux->client);
1245   } else if (!gst_m3u8_is_live (m3u8)) {
1246     GstClockTime current_pos, target_pos;
1247     guint sequence = 0;
1248     GList *walk;
1249
1250     /* Sequence numbers are not guaranteed to be the same in different
1251      * playlists, so get the correct fragment here based on the current
1252      * position
1253      */
1254     GST_M3U8_CLIENT_LOCK (demux->client);
1255
1256     /* Valid because hlsdemux only has a single output */
1257     if (GST_ADAPTIVE_DEMUX_CAST (demux)->streams) {
1258       GstAdaptiveDemuxStream *stream =
1259           GST_ADAPTIVE_DEMUX_CAST (demux)->streams->data;
1260       target_pos = stream->segment.position;
1261     } else {
1262       target_pos = 0;
1263     }
1264     if (GST_CLOCK_TIME_IS_VALID (m3u8->sequence_position)) {
1265       target_pos = MAX (target_pos, m3u8->sequence_position);
1266     }
1267
1268     GST_LOG_OBJECT (demux, "Looking for sequence position %"
1269         GST_TIME_FORMAT " in updated playlist", GST_TIME_ARGS (target_pos));
1270
1271     current_pos = 0;
1272     for (walk = m3u8->files; walk; walk = walk->next) {
1273       GstM3U8MediaFile *file = walk->data;
1274
1275       sequence = file->sequence;
1276       if (current_pos <= target_pos
1277           && target_pos < current_pos + file->duration) {
1278         break;
1279       }
1280       current_pos += file->duration;
1281     }
1282     /* End of playlist */
1283     if (!walk)
1284       sequence++;
1285     m3u8->sequence = sequence;
1286     m3u8->sequence_position = current_pos;
1287     GST_M3U8_CLIENT_UNLOCK (demux->client);
1288   }
1289
1290   return TRUE;
1291 }
1292
1293 static gboolean
1294 gst_hls_demux_change_playlist (GstHLSDemux * demux, guint max_bitrate,
1295     gboolean * changed)
1296 {
1297   GstHLSVariantStream *lowest_variant, *lowest_ivariant;
1298   GstHLSVariantStream *previous_variant, *new_variant;
1299   gint old_bandwidth, new_bandwidth;
1300   GstAdaptiveDemux *adaptive_demux = GST_ADAPTIVE_DEMUX_CAST (demux);
1301   GstAdaptiveDemuxStream *stream;
1302
1303   g_return_val_if_fail (adaptive_demux->streams != NULL, FALSE);
1304
1305   stream = adaptive_demux->streams->data;
1306
1307   previous_variant = demux->current_variant;
1308   new_variant =
1309       gst_hls_master_playlist_get_variant_for_bitrate (demux->master,
1310       demux->current_variant, max_bitrate);
1311
1312   GST_M3U8_CLIENT_LOCK (demux->client);
1313
1314 retry_failover_protection:
1315   old_bandwidth = previous_variant->bandwidth;
1316   new_bandwidth = new_variant->bandwidth;
1317
1318   /* Don't do anything else if the playlist is the same */
1319   if (new_bandwidth == old_bandwidth) {
1320     GST_M3U8_CLIENT_UNLOCK (demux->client);
1321     return TRUE;
1322   }
1323
1324   GST_M3U8_CLIENT_UNLOCK (demux->client);
1325
1326   gst_hls_demux_set_current_variant (demux, new_variant);
1327
1328   GST_INFO_OBJECT (demux, "Client was on %dbps, max allowed is %dbps, switching"
1329       " to bitrate %dbps", old_bandwidth, max_bitrate, new_bandwidth);
1330
1331   if (gst_hls_demux_update_playlist (demux, TRUE, NULL)) {
1332     const gchar *main_uri;
1333     gchar *uri;
1334
1335     uri = gst_m3u8_get_uri (new_variant->m3u8);
1336     main_uri = gst_adaptive_demux_get_manifest_ref_uri (adaptive_demux);
1337     gst_element_post_message (GST_ELEMENT_CAST (demux),
1338         gst_message_new_element (GST_OBJECT_CAST (demux),
1339             gst_structure_new (GST_ADAPTIVE_DEMUX_STATISTICS_MESSAGE_NAME,
1340                 "manifest-uri", G_TYPE_STRING,
1341                 main_uri, "uri", G_TYPE_STRING,
1342                 uri, "bitrate", G_TYPE_INT, new_bandwidth, NULL)));
1343     g_free (uri);
1344     if (changed)
1345       *changed = TRUE;
1346     stream->discont = TRUE;
1347   } else {
1348     GstHLSVariantStream *failover_variant = NULL;
1349     GList *failover;
1350
1351     GST_INFO_OBJECT (demux, "Unable to update playlist. Switching back");
1352     GST_M3U8_CLIENT_LOCK (demux->client);
1353
1354     /* we find variants by bitrate by going from highest to lowest, so it's
1355      * possible that there's another variant with the same bitrate before the
1356      * one selected which we can use as failover */
1357     failover = g_list_find (demux->master->variants, new_variant);
1358     if (failover != NULL)
1359       failover = failover->prev;
1360     if (failover != NULL)
1361       failover_variant = failover->data;
1362     if (failover_variant && new_bandwidth == failover_variant->bandwidth) {
1363       new_variant = failover_variant;
1364       goto retry_failover_protection;
1365     }
1366
1367     GST_M3U8_CLIENT_UNLOCK (demux->client);
1368     gst_hls_demux_set_current_variant (demux, previous_variant);
1369     /*  Try a lower bitrate (or stop if we just tried the lowest) */
1370     lowest_variant = demux->master->variants->data;
1371     lowest_ivariant = demux->master->iframe_variants->data;
1372     if (previous_variant->iframe && new_bandwidth == lowest_ivariant->bandwidth)
1373       return FALSE;
1374     if (!previous_variant->iframe && new_bandwidth == lowest_variant->bandwidth)
1375       return FALSE;
1376     else
1377       return gst_hls_demux_change_playlist (demux, new_bandwidth - 1, changed);
1378   }
1379
1380   return TRUE;
1381 }
1382
1383 #if defined(HAVE_OPENSSL)
1384 static gboolean
1385 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
1386     const guint8 * key_data, const guint8 * iv_data)
1387 {
1388   EVP_CIPHER_CTX_init (&stream->aes_ctx);
1389   if (!EVP_DecryptInit_ex (&stream->aes_ctx, EVP_aes_128_cbc (), NULL, key_data,
1390           iv_data))
1391     return FALSE;
1392   EVP_CIPHER_CTX_set_padding (&stream->aes_ctx, 0);
1393   return TRUE;
1394 }
1395
1396 static gboolean
1397 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
1398     const guint8 * encrypted_data, guint8 * decrypted_data)
1399 {
1400   int len, flen = 0;
1401
1402   if (G_UNLIKELY (length > G_MAXINT || length % 16 != 0))
1403     return FALSE;
1404
1405   len = (int) length;
1406   if (!EVP_DecryptUpdate (&stream->aes_ctx, decrypted_data, &len,
1407           encrypted_data, len))
1408     return FALSE;
1409   EVP_DecryptFinal_ex (&stream->aes_ctx, decrypted_data + len, &flen);
1410   g_return_val_if_fail (len + flen == length, FALSE);
1411   return TRUE;
1412 }
1413
1414 static void
1415 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
1416 {
1417   EVP_CIPHER_CTX_cleanup (&stream->aes_ctx);
1418 }
1419
1420 #elif defined(HAVE_NETTLE)
1421 static gboolean
1422 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
1423     const guint8 * key_data, const guint8 * iv_data)
1424 {
1425   aes_set_decrypt_key (&stream->aes_ctx.ctx, 16, key_data);
1426   CBC_SET_IV (&stream->aes_ctx, iv_data);
1427
1428   return TRUE;
1429 }
1430
1431 static gboolean
1432 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
1433     const guint8 * encrypted_data, guint8 * decrypted_data)
1434 {
1435   if (length % 16 != 0)
1436     return FALSE;
1437
1438   CBC_DECRYPT (&stream->aes_ctx, aes_decrypt, length, decrypted_data,
1439       encrypted_data);
1440
1441   return TRUE;
1442 }
1443
1444 static void
1445 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
1446 {
1447   /* NOP */
1448 }
1449
1450 #else
1451 static gboolean
1452 gst_hls_demux_stream_decrypt_start (GstHLSDemuxStream * stream,
1453     const guint8 * key_data, const guint8 * iv_data)
1454 {
1455   gcry_error_t err = 0;
1456   gboolean ret = FALSE;
1457
1458   err =
1459       gcry_cipher_open (&stream->aes_ctx, GCRY_CIPHER_AES128,
1460       GCRY_CIPHER_MODE_CBC, 0);
1461   if (err)
1462     goto out;
1463   err = gcry_cipher_setkey (stream->aes_ctx, key_data, 16);
1464   if (err)
1465     goto out;
1466   err = gcry_cipher_setiv (stream->aes_ctx, iv_data, 16);
1467   if (!err)
1468     ret = TRUE;
1469
1470 out:
1471   if (!ret)
1472     if (stream->aes_ctx)
1473       gcry_cipher_close (stream->aes_ctx);
1474
1475   return ret;
1476 }
1477
1478 static gboolean
1479 decrypt_fragment (GstHLSDemuxStream * stream, gsize length,
1480     const guint8 * encrypted_data, guint8 * decrypted_data)
1481 {
1482   gcry_error_t err = 0;
1483
1484   err = gcry_cipher_decrypt (stream->aes_ctx, decrypted_data, length,
1485       encrypted_data, length);
1486
1487   return err == 0;
1488 }
1489
1490 static void
1491 gst_hls_demux_stream_decrypt_end (GstHLSDemuxStream * stream)
1492 {
1493   if (stream->aes_ctx) {
1494     gcry_cipher_close (stream->aes_ctx);
1495     stream->aes_ctx = NULL;
1496   }
1497 }
1498 #endif
1499
1500 static GstBuffer *
1501 gst_hls_demux_decrypt_fragment (GstHLSDemux * demux, GstHLSDemuxStream * stream,
1502     GstBuffer * encrypted_buffer, GError ** err)
1503 {
1504   GstBuffer *decrypted_buffer = NULL;
1505   GstMapInfo encrypted_info, decrypted_info;
1506
1507   decrypted_buffer =
1508       gst_buffer_new_allocate (NULL, gst_buffer_get_size (encrypted_buffer),
1509       NULL);
1510
1511   gst_buffer_map (encrypted_buffer, &encrypted_info, GST_MAP_READ);
1512   gst_buffer_map (decrypted_buffer, &decrypted_info, GST_MAP_WRITE);
1513
1514   if (!decrypt_fragment (stream, encrypted_info.size,
1515           encrypted_info.data, decrypted_info.data))
1516     goto decrypt_error;
1517
1518
1519   gst_buffer_unmap (decrypted_buffer, &decrypted_info);
1520   gst_buffer_unmap (encrypted_buffer, &encrypted_info);
1521
1522   gst_buffer_unref (encrypted_buffer);
1523
1524   return decrypted_buffer;
1525
1526 decrypt_error:
1527   GST_ERROR_OBJECT (demux, "Failed to decrypt fragment");
1528   g_set_error (err, GST_STREAM_ERROR, GST_STREAM_ERROR_DECRYPT,
1529       "Failed to decrypt fragment");
1530
1531   gst_buffer_unmap (decrypted_buffer, &decrypted_info);
1532   gst_buffer_unmap (encrypted_buffer, &encrypted_info);
1533
1534   gst_buffer_unref (encrypted_buffer);
1535   gst_buffer_unref (decrypted_buffer);
1536
1537   return NULL;
1538 }
1539
1540 static gint64
1541 gst_hls_demux_get_manifest_update_interval (GstAdaptiveDemux * demux)
1542 {
1543   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
1544   GstClockTime target_duration;
1545
1546   if (hlsdemux->current_variant) {
1547     target_duration =
1548         gst_m3u8_get_target_duration (hlsdemux->current_variant->m3u8);
1549   } else {
1550     target_duration = 5 * GST_SECOND;
1551   }
1552
1553   return gst_util_uint64_scale (target_duration, G_USEC_PER_SEC, GST_SECOND);
1554 }
1555
1556 static gboolean
1557 gst_hls_demux_get_live_seek_range (GstAdaptiveDemux * demux, gint64 * start,
1558     gint64 * stop)
1559 {
1560   GstHLSDemux *hlsdemux = GST_HLS_DEMUX_CAST (demux);
1561   gboolean ret = FALSE;
1562
1563   if (hlsdemux->current_variant) {
1564     ret =
1565         gst_m3u8_get_seek_range (hlsdemux->current_variant->m3u8, start, stop);
1566   }
1567
1568   return ret;
1569 }