2dfb8560a287f61a6c81e9365f67c1264b52600f
[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  *
8  * Gsthlsdemux.c:
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25 /**
26  * SECTION:element-hlsdemux
27  *
28  * HTTP Live Streaming demuxer element.
29  *
30  * <refsect2>
31  * <title>Example launch line</title>
32  * |[
33  * gst-launch souphttpsrc location=http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8 ! hlsdemux ! decodebin2 ! videoconvert ! videoscale ! autovideosink
34  * ]|
35  * </refsect2>
36  *
37  * Last reviewed on 2010-10-07
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #  include "config.h"
42 #endif
43
44 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
45  * with newer GLib versions (>= 2.31.0) */
46 #define GLIB_DISABLE_DEPRECATION_WARNINGS
47
48 #include <string.h>
49 #include <gst/glib-compat-private.h>
50 #include <gnutls/gnutls.h>
51 #include <gnutls/crypto.h>
52 #include "gsthlsdemux.h"
53
54 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
55     GST_PAD_SRC,
56     GST_PAD_SOMETIMES,
57     GST_STATIC_CAPS_ANY);
58
59 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
60     GST_PAD_SINK,
61     GST_PAD_ALWAYS,
62     GST_STATIC_CAPS ("application/x-hls"));
63
64 GST_DEBUG_CATEGORY_STATIC (gst_hls_demux_debug);
65 #define GST_CAT_DEFAULT gst_hls_demux_debug
66
67 enum
68 {
69   PROP_0,
70
71   PROP_FRAGMENTS_CACHE,
72   PROP_BITRATE_LIMIT,
73   PROP_CONNECTION_SPEED,
74   PROP_LAST
75 };
76
77 static const float update_interval_factor[] = { 1, 0.5, 1.5, 3 };
78
79 #define DEFAULT_FRAGMENTS_CACHE 3
80 #define DEFAULT_FAILED_COUNT 3
81 #define DEFAULT_BITRATE_LIMIT 0.8
82 #define DEFAULT_CONNECTION_SPEED    0
83
84 /* GObject */
85 static void gst_hls_demux_set_property (GObject * object, guint prop_id,
86     const GValue * value, GParamSpec * pspec);
87 static void gst_hls_demux_get_property (GObject * object, guint prop_id,
88     GValue * value, GParamSpec * pspec);
89 static void gst_hls_demux_dispose (GObject * obj);
90
91 /* GstElement */
92 static GstStateChangeReturn
93 gst_hls_demux_change_state (GstElement * element, GstStateChange transition);
94
95 /* GstHLSDemux */
96 static GstFlowReturn gst_hls_demux_chain (GstPad * pad, GstObject * parent,
97     GstBuffer * buf);
98 static gboolean gst_hls_demux_sink_event (GstPad * pad, GstObject * parent,
99     GstEvent * event);
100 static gboolean gst_hls_demux_src_event (GstPad * pad, GstObject * parent,
101     GstEvent * event);
102 static gboolean gst_hls_demux_src_query (GstPad * pad, GstObject * parent,
103     GstQuery * query);
104 static void gst_hls_demux_stream_loop (GstHLSDemux * demux);
105 static void gst_hls_demux_updates_loop (GstHLSDemux * demux);
106 static void gst_hls_demux_stop (GstHLSDemux * demux);
107 static void gst_hls_demux_pause_tasks (GstHLSDemux * demux, gboolean caching);
108 static gboolean gst_hls_demux_cache_fragments (GstHLSDemux * demux);
109 static gboolean gst_hls_demux_schedule (GstHLSDemux * demux);
110 static gboolean gst_hls_demux_switch_playlist (GstHLSDemux * demux);
111 static gboolean gst_hls_demux_get_next_fragment (GstHLSDemux * demux,
112     gboolean caching);
113 static gboolean gst_hls_demux_update_playlist (GstHLSDemux * demux,
114     gboolean update);
115 static void gst_hls_demux_reset (GstHLSDemux * demux, gboolean dispose);
116 static gboolean gst_hls_demux_set_location (GstHLSDemux * demux,
117     const gchar * uri);
118 static gchar *gst_hls_src_buf_to_utf8_playlist (GstBuffer * buf);
119
120 #define gst_hls_demux_parent_class parent_class
121 G_DEFINE_TYPE (GstHLSDemux, gst_hls_demux, GST_TYPE_ELEMENT);
122
123 static void
124 gst_hls_demux_dispose (GObject * obj)
125 {
126   GstHLSDemux *demux = GST_HLS_DEMUX (obj);
127
128   if (demux->stream_task) {
129     if (GST_TASK_STATE (demux->stream_task) != GST_TASK_STOPPED) {
130       GST_DEBUG_OBJECT (demux, "Leaving streaming task");
131       gst_task_stop (demux->stream_task);
132       g_rec_mutex_lock (&demux->stream_lock);
133       g_rec_mutex_unlock (&demux->stream_lock);
134       gst_task_join (demux->stream_task);
135     }
136     gst_object_unref (demux->stream_task);
137     g_rec_mutex_clear (&demux->stream_lock);
138     demux->stream_task = NULL;
139   }
140
141   if (demux->updates_task) {
142     if (GST_TASK_STATE (demux->updates_task) != GST_TASK_STOPPED) {
143       GST_DEBUG_OBJECT (demux, "Leaving updates task");
144       demux->cancelled = TRUE;
145       gst_uri_downloader_cancel (demux->downloader);
146       gst_task_stop (demux->updates_task);
147       g_mutex_lock (&demux->updates_timed_lock);
148       GST_TASK_SIGNAL (demux->updates_task);
149       g_rec_mutex_lock (&demux->updates_lock);
150       g_rec_mutex_unlock (&demux->updates_lock);
151       g_mutex_unlock (&demux->updates_timed_lock);
152       gst_task_join (demux->updates_task);
153     }
154     gst_object_unref (demux->updates_task);
155     g_mutex_clear (&demux->updates_timed_lock);
156     g_rec_mutex_clear (&demux->updates_lock);
157     demux->updates_task = NULL;
158   }
159
160   if (demux->downloader != NULL) {
161     g_object_unref (demux->downloader);
162     demux->downloader = NULL;
163   }
164
165   gst_hls_demux_reset (demux, TRUE);
166
167   g_queue_free (demux->queue);
168
169   G_OBJECT_CLASS (parent_class)->dispose (obj);
170 }
171
172 static void
173 gst_hls_demux_class_init (GstHLSDemuxClass * klass)
174 {
175   GObjectClass *gobject_class;
176   GstElementClass *element_class;
177
178   gobject_class = (GObjectClass *) klass;
179   element_class = (GstElementClass *) klass;
180
181   gobject_class->set_property = gst_hls_demux_set_property;
182   gobject_class->get_property = gst_hls_demux_get_property;
183   gobject_class->dispose = gst_hls_demux_dispose;
184
185   g_object_class_install_property (gobject_class, PROP_FRAGMENTS_CACHE,
186       g_param_spec_uint ("fragments-cache", "Fragments cache",
187           "Number of fragments needed to be cached to start playing",
188           2, G_MAXUINT, DEFAULT_FRAGMENTS_CACHE,
189           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
190
191   g_object_class_install_property (gobject_class, PROP_BITRATE_LIMIT,
192       g_param_spec_float ("bitrate-limit",
193           "Bitrate limit in %",
194           "Limit of the available bitrate to use when switching to alternates.",
195           0, 1, DEFAULT_BITRATE_LIMIT,
196           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
197
198   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
199       g_param_spec_uint ("connection-speed", "Connection Speed",
200           "Network connection speed in kbps (0 = unknown)",
201           0, G_MAXUINT / 1000, DEFAULT_CONNECTION_SPEED,
202           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
203
204   element_class->change_state = GST_DEBUG_FUNCPTR (gst_hls_demux_change_state);
205
206   gst_element_class_add_pad_template (element_class,
207       gst_static_pad_template_get (&srctemplate));
208
209   gst_element_class_add_pad_template (element_class,
210       gst_static_pad_template_get (&sinktemplate));
211
212   gst_element_class_set_static_metadata (element_class,
213       "HLS Demuxer",
214       "Demuxer/URIList",
215       "HTTP Live Streaming demuxer",
216       "Marc-Andre Lureau <marcandre.lureau@gmail.com>\n"
217       "Andoni Morales Alastruey <ylatuya@gmail.com>");
218
219   GST_DEBUG_CATEGORY_INIT (gst_hls_demux_debug, "hlsdemux", 0,
220       "hlsdemux element");
221 }
222
223 static void
224 gst_hls_demux_init (GstHLSDemux * demux)
225 {
226   /* sink pad */
227   demux->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
228   gst_pad_set_chain_function (demux->sinkpad,
229       GST_DEBUG_FUNCPTR (gst_hls_demux_chain));
230   gst_pad_set_event_function (demux->sinkpad,
231       GST_DEBUG_FUNCPTR (gst_hls_demux_sink_event));
232   gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);
233
234   /* Downloader */
235   demux->downloader = gst_uri_downloader_new ();
236
237   demux->do_typefind = TRUE;
238
239   /* Properties */
240   demux->fragments_cache = DEFAULT_FRAGMENTS_CACHE;
241   demux->bitrate_limit = DEFAULT_BITRATE_LIMIT;
242   demux->connection_speed = DEFAULT_CONNECTION_SPEED;
243
244   demux->queue = g_queue_new ();
245
246   /* Updates task */
247   g_rec_mutex_init (&demux->updates_lock);
248   demux->updates_task =
249       gst_task_new ((GstTaskFunction) gst_hls_demux_updates_loop, demux, NULL);
250   gst_task_set_lock (demux->updates_task, &demux->updates_lock);
251   g_mutex_init (&demux->updates_timed_lock);
252
253   /* Streaming task */
254   g_rec_mutex_init (&demux->stream_lock);
255   demux->stream_task =
256       gst_task_new ((GstTaskFunction) gst_hls_demux_stream_loop, demux, NULL);
257   gst_task_set_lock (demux->stream_task, &demux->stream_lock);
258
259   demux->have_group_id = FALSE;
260   demux->group_id = G_MAXUINT;
261 }
262
263 static void
264 gst_hls_demux_set_property (GObject * object, guint prop_id,
265     const GValue * value, GParamSpec * pspec)
266 {
267   GstHLSDemux *demux = GST_HLS_DEMUX (object);
268
269   switch (prop_id) {
270     case PROP_FRAGMENTS_CACHE:
271       demux->fragments_cache = g_value_get_uint (value);
272       break;
273     case PROP_BITRATE_LIMIT:
274       demux->bitrate_limit = g_value_get_float (value);
275       break;
276     case PROP_CONNECTION_SPEED:
277       demux->connection_speed = g_value_get_uint (value) * 1000;
278       break;
279     default:
280       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
281       break;
282   }
283 }
284
285 static void
286 gst_hls_demux_get_property (GObject * object, guint prop_id, GValue * value,
287     GParamSpec * pspec)
288 {
289   GstHLSDemux *demux = GST_HLS_DEMUX (object);
290
291   switch (prop_id) {
292     case PROP_FRAGMENTS_CACHE:
293       g_value_set_uint (value, demux->fragments_cache);
294       break;
295     case PROP_BITRATE_LIMIT:
296       g_value_set_float (value, demux->bitrate_limit);
297       break;
298     case PROP_CONNECTION_SPEED:
299       g_value_set_uint (value, demux->connection_speed / 1000);
300       break;
301     default:
302       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
303       break;
304   }
305 }
306
307 static GstStateChangeReturn
308 gst_hls_demux_change_state (GstElement * element, GstStateChange transition)
309 {
310   GstStateChangeReturn ret;
311   GstHLSDemux *demux = GST_HLS_DEMUX (element);
312
313   switch (transition) {
314     case GST_STATE_CHANGE_READY_TO_PAUSED:
315       gst_hls_demux_reset (demux, FALSE);
316       break;
317     default:
318       break;
319   }
320
321   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
322
323   switch (transition) {
324     case GST_STATE_CHANGE_PAUSED_TO_READY:
325       demux->cancelled = TRUE;
326       gst_hls_demux_stop (demux);
327       gst_task_join (demux->stream_task);
328       gst_hls_demux_reset (demux, FALSE);
329       break;
330     default:
331       break;
332   }
333   return ret;
334 }
335
336 static gboolean
337 gst_hls_demux_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
338 {
339   GstHLSDemux *demux;
340
341   demux = GST_HLS_DEMUX (parent);
342
343   switch (event->type) {
344     case GST_EVENT_SEEK:
345     {
346       gdouble rate;
347       GstFormat format;
348       GstSeekFlags flags;
349       GstSeekType start_type, stop_type;
350       gint64 start, stop;
351       GList *walk;
352       GstClockTime position, current_pos, target_pos;
353       gint current_sequence;
354       GstM3U8MediaFile *file;
355
356       GST_INFO_OBJECT (demux, "Received GST_EVENT_SEEK");
357
358       if (gst_m3u8_client_is_live (demux->client)) {
359         GST_WARNING_OBJECT (demux, "Received seek event for live stream");
360         return FALSE;
361       }
362
363       gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
364           &stop_type, &stop);
365
366       if (format != GST_FORMAT_TIME)
367         return FALSE;
368
369       GST_DEBUG_OBJECT (demux, "seek event, rate: %f start: %" GST_TIME_FORMAT
370           " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
371           GST_TIME_ARGS (stop));
372
373       GST_M3U8_CLIENT_LOCK (demux->client);
374       file = GST_M3U8_MEDIA_FILE (demux->client->current->files->data);
375       current_sequence = file->sequence;
376       current_pos = 0;
377       target_pos = (GstClockTime) start;
378       for (walk = demux->client->current->files; walk; walk = walk->next) {
379         file = walk->data;
380
381         current_sequence = file->sequence;
382         if (current_pos <= target_pos
383             && target_pos < current_pos + file->duration) {
384           break;
385         }
386         current_pos += file->duration;
387       }
388       GST_M3U8_CLIENT_UNLOCK (demux->client);
389
390       if (walk == NULL) {
391         GST_WARNING_OBJECT (demux, "Could not find seeked fragment");
392         return FALSE;
393       }
394
395       if (flags & GST_SEEK_FLAG_FLUSH) {
396         GST_DEBUG_OBJECT (demux, "sending flush start");
397         gst_pad_push_event (demux->srcpad, gst_event_new_flush_start ());
398       }
399
400       demux->cancelled = TRUE;
401       gst_task_pause (demux->stream_task);
402       gst_uri_downloader_cancel (demux->downloader);
403       gst_task_stop (demux->updates_task);
404       g_mutex_lock (&demux->updates_timed_lock);
405       GST_TASK_SIGNAL (demux->updates_task);
406       g_mutex_unlock (&demux->updates_timed_lock);
407       g_rec_mutex_lock (&demux->updates_lock);
408       g_rec_mutex_unlock (&demux->updates_lock);
409       gst_task_pause (demux->stream_task);
410
411       /* wait for streaming to finish */
412       g_rec_mutex_lock (&demux->stream_lock);
413
414       demux->need_cache = TRUE;
415       while (!g_queue_is_empty (demux->queue)) {
416         GstFragment *fragment = g_queue_pop_head (demux->queue);
417         g_object_unref (fragment);
418       }
419       g_queue_clear (demux->queue);
420
421       GST_M3U8_CLIENT_LOCK (demux->client);
422       GST_DEBUG_OBJECT (demux, "seeking to sequence %d", current_sequence);
423       demux->client->sequence = current_sequence;
424       gst_m3u8_client_get_current_position (demux->client, &position);
425       demux->position_shift = start - position;
426       demux->need_segment = TRUE;
427       GST_M3U8_CLIENT_UNLOCK (demux->client);
428
429
430       if (flags & GST_SEEK_FLAG_FLUSH) {
431         GST_DEBUG_OBJECT (demux, "sending flush stop");
432         gst_pad_push_event (demux->srcpad, gst_event_new_flush_stop (TRUE));
433       }
434
435       demux->cancelled = FALSE;
436       gst_task_start (demux->stream_task);
437       g_rec_mutex_unlock (&demux->stream_lock);
438
439       return TRUE;
440     }
441     default:
442       break;
443   }
444
445   return gst_pad_event_default (pad, parent, event);
446 }
447
448 static gboolean
449 gst_hls_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
450 {
451   GstHLSDemux *demux;
452   GstQuery *query;
453   gboolean ret;
454   gchar *uri;
455
456   demux = GST_HLS_DEMUX (parent);
457
458   switch (event->type) {
459     case GST_EVENT_EOS:{
460       gchar *playlist = NULL;
461
462       if (demux->playlist == NULL) {
463         GST_WARNING_OBJECT (demux, "Received EOS without a playlist.");
464         break;
465       }
466
467       GST_DEBUG_OBJECT (demux,
468           "Got EOS on the sink pad: main playlist fetched");
469
470       query = gst_query_new_uri ();
471       ret = gst_pad_peer_query (demux->sinkpad, query);
472       if (ret) {
473         gst_query_parse_uri (query, &uri);
474         gst_hls_demux_set_location (demux, uri);
475         g_free (uri);
476       }
477       gst_query_unref (query);
478
479       playlist = gst_hls_src_buf_to_utf8_playlist (demux->playlist);
480       demux->playlist = NULL;
481       if (playlist == NULL) {
482         GST_WARNING_OBJECT (demux, "Error validating first playlist.");
483       } else if (!gst_m3u8_client_update (demux->client, playlist)) {
484         /* In most cases, this will happen if we set a wrong url in the
485          * source element and we have received the 404 HTML response instead of
486          * the playlist */
487         GST_ELEMENT_ERROR (demux, STREAM, DECODE, ("Invalid playlist."),
488             (NULL));
489         return FALSE;
490       }
491
492       if (!ret && gst_m3u8_client_is_live (demux->client)) {
493         GST_ELEMENT_ERROR (demux, RESOURCE, NOT_FOUND,
494             ("Failed querying the playlist uri, "
495                 "required for live sources."), (NULL));
496         return FALSE;
497       }
498
499       gst_task_start (demux->stream_task);
500       gst_event_unref (event);
501       return TRUE;
502     }
503     case GST_EVENT_SEGMENT:
504       /* Swallow newsegments, we'll push our own */
505       gst_event_unref (event);
506       return TRUE;
507     default:
508       break;
509   }
510
511   return gst_pad_event_default (pad, parent, event);
512 }
513
514 static gboolean
515 gst_hls_demux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
516 {
517   GstHLSDemux *hlsdemux;
518   gboolean ret = FALSE;
519
520   if (query == NULL)
521     return FALSE;
522
523   hlsdemux = GST_HLS_DEMUX (parent);
524
525   switch (query->type) {
526     case GST_QUERY_DURATION:{
527       GstClockTime duration = -1;
528       GstFormat fmt;
529
530       gst_query_parse_duration (query, &fmt, NULL);
531       if (fmt == GST_FORMAT_TIME) {
532         duration = gst_m3u8_client_get_duration (hlsdemux->client);
533         if (GST_CLOCK_TIME_IS_VALID (duration) && duration > 0) {
534           gst_query_set_duration (query, GST_FORMAT_TIME, duration);
535           ret = TRUE;
536         }
537       }
538       GST_INFO_OBJECT (hlsdemux, "GST_QUERY_DURATION returns %s with duration %"
539           GST_TIME_FORMAT, ret ? "TRUE" : "FALSE", GST_TIME_ARGS (duration));
540       break;
541     }
542     case GST_QUERY_URI:
543       if (hlsdemux->client) {
544         /* FIXME: Do we answer with the variant playlist, with the current
545          * playlist or the the uri of the least downlowaded fragment? */
546         gst_query_set_uri (query, gst_m3u8_client_get_uri (hlsdemux->client));
547         ret = TRUE;
548       }
549       break;
550     case GST_QUERY_SEEKING:{
551       GstFormat fmt;
552       gint64 stop = -1;
553
554       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
555       GST_INFO_OBJECT (hlsdemux, "Received GST_QUERY_SEEKING with format %d",
556           fmt);
557       if (fmt == GST_FORMAT_TIME) {
558         GstClockTime duration;
559
560         duration = gst_m3u8_client_get_duration (hlsdemux->client);
561         if (GST_CLOCK_TIME_IS_VALID (duration) && duration > 0)
562           stop = duration;
563
564         gst_query_set_seeking (query, fmt,
565             !gst_m3u8_client_is_live (hlsdemux->client), 0, stop);
566         ret = TRUE;
567         GST_INFO_OBJECT (hlsdemux, "GST_QUERY_SEEKING returning with stop : %"
568             GST_TIME_FORMAT, GST_TIME_ARGS (stop));
569       }
570       break;
571     }
572     default:
573       /* Don't fordward queries upstream because of the special nature of this
574        * "demuxer", which relies on the upstream element only to be fed with the
575        * first playlist */
576       break;
577   }
578
579   return ret;
580 }
581
582 static GstFlowReturn
583 gst_hls_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
584 {
585   GstHLSDemux *demux = GST_HLS_DEMUX (parent);
586
587   if (demux->playlist == NULL)
588     demux->playlist = buf;
589   else
590     demux->playlist = gst_buffer_append (demux->playlist, buf);
591
592   return GST_FLOW_OK;
593 }
594
595 static void
596 gst_hls_demux_pause_tasks (GstHLSDemux * demux, gboolean caching)
597 {
598   if (GST_TASK_STATE (demux->updates_task) != GST_TASK_STOPPED) {
599     demux->cancelled = TRUE;
600     gst_uri_downloader_cancel (demux->downloader);
601     gst_task_pause (demux->updates_task);
602     if (!caching)
603       g_mutex_lock (&demux->updates_timed_lock);
604     GST_TASK_SIGNAL (demux->updates_task);
605     if (!caching)
606       g_mutex_unlock (&demux->updates_timed_lock);
607   }
608
609   if (GST_TASK_STATE (demux->stream_task) != GST_TASK_STOPPED) {
610     demux->stop_stream_task = TRUE;
611     gst_task_pause (demux->stream_task);
612   }
613 }
614
615 static void
616 gst_hls_demux_stop (GstHLSDemux * demux)
617 {
618   gst_uri_downloader_cancel (demux->downloader);
619
620   if (GST_TASK_STATE (demux->updates_task) != GST_TASK_STOPPED) {
621     demux->cancelled = TRUE;
622     gst_uri_downloader_cancel (demux->downloader);
623     gst_task_stop (demux->updates_task);
624     g_mutex_lock (&demux->updates_timed_lock);
625     GST_TASK_SIGNAL (demux->updates_task);
626     g_mutex_unlock (&demux->updates_timed_lock);
627     g_rec_mutex_lock (&demux->updates_lock);
628     g_rec_mutex_unlock (&demux->updates_lock);
629   }
630
631   if (GST_TASK_STATE (demux->stream_task) != GST_TASK_STOPPED) {
632     demux->stop_stream_task = TRUE;
633     gst_task_stop (demux->stream_task);
634     g_rec_mutex_lock (&demux->stream_lock);
635     g_rec_mutex_unlock (&demux->stream_lock);
636   }
637 }
638
639 static void
640 switch_pads (GstHLSDemux * demux, GstCaps * newcaps)
641 {
642   GstPad *oldpad = demux->srcpad;
643   GstEvent *event;
644   gchar *stream_id;
645
646   GST_DEBUG ("Switching pads (oldpad:%p) with caps: %" GST_PTR_FORMAT, oldpad,
647       newcaps);
648
649   /* First create and activate new pad */
650   demux->srcpad = gst_pad_new_from_static_template (&srctemplate, NULL);
651   gst_pad_set_event_function (demux->srcpad,
652       GST_DEBUG_FUNCPTR (gst_hls_demux_src_event));
653   gst_pad_set_query_function (demux->srcpad,
654       GST_DEBUG_FUNCPTR (gst_hls_demux_src_query));
655   gst_pad_set_element_private (demux->srcpad, demux);
656   gst_pad_set_active (demux->srcpad, TRUE);
657
658   stream_id =
659       gst_pad_create_stream_id (demux->srcpad, GST_ELEMENT_CAST (demux), NULL);
660
661   event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
662   if (event) {
663     if (gst_event_parse_group_id (event, &demux->group_id))
664       demux->have_group_id = TRUE;
665     else
666       demux->have_group_id = FALSE;
667     gst_event_unref (event);
668   } else if (!demux->have_group_id) {
669     demux->have_group_id = TRUE;
670     demux->group_id = gst_util_group_id_next ();
671   }
672   event = gst_event_new_stream_start (stream_id);
673   if (demux->have_group_id)
674     gst_event_set_group_id (event, demux->group_id);
675
676   gst_pad_push_event (demux->srcpad, event);
677   g_free (stream_id);
678
679   gst_pad_set_caps (demux->srcpad, newcaps);
680
681   gst_element_add_pad (GST_ELEMENT (demux), demux->srcpad);
682
683   gst_element_no_more_pads (GST_ELEMENT (demux));
684
685   if (oldpad) {
686     /* Push out EOS */
687     gst_pad_push_event (oldpad, gst_event_new_eos ());
688     gst_pad_set_active (oldpad, FALSE);
689     gst_element_remove_pad (GST_ELEMENT (demux), oldpad);
690   }
691 }
692
693 static void
694 gst_hls_demux_stream_loop (GstHLSDemux * demux)
695 {
696   GstFragment *fragment;
697   GstBuffer *buf;
698   GstFlowReturn ret;
699   GstCaps *bufcaps, *srccaps = NULL;
700
701   /* Loop for the source pad task. The task is started when we have
702    * received the main playlist from the source element. It tries first to
703    * cache the first fragments and then it waits until it has more data in the
704    * queue. This task is woken up when we push a new fragment to the queue or
705    * when we reached the end of the playlist  */
706   GST_DEBUG_OBJECT (demux, "Enter task");
707
708   if (G_UNLIKELY (demux->need_cache)) {
709     if (!gst_hls_demux_cache_fragments (demux))
710       goto cache_error;
711
712     /* we can start now the updates thread (only if on playing) */
713     gst_task_start (demux->updates_task);
714     GST_INFO_OBJECT (demux, "First fragments cached successfully");
715   }
716
717   if (g_queue_is_empty (demux->queue)) {
718     if (demux->end_of_playlist)
719       goto end_of_playlist;
720
721     goto pause_task;
722   }
723
724   fragment = g_queue_pop_head (demux->queue);
725   buf = gst_fragment_get_buffer (fragment);
726
727   /* Figure out if we need to create/switch pads */
728   if (G_LIKELY (demux->srcpad))
729     srccaps = gst_pad_get_current_caps (demux->srcpad);
730   bufcaps = gst_fragment_get_caps (fragment);
731   if (G_UNLIKELY (!srccaps || !gst_caps_is_equal_fixed (bufcaps, srccaps)
732           || demux->need_segment)) {
733     switch_pads (demux, bufcaps);
734     demux->need_segment = TRUE;
735   }
736   gst_caps_unref (bufcaps);
737   if (G_LIKELY (srccaps))
738     gst_caps_unref (srccaps);
739   g_object_unref (fragment);
740
741   if (demux->need_segment) {
742     GstSegment segment;
743     GstClockTime start = GST_BUFFER_PTS (buf);
744
745     start += demux->position_shift;
746     /* And send a newsegment */
747     GST_DEBUG_OBJECT (demux, "Sending new-segment. segment start:%"
748         GST_TIME_FORMAT, GST_TIME_ARGS (start));
749     gst_segment_init (&segment, GST_FORMAT_TIME);
750     segment.start = start;
751     segment.time = start;
752     gst_pad_push_event (demux->srcpad, gst_event_new_segment (&segment));
753     demux->need_segment = FALSE;
754     demux->position_shift = 0;
755   }
756
757   GST_DEBUG_OBJECT (demux, "Pushing buffer %p", buf);
758
759   ret = gst_pad_push (demux->srcpad, buf);
760   if (ret != GST_FLOW_OK)
761     goto error_pushing;
762
763   GST_DEBUG_OBJECT (demux, "Pushed buffer");
764
765   return;
766
767 end_of_playlist:
768   {
769     GST_DEBUG_OBJECT (demux, "Reached end of playlist, sending EOS");
770     gst_pad_push_event (demux->srcpad, gst_event_new_eos ());
771     gst_hls_demux_pause_tasks (demux, FALSE);
772     return;
773   }
774
775 cache_error:
776   {
777     gst_task_pause (demux->stream_task);
778     if (!demux->cancelled) {
779       GST_ELEMENT_ERROR (demux, RESOURCE, NOT_FOUND,
780           ("Could not cache the first fragments"), (NULL));
781       gst_hls_demux_pause_tasks (demux, FALSE);
782     }
783     return;
784   }
785
786 error_pushing:
787   {
788     if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
789       GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
790           ("stream stopped, reason %s", gst_flow_get_name (ret)));
791       gst_pad_push_event (demux->srcpad, gst_event_new_eos ());
792     } else {
793       GST_DEBUG_OBJECT (demux, "stream stopped, reason %s",
794           gst_flow_get_name (ret));
795     }
796     gst_hls_demux_pause_tasks (demux, FALSE);
797     return;
798   }
799
800 pause_task:
801   {
802     GST_DEBUG_OBJECT (demux, "Pause task");
803     gst_task_pause (demux->stream_task);
804     return;
805   }
806 }
807
808 static void
809 gst_hls_demux_reset (GstHLSDemux * demux, gboolean dispose)
810 {
811   demux->need_cache = TRUE;
812   demux->end_of_playlist = FALSE;
813   demux->cancelled = FALSE;
814   demux->do_typefind = TRUE;
815
816   if (demux->input_caps) {
817     gst_caps_unref (demux->input_caps);
818     demux->input_caps = NULL;
819   }
820
821   if (demux->playlist) {
822     gst_buffer_unref (demux->playlist);
823     demux->playlist = NULL;
824   }
825
826   if (demux->client) {
827     gst_m3u8_client_free (demux->client);
828     demux->client = NULL;
829   }
830
831   if (!dispose) {
832     demux->client = gst_m3u8_client_new ("");
833   }
834
835   while (!g_queue_is_empty (demux->queue)) {
836     GstFragment *fragment = g_queue_pop_head (demux->queue);
837     g_object_unref (fragment);
838   }
839   g_queue_clear (demux->queue);
840
841   demux->position_shift = 0;
842   demux->need_segment = TRUE;
843
844   demux->have_group_id = FALSE;
845   demux->group_id = G_MAXUINT;
846 }
847
848 static gboolean
849 gst_hls_demux_set_location (GstHLSDemux * demux, const gchar * uri)
850 {
851   if (demux->client)
852     gst_m3u8_client_free (demux->client);
853   demux->client = gst_m3u8_client_new (uri);
854   GST_INFO_OBJECT (demux, "Changed location: %s", uri);
855   return TRUE;
856 }
857
858 void
859 gst_hls_demux_updates_loop (GstHLSDemux * demux)
860 {
861   /* Loop for the updates. It's started when the first fragments are cached and
862    * schedules the next update of the playlist (for lives sources) and the next
863    * update of fragments. When a new fragment is downloaded, it compares the
864    * download time with the next scheduled update to check if we can or should
865    * switch to a different bitrate */
866
867   /* block until the next scheduled update or the signal to quit this thread */
868   g_mutex_lock (&demux->updates_timed_lock);
869   GST_DEBUG_OBJECT (demux, "Started updates task");
870   while (TRUE) {
871     if (demux->cancelled)
872       goto quit;
873
874     /* schedule the next update */
875     gst_hls_demux_schedule (demux);
876
877     /*  block until the next scheduled update or the signal to quit this thread */
878     GST_DEBUG_OBJECT (demux, "Waiting");
879     if (g_cond_timed_wait (GST_TASK_GET_COND (demux->updates_task),
880             &demux->updates_timed_lock, &demux->next_update)) {
881       GST_DEBUG_OBJECT (demux, "Unlocked");
882       goto quit;
883     }
884     GST_DEBUG_OBJECT (demux, "Continue");
885
886     if (demux->cancelled)
887       goto quit;
888
889     /* update the playlist for live sources */
890     if (gst_m3u8_client_is_live (demux->client)) {
891       if (!gst_hls_demux_update_playlist (demux, TRUE)) {
892         if (demux->cancelled)
893           goto quit;
894         demux->client->update_failed_count++;
895         if (demux->client->update_failed_count < DEFAULT_FAILED_COUNT) {
896           GST_WARNING_OBJECT (demux, "Could not update the playlist");
897           continue;
898         } else {
899           GST_ELEMENT_ERROR (demux, RESOURCE, NOT_FOUND,
900               ("Could not update the playlist"), (NULL));
901           goto error;
902         }
903       }
904     }
905
906     /* if it's a live source and the playlist couldn't be updated, there aren't
907      * more fragments in the playlist, so we just wait for the next schedulled
908      * update */
909     if (gst_m3u8_client_is_live (demux->client) &&
910         demux->client->update_failed_count > 0) {
911       GST_WARNING_OBJECT (demux,
912           "The playlist hasn't been updated, failed count is %d",
913           demux->client->update_failed_count);
914       continue;
915     }
916
917     if (demux->cancelled)
918       goto quit;
919
920     /* fetch the next fragment */
921     if (g_queue_is_empty (demux->queue)) {
922       GST_DEBUG_OBJECT (demux, "queue empty, get next fragment");
923       if (!gst_hls_demux_get_next_fragment (demux, FALSE)) {
924         if (demux->cancelled) {
925           goto quit;
926         } else if (!demux->end_of_playlist && !demux->cancelled) {
927           demux->client->update_failed_count++;
928           if (demux->client->update_failed_count < DEFAULT_FAILED_COUNT) {
929             GST_WARNING_OBJECT (demux, "Could not fetch the next fragment");
930             continue;
931           } else {
932             GST_ELEMENT_ERROR (demux, RESOURCE, NOT_FOUND,
933                 ("Could not fetch the next fragment"), (NULL));
934             goto error;
935           }
936         }
937       } else {
938         demux->client->update_failed_count = 0;
939
940         if (demux->cancelled)
941           goto quit;
942
943         /* try to switch to another bitrate if needed */
944         gst_hls_demux_switch_playlist (demux);
945       }
946     }
947   }
948
949 quit:
950   {
951     GST_DEBUG_OBJECT (demux, "Stopped updates task");
952     g_mutex_unlock (&demux->updates_timed_lock);
953     return;
954   }
955
956 error:
957   {
958     GST_DEBUG_OBJECT (demux, "Stopped updates task because of error");
959     gst_hls_demux_pause_tasks (demux, TRUE);
960     g_mutex_unlock (&demux->updates_timed_lock);
961   }
962 }
963
964 static gboolean
965 gst_hls_demux_cache_fragments (GstHLSDemux * demux)
966 {
967   gint i;
968
969   /* If this playlist is a variant playlist, select the first one
970    * and update it */
971   if (gst_m3u8_client_has_variant_playlist (demux->client)) {
972     GstM3U8 *child = NULL;
973
974     if (demux->connection_speed == 0) {
975
976       GST_M3U8_CLIENT_LOCK (demux->client);
977       child = demux->client->main->current_variant->data;
978       GST_M3U8_CLIENT_UNLOCK (demux->client);
979     } else {
980       GList *tmp = gst_m3u8_client_get_playlist_for_bitrate (demux->client,
981           demux->connection_speed);
982
983       child = GST_M3U8 (tmp->data);
984     }
985
986     gst_m3u8_client_set_current (demux->client, child);
987     if (!gst_hls_demux_update_playlist (demux, FALSE)) {
988       GST_ERROR_OBJECT (demux, "Could not fetch the child playlist %s",
989           child->uri);
990       return FALSE;
991     }
992   }
993
994   if (!gst_m3u8_client_is_live (demux->client)) {
995     GstClockTime duration = gst_m3u8_client_get_duration (demux->client);
996
997     GST_DEBUG_OBJECT (demux, "Sending duration message : %" GST_TIME_FORMAT,
998         GST_TIME_ARGS (duration));
999     if (duration != GST_CLOCK_TIME_NONE)
1000       gst_element_post_message (GST_ELEMENT (demux),
1001           gst_message_new_duration_changed (GST_OBJECT (demux)));
1002   }
1003
1004   /* Cache the first fragments */
1005   for (i = 0; i < demux->fragments_cache; i++) {
1006     gst_element_post_message (GST_ELEMENT (demux),
1007         gst_message_new_buffering (GST_OBJECT (demux),
1008             100 * i / demux->fragments_cache));
1009     g_get_current_time (&demux->next_update);
1010     if (!gst_hls_demux_get_next_fragment (demux, TRUE)) {
1011       if (demux->end_of_playlist)
1012         break;
1013       if (!demux->cancelled)
1014         GST_ERROR_OBJECT (demux, "Error caching the first fragments");
1015       return FALSE;
1016     }
1017     /* make sure we stop caching fragments if something cancelled it */
1018     if (demux->cancelled)
1019       return FALSE;
1020     gst_hls_demux_switch_playlist (demux);
1021   }
1022   gst_element_post_message (GST_ELEMENT (demux),
1023       gst_message_new_buffering (GST_OBJECT (demux), 100));
1024
1025   g_get_current_time (&demux->next_update);
1026
1027   demux->need_cache = FALSE;
1028   return TRUE;
1029
1030 }
1031
1032 static gchar *
1033 gst_hls_src_buf_to_utf8_playlist (GstBuffer * buf)
1034 {
1035   GstMapInfo info;
1036   gchar *playlist;
1037
1038   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1039     return NULL;
1040
1041   if (!g_utf8_validate ((gchar *) info.data, info.size, NULL))
1042     goto validate_error;
1043
1044   /* alloc size + 1 to end with a null character */
1045   playlist = g_malloc0 (info.size + 1);
1046   memcpy (playlist, info.data, info.size);
1047
1048   gst_buffer_unmap (buf, &info);
1049   gst_buffer_unref (buf);
1050   return playlist;
1051
1052 validate_error:
1053   gst_buffer_unmap (buf, &info);
1054   gst_buffer_unref (buf);
1055   return NULL;
1056 }
1057
1058 static gboolean
1059 gst_hls_demux_update_playlist (GstHLSDemux * demux, gboolean update)
1060 {
1061   GstFragment *download;
1062   GstBuffer *buf;
1063   gchar *playlist;
1064   gboolean updated = FALSE;
1065
1066   const gchar *uri = gst_m3u8_client_get_current_uri (demux->client);
1067
1068   download = gst_uri_downloader_fetch_uri (demux->downloader, uri);
1069
1070   if (download == NULL)
1071     return FALSE;
1072
1073   buf = gst_fragment_get_buffer (download);
1074   playlist = gst_hls_src_buf_to_utf8_playlist (buf);
1075   g_object_unref (download);
1076
1077   if (playlist == NULL) {
1078     GST_WARNING_OBJECT (demux, "Couldn't not validate playlist encoding");
1079     return FALSE;
1080   }
1081
1082   updated = gst_m3u8_client_update (demux->client, playlist);
1083
1084   /*  If it's a live source, do not let the sequence number go beyond
1085    * three fragments before the end of the list */
1086   if (updated && update == FALSE && demux->client->current &&
1087       gst_m3u8_client_is_live (demux->client)) {
1088     guint last_sequence;
1089
1090     GST_M3U8_CLIENT_LOCK (demux->client);
1091     last_sequence =
1092         GST_M3U8_MEDIA_FILE (g_list_last (demux->client->current->
1093             files)->data)->sequence;
1094
1095     if (demux->client->sequence >= last_sequence - 3) {
1096       GST_DEBUG_OBJECT (demux, "Sequence is beyond playlist. Moving back to %d",
1097           last_sequence - 3);
1098       demux->need_segment = TRUE;
1099       demux->client->sequence = last_sequence - 3;
1100     }
1101     GST_M3U8_CLIENT_UNLOCK (demux->client);
1102   }
1103
1104   return updated;
1105 }
1106
1107 static gboolean
1108 gst_hls_demux_change_playlist (GstHLSDemux * demux, guint max_bitrate)
1109 {
1110   GList *previous_variant, *current_variant;
1111   gint old_bandwidth, new_bandwidth;
1112
1113   /* If user specifies a connection speed never use a playlist with a bandwidth
1114    * superior than it */
1115   if (demux->connection_speed != 0 && max_bitrate > demux->connection_speed)
1116     max_bitrate = demux->connection_speed;
1117
1118   previous_variant = demux->client->main->current_variant;
1119   current_variant = gst_m3u8_client_get_playlist_for_bitrate (demux->client,
1120       max_bitrate);
1121
1122 retry_failover_protection:
1123   old_bandwidth = GST_M3U8 (previous_variant->data)->bandwidth;
1124   new_bandwidth = GST_M3U8 (current_variant->data)->bandwidth;
1125
1126   /* Don't do anything else if the playlist is the same */
1127   if (new_bandwidth == old_bandwidth) {
1128     return TRUE;
1129   }
1130
1131   demux->client->main->current_variant = current_variant;
1132   GST_M3U8_CLIENT_UNLOCK (demux->client);
1133
1134   gst_m3u8_client_set_current (demux->client, current_variant->data);
1135
1136   GST_INFO_OBJECT (demux, "Client was on %dbps, max allowed is %dbps, switching"
1137       " to bitrate %dbps", old_bandwidth, max_bitrate, new_bandwidth);
1138
1139   if (gst_hls_demux_update_playlist (demux, FALSE)) {
1140     GstStructure *s;
1141
1142     s = gst_structure_new ("playlist",
1143         "uri", G_TYPE_STRING, gst_m3u8_client_get_current_uri (demux->client),
1144         "bitrate", G_TYPE_INT, new_bandwidth, NULL);
1145     gst_element_post_message (GST_ELEMENT_CAST (demux),
1146         gst_message_new_element (GST_OBJECT_CAST (demux), s));
1147   } else {
1148     GList *failover = NULL;
1149
1150     GST_INFO_OBJECT (demux, "Unable to update playlist. Switching back");
1151     GST_M3U8_CLIENT_LOCK (demux->client);
1152
1153     failover = g_list_previous (current_variant);
1154     if (failover && new_bandwidth == GST_M3U8 (failover->data)->bandwidth) {
1155       current_variant = failover;
1156       goto retry_failover_protection;
1157     }
1158
1159     demux->client->main->current_variant = previous_variant;
1160     GST_M3U8_CLIENT_UNLOCK (demux->client);
1161     gst_m3u8_client_set_current (demux->client, previous_variant->data);
1162     /*  Try a lower bitrate (or stop if we just tried the lowest) */
1163     if (new_bandwidth ==
1164         GST_M3U8 (g_list_first (demux->client->main->lists)->data)->bandwidth)
1165       return FALSE;
1166     else
1167       return gst_hls_demux_change_playlist (demux, new_bandwidth - 1);
1168   }
1169
1170   /* Force typefinding since we might have changed media type */
1171   demux->do_typefind = TRUE;
1172
1173   return TRUE;
1174 }
1175
1176 static gboolean
1177 gst_hls_demux_schedule (GstHLSDemux * demux)
1178 {
1179   gfloat update_factor;
1180   gint count;
1181
1182   /* As defined in §6.3.4. Reloading the Playlist file:
1183    * "If the client reloads a Playlist file and finds that it has not
1184    * changed then it MUST wait for a period of time before retrying.  The
1185    * minimum delay is a multiple of the target duration.  This multiple is
1186    * 0.5 for the first attempt, 1.5 for the second, and 3.0 thereafter."
1187    */
1188   count = demux->client->update_failed_count;
1189   if (count < 3)
1190     update_factor = update_interval_factor[count];
1191   else
1192     update_factor = update_interval_factor[3];
1193
1194   /* schedule the next update using the target duration field of the
1195    * playlist */
1196   g_time_val_add (&demux->next_update,
1197       gst_m3u8_client_get_target_duration (demux->client)
1198       / GST_SECOND * G_USEC_PER_SEC * update_factor);
1199   GST_DEBUG_OBJECT (demux, "Next update scheduled at %s",
1200       g_time_val_to_iso8601 (&demux->next_update));
1201
1202   return TRUE;
1203 }
1204
1205 static gboolean
1206 gst_hls_demux_switch_playlist (GstHLSDemux * demux)
1207 {
1208   GTimeVal now;
1209   GstClockTime diff;
1210   gsize size;
1211   gint bitrate;
1212   GstFragment *fragment = g_queue_peek_tail (demux->queue);
1213   GstBuffer *buffer;
1214
1215   GST_M3U8_CLIENT_LOCK (demux->client);
1216   if (!demux->client->main->lists) {
1217     GST_M3U8_CLIENT_UNLOCK (demux->client);
1218     return TRUE;
1219   }
1220   GST_M3U8_CLIENT_UNLOCK (demux->client);
1221
1222   /* compare the time when the fragment was downloaded with the time when it was
1223    * scheduled */
1224   g_get_current_time (&now);
1225   diff = (GST_TIMEVAL_TO_TIME (now) - GST_TIMEVAL_TO_TIME (demux->next_update));
1226   buffer = gst_fragment_get_buffer (fragment);
1227   size = gst_buffer_get_size (buffer);
1228   bitrate = (size * 8) / ((double) diff / GST_SECOND);
1229
1230   GST_DEBUG ("Downloaded %d bytes in %" GST_TIME_FORMAT ". Bitrate is : %d",
1231       (guint) size, GST_TIME_ARGS (diff), bitrate);
1232
1233   gst_buffer_unref (buffer);
1234   return gst_hls_demux_change_playlist (demux, bitrate * demux->bitrate_limit);
1235 }
1236
1237 static GstFragment *
1238 gst_hls_demux_decrypt_fragment (GstHLSDemux * demux,
1239     GstFragment * encrypted_fragment, const gchar * key, const guint8 * iv)
1240 {
1241   GstFragment *key_fragment, *ret;
1242   GstBuffer *key_buffer, *encrypted_buffer, *decrypted_buffer;
1243   GstMapInfo key_info, encrypted_info, decrypted_info;
1244   gnutls_cipher_hd_t aes_ctx;
1245   gnutls_datum_t key_d, iv_d;
1246   gsize unpadded_size;
1247
1248   GST_INFO_OBJECT (demux, "Fetching key %s", key);
1249   key_fragment = gst_uri_downloader_fetch_uri (demux->downloader, key);
1250   if (key_fragment == NULL)
1251     return NULL;
1252
1253   key_buffer = gst_fragment_get_buffer (key_fragment);
1254   encrypted_buffer = gst_fragment_get_buffer (encrypted_fragment);
1255   decrypted_buffer =
1256       gst_buffer_new_allocate (NULL, gst_buffer_get_size (encrypted_buffer),
1257       NULL);
1258
1259   gst_buffer_map (key_buffer, &key_info, GST_MAP_READ);
1260   gst_buffer_map (encrypted_buffer, &encrypted_info, GST_MAP_READ);
1261   gst_buffer_map (decrypted_buffer, &decrypted_info, GST_MAP_WRITE);
1262
1263   key_d.data = key_info.data;
1264   key_d.size = 16;
1265   iv_d.data = (unsigned char *) iv;
1266   iv_d.size = 16;
1267   gnutls_cipher_init (&aes_ctx, gnutls_cipher_get_id ("AES-128-CBC"), &key_d,
1268       &iv_d);
1269   gnutls_cipher_decrypt2 (aes_ctx, encrypted_info.data, encrypted_info.size,
1270       decrypted_info.data, decrypted_info.size);
1271   gnutls_cipher_deinit (aes_ctx);
1272
1273   /* Handle pkcs7 unpadding here */
1274   unpadded_size =
1275       decrypted_info.size - decrypted_info.data[decrypted_info.size - 1];
1276
1277   gst_buffer_unmap (decrypted_buffer, &decrypted_info);
1278   gst_buffer_unmap (encrypted_buffer, &encrypted_info);
1279   gst_buffer_unmap (key_buffer, &key_info);
1280
1281   gst_buffer_resize (decrypted_buffer, 0, unpadded_size);
1282
1283   gst_buffer_unref (key_buffer);
1284   gst_buffer_unref (encrypted_buffer);
1285   g_object_unref (key_fragment);
1286   g_object_unref (encrypted_fragment);
1287
1288   ret = gst_fragment_new ();
1289   gst_fragment_add_buffer (ret, decrypted_buffer);
1290   ret->completed = TRUE;
1291
1292   return ret;
1293 }
1294
1295 static gboolean
1296 gst_hls_demux_get_next_fragment (GstHLSDemux * demux, gboolean caching)
1297 {
1298   GstFragment *download;
1299   const gchar *next_fragment_uri;
1300   GstClockTime duration;
1301   GstClockTime timestamp;
1302   GstBuffer *buf;
1303   gboolean discont;
1304   const gchar *key = NULL;
1305   const guint8 *iv = NULL;
1306
1307   if (!gst_m3u8_client_get_next_fragment (demux->client, &discont,
1308           &next_fragment_uri, &duration, &timestamp, &key, &iv)) {
1309     GST_INFO_OBJECT (demux, "This playlist doesn't contain more fragments");
1310     demux->end_of_playlist = TRUE;
1311     gst_task_start (demux->stream_task);
1312     return FALSE;
1313   }
1314
1315   GST_INFO_OBJECT (demux, "Fetching next fragment %s", next_fragment_uri);
1316
1317   download = gst_uri_downloader_fetch_uri (demux->downloader,
1318       next_fragment_uri);
1319
1320   if (download && key)
1321     download = gst_hls_demux_decrypt_fragment (demux, download, key, iv);
1322
1323   if (download == NULL)
1324     goto error;
1325
1326   buf = gst_fragment_get_buffer (download);
1327
1328   GST_BUFFER_DURATION (buf) = duration;
1329   GST_BUFFER_PTS (buf) = timestamp;
1330
1331   /* We actually need to do this every time we switch bitrate */
1332   if (G_UNLIKELY (demux->do_typefind)) {
1333     GstCaps *caps = gst_fragment_get_caps (download);
1334
1335     if (!demux->input_caps || !gst_caps_is_equal (caps, demux->input_caps)) {
1336       gst_caps_replace (&demux->input_caps, caps);
1337       /* gst_pad_set_caps (demux->srcpad, demux->input_caps); */
1338       GST_INFO_OBJECT (demux, "Input source caps: %" GST_PTR_FORMAT,
1339           demux->input_caps);
1340       demux->do_typefind = FALSE;
1341     }
1342     gst_caps_unref (caps);
1343   } else {
1344     gst_fragment_set_caps (download, demux->input_caps);
1345   }
1346
1347   if (discont) {
1348     GST_DEBUG_OBJECT (demux, "Marking fragment as discontinuous");
1349     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1350   }
1351
1352   GST_DEBUG_OBJECT (demux, "Pushing fragment in queue");
1353   g_queue_push_tail (demux->queue, download);
1354   if (!caching) {
1355     GST_TASK_SIGNAL (demux->updates_task);
1356     gst_task_start (demux->stream_task);
1357   }
1358   return TRUE;
1359
1360 error:
1361   {
1362     gst_hls_demux_stop (demux);
1363     return FALSE;
1364   }
1365 }