splitmuxsink: Don't accumulate more than 2 GOPs
[platform/upstream/gst-plugins-good.git] / gst / multifile / gstsplitmuxsink.c
1 /* GStreamer Muxer bin that splits output stream by size/time
2  * Copyright (C) <2014> Jan Schmidt <jan@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:element-splitmuxsink
22  * @short_description: Muxer wrapper for splitting output stream by size or time
23  *
24  * This element wraps a muxer and a sink, and starts a new file when the mux
25  * contents are about to cross a threshold of maximum size of maximum time,
26  * splitting at video keyframe boundaries. Exactly one input video stream
27  * is required, with as many accompanying audio and subtitle streams as
28  * desired.
29  *
30  * By default, it uses mp4mux and filesink, but they can be changed via
31  * the 'muxer' and 'sink' properties.
32  *
33  * The minimum file size is 1 GOP, however - so limits may be overrun if the
34  * distance between any 2 keyframes is larger than the limits.
35  *
36  * The splitting process is driven by the video stream contents, and
37  * the video stream must contain closed GOPs for the output file parts
38  * to be played individually correctly.
39  *
40  * <refsect2>
41  * <title>Example pipelines</title>
42  * |[
43  * gst-launch-1.0 -e v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! queue ! timeoverlay ! x264enc key-int-max=10 ! h264parse ! splitmuxsink location=video%02d.mov max-size-time=10000000000 max-size-bytes=1000000
44  * ]|
45  * Records a video stream captured from a v4l2 device and muxes it into
46  * ISO mp4 files, splitting as needed to limit size/duration to 10 seconds
47  * and 1MB maximum size.
48  * </refsect2>
49  */
50
51 #ifdef HAVE_CONFIG_H
52 #include "config.h"
53 #endif
54
55 #include <string.h>
56 #include "gstsplitmuxsink.h"
57
58 GST_DEBUG_CATEGORY_STATIC (splitmux_debug);
59 #define GST_CAT_DEFAULT splitmux_debug
60
61 #define GST_SPLITMUX_LOCK(s) g_mutex_lock(&(s)->lock)
62 #define GST_SPLITMUX_UNLOCK(s) g_mutex_unlock(&(s)->lock)
63 #define GST_SPLITMUX_WAIT(s) g_cond_wait (&(s)->data_cond, &(s)->lock)
64 #define GST_SPLITMUX_BROADCAST(s) g_cond_broadcast (&(s)->data_cond)
65
66 enum
67 {
68   PROP_0,
69   PROP_LOCATION,
70   PROP_MAX_SIZE_TIME,
71   PROP_MAX_SIZE_BYTES,
72   PROP_MUXER_OVERHEAD,
73   PROP_MUXER,
74   PROP_SINK
75 };
76
77 #define DEFAULT_MAX_SIZE_TIME       0
78 #define DEFAULT_MAX_SIZE_BYTES      0
79 #define DEFAULT_MUXER_OVERHEAD      0.02
80 #define DEFAULT_MUXER "mp4mux"
81 #define DEFAULT_SINK "filesink"
82
83 static GstStaticPadTemplate video_sink_template =
84 GST_STATIC_PAD_TEMPLATE ("video",
85     GST_PAD_SINK,
86     GST_PAD_REQUEST,
87     GST_STATIC_CAPS_ANY);
88 static GstStaticPadTemplate audio_sink_template =
89 GST_STATIC_PAD_TEMPLATE ("audio_%u",
90     GST_PAD_SINK,
91     GST_PAD_REQUEST,
92     GST_STATIC_CAPS_ANY);
93 static GstStaticPadTemplate subtitle_sink_template =
94 GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
95     GST_PAD_SINK,
96     GST_PAD_REQUEST,
97     GST_STATIC_CAPS_ANY);
98
99 static GQuark PAD_CONTEXT;
100
101 static void
102 _do_init (void)
103 {
104   PAD_CONTEXT = g_quark_from_static_string ("pad-context");
105 }
106
107 #define gst_splitmux_sink_parent_class parent_class
108 G_DEFINE_TYPE_EXTENDED (GstSplitMuxSink, gst_splitmux_sink, GST_TYPE_BIN, 0,
109     _do_init ());
110
111 static gboolean create_elements (GstSplitMuxSink * splitmux);
112 static gboolean create_sink (GstSplitMuxSink * splitmux);
113 static void gst_splitmux_sink_set_property (GObject * object, guint prop_id,
114     const GValue * value, GParamSpec * pspec);
115 static void gst_splitmux_sink_get_property (GObject * object, guint prop_id,
116     GValue * value, GParamSpec * pspec);
117 static void gst_splitmux_sink_dispose (GObject * object);
118 static void gst_splitmux_sink_finalize (GObject * object);
119
120 static GstPad *gst_splitmux_sink_request_new_pad (GstElement * element,
121     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
122 static void gst_splitmux_sink_release_pad (GstElement * element, GstPad * pad);
123
124 static GstStateChangeReturn gst_splitmux_sink_change_state (GstElement *
125     element, GstStateChange transition);
126
127 static void bus_handler (GstBin * bin, GstMessage * msg);
128 static void set_next_filename (GstSplitMuxSink * splitmux);
129 static void start_next_fragment (GstSplitMuxSink * splitmux);
130 static void check_queue_length (GstSplitMuxSink * splitmux, MqStreamCtx * ctx);
131 static void mq_stream_ctx_unref (MqStreamCtx * ctx);
132
133 static MqStreamBuf *
134 mq_stream_buf_new (void)
135 {
136   return g_slice_new0 (MqStreamBuf);
137 }
138
139 static void
140 mq_stream_buf_free (MqStreamBuf * data)
141 {
142   g_slice_free (MqStreamBuf, data);
143 }
144
145 static void
146 gst_splitmux_sink_class_init (GstSplitMuxSinkClass * klass)
147 {
148   GObjectClass *gobject_class = (GObjectClass *) klass;
149   GstElementClass *gstelement_class = (GstElementClass *) klass;
150   GstBinClass *gstbin_class = (GstBinClass *) klass;
151
152   gobject_class->set_property = gst_splitmux_sink_set_property;
153   gobject_class->get_property = gst_splitmux_sink_get_property;
154   gobject_class->dispose = gst_splitmux_sink_dispose;
155   gobject_class->finalize = gst_splitmux_sink_finalize;
156
157   gst_element_class_set_static_metadata (gstelement_class,
158       "Split Muxing Bin", "Generic/Bin/Muxer",
159       "Convenience bin that muxes incoming streams into multiple time/size limited files",
160       "Jan Schmidt <jan@centricular.com>");
161
162   gst_element_class_add_pad_template (gstelement_class,
163       gst_static_pad_template_get (&video_sink_template));
164   gst_element_class_add_pad_template (gstelement_class,
165       gst_static_pad_template_get (&audio_sink_template));
166   gst_element_class_add_pad_template (gstelement_class,
167       gst_static_pad_template_get (&subtitle_sink_template));
168
169   gstelement_class->change_state =
170       GST_DEBUG_FUNCPTR (gst_splitmux_sink_change_state);
171   gstelement_class->request_new_pad =
172       GST_DEBUG_FUNCPTR (gst_splitmux_sink_request_new_pad);
173   gstelement_class->release_pad =
174       GST_DEBUG_FUNCPTR (gst_splitmux_sink_release_pad);
175
176   gstbin_class->handle_message = bus_handler;
177
178   g_object_class_install_property (gobject_class, PROP_LOCATION,
179       g_param_spec_string ("location", "File Output Pattern",
180           "Format string pattern for the location of the files to write (e.g. video%05d.mp4)",
181           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
182   g_object_class_install_property (gobject_class, PROP_MUXER_OVERHEAD,
183       g_param_spec_double ("mux-overhead", "Muxing Overhead",
184           "Extra size overhead of muxing (0.02 = 2%)", 0.0, 1.0,
185           DEFAULT_MUXER_OVERHEAD,
186           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
187
188   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
189       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
190           "Max. amount of time per file (in ns, 0=disable)", 0, G_MAXUINT64,
191           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
193       g_param_spec_uint64 ("max-size-bytes", "Max. size bytes",
194           "Max. amount of data per file (in bytes, 0=disable)", 0, G_MAXUINT64,
195           DEFAULT_MAX_SIZE_BYTES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
196
197   g_object_class_install_property (gobject_class, PROP_MUXER,
198       g_param_spec_object ("muxer", "Muxer",
199           "The muxer element to use (NULL = default mp4mux)",
200           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201   g_object_class_install_property (gobject_class, PROP_SINK,
202       g_param_spec_object ("sink", "Sink",
203           "The sink element (or element chain) to use (NULL = default filesink)",
204           GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
205 }
206
207 static void
208 gst_splitmux_sink_init (GstSplitMuxSink * splitmux)
209 {
210   g_mutex_init (&splitmux->lock);
211   g_cond_init (&splitmux->data_cond);
212
213   splitmux->mux_overhead = DEFAULT_MUXER_OVERHEAD;
214   splitmux->threshold_time = DEFAULT_MAX_SIZE_TIME;
215   splitmux->threshold_bytes = DEFAULT_MAX_SIZE_BYTES;
216
217   GST_OBJECT_FLAG_SET (splitmux, GST_ELEMENT_FLAG_SINK);
218 }
219
220 static void
221 gst_splitmux_reset (GstSplitMuxSink * splitmux)
222 {
223   if (splitmux->mq)
224     gst_bin_remove (GST_BIN (splitmux), splitmux->mq);
225   if (splitmux->muxer)
226     gst_bin_remove (GST_BIN (splitmux), splitmux->muxer);
227   if (splitmux->active_sink)
228     gst_bin_remove (GST_BIN (splitmux), splitmux->active_sink);
229
230   splitmux->sink = splitmux->active_sink = splitmux->muxer = splitmux->mq =
231       NULL;
232 }
233
234 static void
235 gst_splitmux_sink_dispose (GObject * object)
236 {
237   GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
238
239   G_OBJECT_CLASS (parent_class)->dispose (object);
240
241   /* Calling parent dispose invalidates all child pointers */
242   splitmux->sink = splitmux->active_sink = splitmux->muxer = splitmux->mq =
243       NULL;
244 }
245
246 static void
247 gst_splitmux_sink_finalize (GObject * object)
248 {
249   GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
250   g_cond_clear (&splitmux->data_cond);
251   g_mutex_clear (&splitmux->lock);
252   if (splitmux->provided_sink)
253     gst_object_unref (splitmux->provided_sink);
254   if (splitmux->provided_muxer)
255     gst_object_unref (splitmux->provided_muxer);
256
257   g_free (splitmux->location);
258
259   /* Make sure to free any un-released contexts */
260   g_list_foreach (splitmux->contexts, (GFunc) mq_stream_ctx_unref, NULL);
261   g_list_free (splitmux->contexts);
262
263   G_OBJECT_CLASS (parent_class)->finalize (object);
264 }
265
266 static void
267 gst_splitmux_sink_set_property (GObject * object, guint prop_id,
268     const GValue * value, GParamSpec * pspec)
269 {
270   GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
271
272   switch (prop_id) {
273     case PROP_LOCATION:{
274       GST_OBJECT_LOCK (splitmux);
275       g_free (splitmux->location);
276       splitmux->location = g_value_dup_string (value);
277       GST_OBJECT_UNLOCK (splitmux);
278       break;
279     }
280     case PROP_MAX_SIZE_BYTES:
281       GST_OBJECT_LOCK (splitmux);
282       splitmux->threshold_bytes = g_value_get_uint64 (value);
283       GST_OBJECT_UNLOCK (splitmux);
284       break;
285     case PROP_MAX_SIZE_TIME:
286       GST_OBJECT_LOCK (splitmux);
287       splitmux->threshold_time = g_value_get_uint64 (value);
288       GST_OBJECT_UNLOCK (splitmux);
289       break;
290     case PROP_MUXER_OVERHEAD:
291       GST_OBJECT_LOCK (splitmux);
292       splitmux->mux_overhead = g_value_get_double (value);
293       GST_OBJECT_UNLOCK (splitmux);
294       break;
295     case PROP_SINK:
296       GST_OBJECT_LOCK (splitmux);
297       if (splitmux->provided_sink)
298         gst_object_unref (splitmux->provided_sink);
299       splitmux->provided_sink = g_value_dup_object (value);
300       GST_OBJECT_UNLOCK (splitmux);
301       break;
302     case PROP_MUXER:
303       GST_OBJECT_LOCK (splitmux);
304       if (splitmux->provided_muxer)
305         gst_object_unref (splitmux->provided_muxer);
306       splitmux->provided_muxer = g_value_dup_object (value);
307       GST_OBJECT_UNLOCK (splitmux);
308       break;
309     default:
310       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
311       break;
312   }
313 }
314
315 static void
316 gst_splitmux_sink_get_property (GObject * object, guint prop_id,
317     GValue * value, GParamSpec * pspec)
318 {
319   GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
320
321   switch (prop_id) {
322     case PROP_LOCATION:
323       GST_OBJECT_LOCK (splitmux);
324       g_value_set_string (value, splitmux->location);
325       GST_OBJECT_UNLOCK (splitmux);
326       break;
327     case PROP_MAX_SIZE_BYTES:
328       GST_OBJECT_LOCK (splitmux);
329       g_value_set_uint64 (value, splitmux->threshold_bytes);
330       GST_OBJECT_UNLOCK (splitmux);
331       break;
332     case PROP_MAX_SIZE_TIME:
333       GST_OBJECT_LOCK (splitmux);
334       g_value_set_uint64 (value, splitmux->threshold_time);
335       GST_OBJECT_UNLOCK (splitmux);
336       break;
337     case PROP_MUXER_OVERHEAD:
338       GST_OBJECT_LOCK (splitmux);
339       g_value_set_double (value, splitmux->mux_overhead);
340       GST_OBJECT_UNLOCK (splitmux);
341       break;
342     case PROP_SINK:
343       GST_OBJECT_LOCK (splitmux);
344       g_value_set_object (value, splitmux->provided_sink);
345       GST_OBJECT_UNLOCK (splitmux);
346       break;
347     case PROP_MUXER:
348       GST_OBJECT_LOCK (splitmux);
349       g_value_set_object (value, splitmux->provided_muxer);
350       GST_OBJECT_UNLOCK (splitmux);
351       break;
352     default:
353       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
354       break;
355   }
356 }
357
358 static GstPad *
359 mq_sink_to_src (GstElement * mq, GstPad * sink_pad)
360 {
361   gchar *tmp, *sinkname, *srcname;
362   GstPad *mq_src;
363
364   sinkname = gst_pad_get_name (sink_pad);
365   tmp = sinkname + 5;
366   srcname = g_strdup_printf ("src_%s", tmp);
367
368   mq_src = gst_element_get_static_pad (mq, srcname);
369
370   g_free (sinkname);
371   g_free (srcname);
372
373   return mq_src;
374 }
375
376 static gboolean
377 get_pads_from_mq (GstSplitMuxSink * splitmux, GstPad ** sink_pad,
378     GstPad ** src_pad)
379 {
380   GstPad *mq_sink;
381   GstPad *mq_src;
382
383   /* Request a pad from multiqueue, then connect this one, then
384    * discover the corresponding output pad and return both */
385   mq_sink = gst_element_get_request_pad (splitmux->mq, "sink_%u");
386   if (mq_sink == NULL)
387     return FALSE;
388
389   mq_src = mq_sink_to_src (splitmux->mq, mq_sink);
390   if (mq_src == NULL)
391     goto fail;
392
393   *sink_pad = mq_sink;
394   *src_pad = mq_src;
395
396   return TRUE;
397
398 fail:
399   gst_element_release_request_pad (splitmux->mq, mq_sink);
400   return FALSE;
401 }
402
403 static MqStreamCtx *
404 mq_stream_ctx_new (GstSplitMuxSink * splitmux)
405 {
406   MqStreamCtx *ctx;
407
408   ctx = g_new0 (MqStreamCtx, 1);
409   g_atomic_int_set (&ctx->refcount, 1);
410   ctx->splitmux = splitmux;
411   gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
412   gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
413   ctx->in_running_time = ctx->out_running_time = 0;
414   g_queue_init (&ctx->queued_bufs);
415   return ctx;
416 }
417
418 static void
419 mq_stream_ctx_free (MqStreamCtx * ctx)
420 {
421   g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
422   g_queue_clear (&ctx->queued_bufs);
423   g_free (ctx);
424 }
425
426 static void
427 mq_stream_ctx_unref (MqStreamCtx * ctx)
428 {
429   if (g_atomic_int_dec_and_test (&ctx->refcount))
430     mq_stream_ctx_free (ctx);
431 }
432
433 static void
434 mq_stream_ctx_ref (MqStreamCtx * ctx)
435 {
436   g_atomic_int_inc (&ctx->refcount);
437 }
438
439 static void
440 _pad_block_destroy_sink_notify (MqStreamCtx * ctx)
441 {
442   ctx->sink_pad_block_id = 0;
443   mq_stream_ctx_unref (ctx);
444 }
445
446 static void
447 _pad_block_destroy_src_notify (MqStreamCtx * ctx)
448 {
449   ctx->src_pad_block_id = 0;
450   mq_stream_ctx_unref (ctx);
451 }
452
453 /* Called with lock held, drops the lock to send EOS to the
454  * pad
455  */
456 static void
457 send_eos (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
458 {
459   GstEvent *eos;
460   GstPad *pad;
461
462   eos = gst_event_new_eos ();
463   pad = gst_pad_get_peer (ctx->srcpad);
464
465   ctx->out_eos = TRUE;
466
467   GST_INFO_OBJECT (splitmux, "Sending EOS on %" GST_PTR_FORMAT, pad);
468   GST_SPLITMUX_UNLOCK (splitmux);
469   gst_pad_send_event (pad, eos);
470   GST_SPLITMUX_LOCK (splitmux);
471
472   gst_object_unref (pad);
473 }
474
475 /* Called with splitmux lock held to check if this output
476  * context needs to sleep to wait for the release of the
477  * next GOP, or to send EOS to close out the current file
478  */
479 static void
480 complete_or_wait_on_out (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
481 {
482   do {
483
484     GST_LOG_OBJECT (ctx->srcpad,
485         "Checking running time %" GST_TIME_FORMAT " against max %"
486         GST_TIME_FORMAT, GST_TIME_ARGS (ctx->out_running_time),
487         GST_TIME_ARGS (splitmux->max_out_running_time));
488
489     if (splitmux->max_out_running_time == GST_CLOCK_TIME_NONE ||
490         ctx->out_running_time < splitmux->max_out_running_time)
491       return;
492
493     if (ctx->flushing || splitmux->state == SPLITMUX_STATE_STOPPED)
494       return;
495
496     if (splitmux->state == SPLITMUX_STATE_ENDING_FILE) {
497       if (ctx->out_eos == FALSE) {
498         send_eos (splitmux, ctx);
499         continue;
500       }
501     } else if (splitmux->state == SPLITMUX_STATE_START_NEXT_FRAGMENT) {
502       start_next_fragment (splitmux);
503       continue;
504     }
505
506     GST_INFO_OBJECT (ctx->srcpad,
507         "Sleeping for running time %"
508         GST_TIME_FORMAT " (max %" GST_TIME_FORMAT ")",
509         GST_TIME_ARGS (ctx->out_running_time),
510         GST_TIME_ARGS (splitmux->max_out_running_time));
511     ctx->out_blocked = TRUE;
512     /* Expand the mq if needed before sleeping */
513     check_queue_length (splitmux, ctx);
514     GST_SPLITMUX_WAIT (splitmux);
515     ctx->out_blocked = FALSE;
516     GST_INFO_OBJECT (ctx->srcpad,
517         "Woken for new max running time %" GST_TIME_FORMAT,
518         GST_TIME_ARGS (splitmux->max_out_running_time));
519   } while (1);
520 }
521
522 static GstPadProbeReturn
523 handle_mq_output (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
524 {
525   GstSplitMuxSink *splitmux = ctx->splitmux;
526   MqStreamBuf *buf_info = NULL;
527
528   GST_LOG_OBJECT (pad, "Fired probe type 0x%x\n", info->type);
529
530   /* FIXME: Handle buffer lists, until then make it clear they won't work */
531   if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
532     g_warning ("Buffer list handling not implemented");
533     return GST_PAD_PROBE_DROP;
534   }
535   if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) {
536     GstEvent *event = gst_pad_probe_info_get_event (info);
537
538     GST_LOG_OBJECT (pad, "Event %" GST_PTR_FORMAT, event);
539
540     switch (GST_EVENT_TYPE (event)) {
541       case GST_EVENT_SEGMENT:
542         gst_event_copy_segment (event, &ctx->out_segment);
543         break;
544       case GST_EVENT_FLUSH_STOP:
545         GST_SPLITMUX_LOCK (splitmux);
546         gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
547         g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
548         g_queue_clear (&ctx->queued_bufs);
549         ctx->flushing = FALSE;
550         GST_SPLITMUX_UNLOCK (splitmux);
551         break;
552       case GST_EVENT_FLUSH_START:
553         GST_SPLITMUX_LOCK (splitmux);
554         GST_LOG_OBJECT (pad, "Flush start");
555         ctx->flushing = TRUE;
556         GST_SPLITMUX_BROADCAST (splitmux);
557         GST_SPLITMUX_UNLOCK (splitmux);
558         break;
559       case GST_EVENT_EOS:
560         GST_SPLITMUX_LOCK (splitmux);
561         if (splitmux->state == SPLITMUX_STATE_STOPPED)
562           goto beach;
563         ctx->out_eos = TRUE;
564         GST_SPLITMUX_UNLOCK (splitmux);
565         break;
566       case GST_EVENT_GAP:{
567         GstClockTime gap_ts;
568
569         gst_event_parse_gap (event, &gap_ts, NULL);
570         if (gap_ts == GST_CLOCK_TIME_NONE)
571           break;
572
573         GST_SPLITMUX_LOCK (splitmux);
574
575         gap_ts = gst_segment_to_running_time (&ctx->out_segment,
576             GST_FORMAT_TIME, gap_ts);
577
578         GST_LOG_OBJECT (pad, "Have GAP w/ ts %" GST_TIME_FORMAT,
579             GST_TIME_ARGS (gap_ts));
580
581         if (splitmux->state == SPLITMUX_STATE_STOPPED)
582           goto beach;
583         ctx->out_running_time = gap_ts;
584         complete_or_wait_on_out (splitmux, ctx);
585         GST_SPLITMUX_UNLOCK (splitmux);
586         break;
587       }
588       default:
589         break;
590     }
591     return GST_PAD_PROBE_PASS;
592   }
593
594   /* Allow everything through until the configured next stopping point */
595   GST_SPLITMUX_LOCK (splitmux);
596
597   buf_info = g_queue_pop_tail (&ctx->queued_bufs);
598   if (buf_info == NULL)
599     /* Can only happen due to a poorly timed flush */
600     goto beach;
601
602   /* If we have popped a keyframe, decrement the queued_gop count */
603   if (buf_info->keyframe && splitmux->queued_gops > 0)
604     splitmux->queued_gops--;
605
606   ctx->out_running_time = buf_info->run_ts;
607
608   GST_LOG_OBJECT (splitmux,
609       "Pad %" GST_PTR_FORMAT " buffer with TS %" GST_TIME_FORMAT
610       " size %" G_GSIZE_FORMAT,
611       pad, GST_TIME_ARGS (ctx->out_running_time), buf_info->buf_size);
612
613   complete_or_wait_on_out (splitmux, ctx);
614
615   if (splitmux->muxed_out_time == GST_CLOCK_TIME_NONE ||
616       splitmux->muxed_out_time < buf_info->run_ts)
617     splitmux->muxed_out_time = buf_info->run_ts;
618
619   splitmux->muxed_out_bytes += buf_info->buf_size;
620
621 #ifndef GST_DISABLE_GST_DEBUG
622   {
623     GstBuffer *buf = gst_pad_probe_info_get_buffer (info);
624     GST_LOG_OBJECT (pad, "Returning to pass buffer %" GST_PTR_FORMAT
625         " run ts %" GST_TIME_FORMAT, buf,
626         GST_TIME_ARGS (ctx->out_running_time));
627   }
628 #endif
629
630   GST_SPLITMUX_UNLOCK (splitmux);
631
632   mq_stream_buf_free (buf_info);
633
634   return GST_PAD_PROBE_PASS;
635
636 beach:
637   GST_SPLITMUX_UNLOCK (splitmux);
638   return GST_PAD_PROBE_DROP;
639 }
640
641 static gboolean
642 resend_sticky (GstPad * pad, GstEvent ** event, GstPad * peer)
643 {
644   return gst_pad_send_event (peer, gst_event_ref (*event));
645 }
646
647 static void
648 restart_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
649 {
650   GstPad *peer = gst_pad_get_peer (ctx->srcpad);
651
652   gst_pad_sticky_events_foreach (ctx->srcpad,
653       (GstPadStickyEventsForeachFunction) (resend_sticky), peer);
654
655   /* Clear EOS flag */
656   ctx->out_eos = FALSE;
657
658   gst_object_unref (peer);
659 }
660
661 /* Called with lock held when a fragment
662  * reaches EOS and it is time to restart
663  * a new fragment
664  */
665 static void
666 start_next_fragment (GstSplitMuxSink * splitmux)
667 {
668   /* 1 change to new file */
669   gst_element_set_state (splitmux->muxer, GST_STATE_NULL);
670   gst_element_set_state (splitmux->active_sink, GST_STATE_NULL);
671
672   set_next_filename (splitmux);
673
674   gst_element_sync_state_with_parent (splitmux->active_sink);
675   gst_element_sync_state_with_parent (splitmux->muxer);
676
677   g_list_foreach (splitmux->contexts, (GFunc) restart_context, splitmux);
678
679   /* Switch state and go back to processing */
680   splitmux->state = SPLITMUX_STATE_COLLECTING_GOP_START;
681   if (!splitmux->video_ctx->in_eos)
682     splitmux->max_out_running_time = splitmux->video_ctx->in_running_time;
683   else
684     splitmux->max_out_running_time = GST_CLOCK_TIME_NONE;
685
686   /* Store the overflow parameters as the basis for the next fragment */
687   splitmux->mux_start_time = splitmux->muxed_out_time;
688   splitmux->mux_start_bytes = splitmux->muxed_out_bytes;
689
690   GST_DEBUG_OBJECT (splitmux,
691       "Restarting flow for new fragment. New running time %" GST_TIME_FORMAT,
692       GST_TIME_ARGS (splitmux->max_out_running_time));
693
694   GST_SPLITMUX_BROADCAST (splitmux);
695 }
696
697 static void
698 bus_handler (GstBin * bin, GstMessage * message)
699 {
700   GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (bin);
701
702   switch (GST_MESSAGE_TYPE (message)) {
703     case GST_MESSAGE_EOS:
704       /* If the state is draining out the current file, drop this EOS */
705       GST_SPLITMUX_LOCK (splitmux);
706       if (splitmux->state == SPLITMUX_STATE_ENDING_FILE &&
707           splitmux->max_out_running_time != GST_CLOCK_TIME_NONE) {
708         GST_DEBUG_OBJECT (splitmux, "Caught EOS at end of fragment, dropping");
709         splitmux->state = SPLITMUX_STATE_START_NEXT_FRAGMENT;
710         GST_SPLITMUX_BROADCAST (splitmux);
711
712         gst_message_unref (message);
713         GST_SPLITMUX_UNLOCK (splitmux);
714         return;
715       }
716       GST_SPLITMUX_UNLOCK (splitmux);
717       break;
718     default:
719       break;
720   }
721
722   GST_BIN_CLASS (parent_class)->handle_message (bin, message);
723 }
724
725 /* Called with splitmux lock held */
726 /* Called when entering ProcessingCompleteGop state
727  * Assess if mq contents overflowed the current file
728  *   -> If yes, need to switch to new file
729  *   -> if no, set max_out_running_time to let this GOP in and
730  *      go to COLLECTING_GOP_START state
731  */
732 static void
733 handle_gathered_gop (GstSplitMuxSink * splitmux)
734 {
735   GList *cur;
736   gsize queued_bytes = 0;
737   GstClockTime queued_time = 0;
738
739   /* Assess if the multiqueue contents overflowed the current file */
740   for (cur = g_list_first (splitmux->contexts);
741       cur != NULL; cur = g_list_next (cur)) {
742     MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
743     if (tmpctx->in_running_time > queued_time)
744       queued_time = tmpctx->in_running_time;
745     queued_bytes += tmpctx->in_bytes;
746   }
747
748   g_assert (queued_bytes >= splitmux->mux_start_bytes);
749   g_assert (queued_time >= splitmux->mux_start_time);
750
751   queued_bytes -= splitmux->mux_start_bytes;
752   queued_time -= splitmux->mux_start_time;
753
754   /* Expand queued bytes estimate by muxer overhead */
755   queued_bytes += (queued_bytes * splitmux->mux_overhead);
756
757   GST_LOG_OBJECT (splitmux, "mq at TS %" GST_TIME_FORMAT
758       " bytes %" G_GSIZE_FORMAT, GST_TIME_ARGS (queued_time), queued_bytes);
759
760   /* Check for overrun - have we output at least one byte and overrun
761    * either threshold? */
762   if ((splitmux->mux_start_bytes < splitmux->muxed_out_bytes) &&
763       ((splitmux->threshold_bytes > 0 &&
764               queued_bytes >= splitmux->threshold_bytes) ||
765           (splitmux->threshold_time > 0 &&
766               queued_time >= splitmux->threshold_time))) {
767
768     splitmux->state = SPLITMUX_STATE_ENDING_FILE;
769
770     GST_INFO_OBJECT (splitmux,
771         "mq overflowed since last, draining out. max out TS is %"
772         GST_TIME_FORMAT, GST_TIME_ARGS (splitmux->max_out_running_time));
773     GST_SPLITMUX_BROADCAST (splitmux);
774
775   } else {
776     /* No overflow */
777     GST_LOG_OBJECT (splitmux,
778         "This GOP didn't overflow the fragment. Bytes sent %" G_GSIZE_FORMAT
779         " queued %" G_GSIZE_FORMAT " time %" GST_TIME_FORMAT " Continuing.",
780         splitmux->muxed_out_bytes - splitmux->mux_start_bytes,
781         queued_bytes, GST_TIME_ARGS (queued_time));
782
783     /* Wake everyone up to push this one GOP, then sleep */
784     splitmux->state = SPLITMUX_STATE_COLLECTING_GOP_START;
785     if (!splitmux->video_ctx->in_eos)
786       splitmux->max_out_running_time = splitmux->video_ctx->in_running_time;
787     else
788       splitmux->max_out_running_time = GST_CLOCK_TIME_NONE;
789
790     GST_LOG_OBJECT (splitmux, "Waking output for complete GOP, TS %"
791         GST_TIME_FORMAT, GST_TIME_ARGS (splitmux->max_out_running_time));
792     GST_SPLITMUX_BROADCAST (splitmux);
793   }
794
795 }
796
797 /* Called with splitmux lock held */
798 /* Called from each input pad when it is has all the pieces
799  * for a GOP or EOS, starting with the video pad which has set the
800  * splitmux->max_in_running_time
801  */
802 static void
803 check_completed_gop (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
804 {
805   GList *cur;
806   gboolean ready = TRUE;
807
808   if (splitmux->state == SPLITMUX_STATE_WAITING_GOP_COMPLETE) {
809     /* Iterate each pad, and check that the input running time is at least
810      * up to the video runnning time, and if so handle the collected GOP */
811     GST_LOG_OBJECT (splitmux, "Checking GOP collected, ctx %p", ctx);
812     for (cur = g_list_first (splitmux->contexts);
813         cur != NULL; cur = g_list_next (cur)) {
814       MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
815
816       GST_LOG_OBJECT (splitmux,
817           "Context %p (src pad %" GST_PTR_FORMAT ") TS %" GST_TIME_FORMAT
818           " EOS %d", tmpctx, tmpctx->srcpad,
819           GST_TIME_ARGS (tmpctx->in_running_time), tmpctx->in_eos);
820
821       if (tmpctx->in_running_time < splitmux->max_in_running_time &&
822           !tmpctx->in_eos) {
823         GST_LOG_OBJECT (splitmux,
824             "Context %p (src pad %" GST_PTR_FORMAT ") not ready. We'll sleep",
825             tmpctx, tmpctx->srcpad);
826         ready = FALSE;
827         break;
828       }
829     }
830     if (ready) {
831       GST_DEBUG_OBJECT (splitmux,
832           "Collected GOP is complete. Processing (ctx %p)", ctx);
833       /* All pads have a complete GOP, release it into the multiqueue */
834       handle_gathered_gop (splitmux);
835     }
836   }
837
838   /* Some pad is not yet ready, or GOP is being pushed
839    * either way, sleep and wait to get woken */
840   while ((splitmux->state == SPLITMUX_STATE_WAITING_GOP_COMPLETE ||
841           splitmux->state == SPLITMUX_STATE_START_NEXT_FRAGMENT) &&
842       !ctx->flushing) {
843
844     GST_LOG_OBJECT (splitmux, "Sleeping for %s (ctx %p)",
845         splitmux->state == SPLITMUX_STATE_WAITING_GOP_COMPLETE ?
846         "GOP complete" : "EOF draining", ctx);
847     GST_SPLITMUX_WAIT (splitmux);
848
849     GST_LOG_OBJECT (splitmux, "Done waiting for complete GOP (ctx %p)", ctx);
850   }
851 }
852
853 static void
854 check_queue_length (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
855 {
856   GList *cur;
857   guint cur_len = g_queue_get_length (&ctx->queued_bufs);
858
859   GST_DEBUG_OBJECT (ctx->sinkpad,
860       "Checking queue length len %u cur_max %u queued gops %u",
861       cur_len, splitmux->mq_max_buffers, splitmux->queued_gops);
862
863   if (cur_len >= splitmux->mq_max_buffers) {
864     gboolean allow_grow = FALSE;
865
866     /* If collecting a GOP and this pad might block,
867      * and there isn't already a pending GOP in the queue
868      * then grow
869      */
870     if (splitmux->state == SPLITMUX_STATE_WAITING_GOP_COMPLETE &&
871         ctx->in_running_time < splitmux->max_in_running_time &&
872         splitmux->queued_gops <= 1) {
873       allow_grow = TRUE;
874     } else if (splitmux->state == SPLITMUX_STATE_COLLECTING_GOP_START &&
875         ctx->is_video && splitmux->queued_gops <= 1) {
876       allow_grow = TRUE;
877     }
878
879     if (!allow_grow) {
880       for (cur = g_list_first (splitmux->contexts);
881           cur != NULL; cur = g_list_next (cur)) {
882         MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
883         GST_DEBUG_OBJECT (tmpctx->sinkpad,
884             " len %u out_blocked %d",
885             g_queue_get_length (&tmpctx->queued_bufs), tmpctx->out_blocked);
886         /* If another stream is starving, grow */
887         if (tmpctx != ctx && g_queue_get_length (&tmpctx->queued_bufs) < 1) {
888           allow_grow = TRUE;
889         }
890       }
891     }
892
893     if (allow_grow) {
894       splitmux->mq_max_buffers = cur_len + 1;
895
896       GST_INFO_OBJECT (splitmux,
897           "Multiqueue overrun - enlarging to %u buffers ctx %p",
898           splitmux->mq_max_buffers, ctx);
899
900       g_object_set (splitmux->mq, "max-size-buffers",
901           splitmux->mq_max_buffers, NULL);
902     }
903   }
904 }
905
906 static GstPadProbeReturn
907 handle_mq_input (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
908 {
909   GstSplitMuxSink *splitmux = ctx->splitmux;
910   GstBuffer *buf;
911   MqStreamBuf *buf_info = NULL;
912   GstClockTime ts;
913   gboolean loop_again;
914   gboolean keyframe = FALSE;
915
916   GST_LOG_OBJECT (pad, "Fired probe type 0x%x\n", info->type);
917
918   /* FIXME: Handle buffer lists, until then make it clear they won't work */
919   if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
920     g_warning ("Buffer list handling not implemented");
921     return GST_PAD_PROBE_DROP;
922   }
923   if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) {
924     GstEvent *event = gst_pad_probe_info_get_event (info);
925     switch (GST_EVENT_TYPE (event)) {
926       case GST_EVENT_SEGMENT:
927         gst_event_copy_segment (event, &ctx->in_segment);
928         break;
929       case GST_EVENT_FLUSH_STOP:
930         GST_SPLITMUX_LOCK (splitmux);
931         gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
932         ctx->in_eos = FALSE;
933         ctx->in_bytes = 0;
934         ctx->in_running_time = 0;
935         GST_SPLITMUX_UNLOCK (splitmux);
936         break;
937       case GST_EVENT_EOS:
938         GST_SPLITMUX_LOCK (splitmux);
939         ctx->in_eos = TRUE;
940
941         if (splitmux->state == SPLITMUX_STATE_STOPPED)
942           goto beach;
943
944         if (ctx->is_video) {
945           GST_INFO_OBJECT (splitmux, "Got Video EOS. Finishing up");
946           /* Act as if this is a new keyframe with infinite timestamp */
947           splitmux->max_in_running_time = GST_CLOCK_TIME_NONE;
948           splitmux->state = SPLITMUX_STATE_WAITING_GOP_COMPLETE;
949           /* Wake up other input pads to collect this GOP */
950           GST_SPLITMUX_BROADCAST (splitmux);
951           check_completed_gop (splitmux, ctx);
952         } else if (splitmux->state == SPLITMUX_STATE_WAITING_GOP_COMPLETE) {
953           /* If we are waiting for a GOP to be completed (ie, for aux
954            * pads to catch up), then this pad is complete, so check
955            * if the whole GOP is.
956            */
957           check_completed_gop (splitmux, ctx);
958         }
959         GST_SPLITMUX_UNLOCK (splitmux);
960         break;
961       default:
962         break;
963     }
964     return GST_PAD_PROBE_PASS;
965   }
966
967   buf = gst_pad_probe_info_get_buffer (info);
968   ctx->in_running_time = gst_segment_to_running_time (&ctx->in_segment,
969       GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (buf));
970   buf_info = mq_stream_buf_new ();
971
972   if (GST_BUFFER_PTS_IS_VALID (buf))
973     ts = GST_BUFFER_PTS (buf);
974   else
975     ts = GST_BUFFER_DTS (buf);
976
977   GST_SPLITMUX_LOCK (splitmux);
978
979   if (splitmux->state == SPLITMUX_STATE_STOPPED)
980     goto beach;
981
982   /* If this buffer has a timestamp, advance the input timestamp of the
983    * stream */
984   if (GST_CLOCK_TIME_IS_VALID (ts)) {
985     GstClockTime running_time =
986         gst_segment_to_running_time (&ctx->in_segment, GST_FORMAT_TIME,
987         GST_BUFFER_TIMESTAMP (buf));
988
989     if (GST_CLOCK_TIME_IS_VALID (running_time) &&
990         (ctx->in_running_time == GST_CLOCK_TIME_NONE
991             || running_time > ctx->in_running_time))
992       ctx->in_running_time = running_time;
993   }
994
995   /* Try to make sure we have a valid running time */
996   if (!GST_CLOCK_TIME_IS_VALID (ctx->in_running_time)) {
997     ctx->in_running_time =
998         gst_segment_to_running_time (&ctx->in_segment, GST_FORMAT_TIME,
999         ctx->in_segment.start);
1000   }
1001
1002   buf_info->run_ts = ctx->in_running_time;
1003   buf_info->buf_size = gst_buffer_get_size (buf);
1004
1005   /* Update total input byte counter for overflow detect */
1006   ctx->in_bytes += buf_info->buf_size;
1007
1008   GST_DEBUG_OBJECT (pad, "Buf TS %" GST_TIME_FORMAT
1009       " total in_bytes %" G_GSIZE_FORMAT,
1010       GST_TIME_ARGS (buf_info->run_ts), ctx->in_bytes);
1011
1012   loop_again = TRUE;
1013   do {
1014     if (ctx->flushing)
1015       break;
1016
1017     switch (splitmux->state) {
1018       case SPLITMUX_STATE_COLLECTING_GOP_START:
1019         if (ctx->is_video) {
1020           /* If a keyframe, we have a complete GOP */
1021           if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) ||
1022               !GST_CLOCK_TIME_IS_VALID (ctx->in_running_time) ||
1023               splitmux->max_in_running_time >= ctx->in_running_time) {
1024             /* Pass this buffer through */
1025             loop_again = FALSE;
1026             break;
1027           }
1028           GST_INFO_OBJECT (pad,
1029               "Have keyframe with running time %" GST_TIME_FORMAT,
1030               GST_TIME_ARGS (ctx->in_running_time));
1031           keyframe = TRUE;
1032           splitmux->state = SPLITMUX_STATE_WAITING_GOP_COMPLETE;
1033           splitmux->max_in_running_time = ctx->in_running_time;
1034           /* Wake up other input pads to collect this GOP */
1035           GST_SPLITMUX_BROADCAST (splitmux);
1036           check_completed_gop (splitmux, ctx);
1037         } else {
1038           /* We're still waiting for a keyframe on the video pad, sleep */
1039           GST_LOG_OBJECT (pad, "Sleeping for GOP start");
1040           GST_SPLITMUX_WAIT (splitmux);
1041           GST_LOG_OBJECT (pad, "Done sleeping for GOP start state now %d",
1042               splitmux->state);
1043         }
1044         break;
1045       case SPLITMUX_STATE_WAITING_GOP_COMPLETE:
1046         /* After a GOP start is found, this buffer might complete the GOP */
1047         /* If we overran the target timestamp, it might be time to process
1048          * the GOP, otherwise bail out for more data
1049          */
1050         GST_LOG_OBJECT (pad,
1051             "Checking TS %" GST_TIME_FORMAT " against max %" GST_TIME_FORMAT,
1052             GST_TIME_ARGS (ctx->in_running_time),
1053             GST_TIME_ARGS (splitmux->max_in_running_time));
1054
1055         if (ctx->in_running_time < splitmux->max_in_running_time) {
1056           loop_again = FALSE;
1057           break;
1058         }
1059
1060         GST_LOG_OBJECT (pad,
1061             "Collected last packet of GOP. Checking other pads");
1062         check_completed_gop (splitmux, ctx);
1063         break;
1064       case SPLITMUX_STATE_ENDING_FILE:
1065       case SPLITMUX_STATE_START_NEXT_FRAGMENT:
1066         /* A fragment is ending, wait until that's done before continuing */
1067         GST_DEBUG_OBJECT (pad, "Sleeping for fragment restart");
1068         GST_SPLITMUX_WAIT (splitmux);
1069         GST_DEBUG_OBJECT (pad,
1070             "Done sleeping for fragment restart state now %d", splitmux->state);
1071         break;
1072       default:
1073         loop_again = FALSE;
1074         break;
1075     }
1076   } while (loop_again);
1077
1078   if (keyframe) {
1079     splitmux->queued_gops++;
1080     buf_info->keyframe = TRUE;
1081   }
1082
1083   /* Now add this buffer to the queue just before returning */
1084   g_queue_push_head (&ctx->queued_bufs, buf_info);
1085
1086   /* Check the buffer will fit in the mq */
1087   check_queue_length (splitmux, ctx);
1088
1089   GST_LOG_OBJECT (pad, "Returning to queue buffer %" GST_PTR_FORMAT
1090       " run ts %" GST_TIME_FORMAT, buf, GST_TIME_ARGS (ctx->in_running_time));
1091
1092   GST_SPLITMUX_UNLOCK (splitmux);
1093   return GST_PAD_PROBE_PASS;
1094
1095 beach:
1096   GST_SPLITMUX_UNLOCK (splitmux);
1097   if (buf_info)
1098     mq_stream_buf_free (buf_info);
1099   return GST_PAD_PROBE_PASS;
1100 }
1101
1102 static GstPad *
1103 gst_splitmux_sink_request_new_pad (GstElement * element,
1104     GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
1105 {
1106   GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
1107   GstPadTemplate *mux_template = NULL;
1108   GstPad *res = NULL;
1109   GstPad *mq_sink, *mq_src;
1110   gchar *gname;
1111   gboolean is_video = FALSE;
1112   MqStreamCtx *ctx;
1113
1114   GST_DEBUG_OBJECT (element, "templ:%s, name:%s", templ->name_template, name);
1115
1116   GST_SPLITMUX_LOCK (splitmux);
1117   if (!create_elements (splitmux))
1118     goto fail;
1119
1120   if (templ->name_template) {
1121     if (g_str_equal (templ->name_template, "video")) {
1122       /* FIXME: Look for a pad template with matching caps, rather than by name */
1123       mux_template =
1124           gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
1125           (splitmux->muxer), "video_%u");
1126       is_video = TRUE;
1127       name = NULL;
1128     } else {
1129       mux_template =
1130           gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
1131           (splitmux->muxer), templ->name_template);
1132     }
1133   }
1134
1135   res = gst_element_request_pad (splitmux->muxer, mux_template, name, caps);
1136   if (res == NULL)
1137     goto fail;
1138
1139   if (is_video)
1140     gname = g_strdup ("video");
1141   else if (name == NULL)
1142     gname = gst_pad_get_name (res);
1143   else
1144     gname = g_strdup (name);
1145
1146   if (!get_pads_from_mq (splitmux, &mq_sink, &mq_src)) {
1147     gst_element_release_request_pad (splitmux->muxer, res);
1148     gst_object_unref (GST_OBJECT (res));
1149     goto fail;
1150   }
1151
1152   if (gst_pad_link (mq_src, res) != GST_PAD_LINK_OK) {
1153     gst_element_release_request_pad (splitmux->muxer, res);
1154     gst_object_unref (GST_OBJECT (res));
1155     gst_element_release_request_pad (splitmux->mq, mq_sink);
1156     gst_object_unref (GST_OBJECT (mq_sink));
1157     goto fail;
1158   }
1159
1160   gst_object_unref (GST_OBJECT (res));
1161
1162   ctx = mq_stream_ctx_new (splitmux);
1163   ctx->is_video = is_video;
1164   ctx->srcpad = mq_src;
1165   ctx->sinkpad = mq_sink;
1166
1167   mq_stream_ctx_ref (ctx);
1168   ctx->src_pad_block_id =
1169       gst_pad_add_probe (mq_src, GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM,
1170       (GstPadProbeCallback) handle_mq_output, ctx, (GDestroyNotify)
1171       _pad_block_destroy_src_notify);
1172   if (is_video)
1173     splitmux->video_ctx = ctx;
1174
1175   res = gst_ghost_pad_new (gname, mq_sink);
1176   g_object_set_qdata ((GObject *) (res), PAD_CONTEXT, ctx);
1177
1178   mq_stream_ctx_ref (ctx);
1179   ctx->sink_pad_block_id =
1180       gst_pad_add_probe (mq_sink, GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM,
1181       (GstPadProbeCallback) handle_mq_input, ctx, (GDestroyNotify)
1182       _pad_block_destroy_sink_notify);
1183
1184   GST_DEBUG_OBJECT (splitmux, "Request pad %" GST_PTR_FORMAT
1185       " is mq pad %" GST_PTR_FORMAT, res, mq_sink);
1186
1187   splitmux->contexts = g_list_prepend (splitmux->contexts, ctx);
1188
1189   g_free (gname);
1190
1191   gst_object_unref (mq_sink);
1192   gst_object_unref (mq_src);
1193
1194   gst_pad_set_active (res, TRUE);
1195   gst_element_add_pad (element, res);
1196   GST_SPLITMUX_UNLOCK (splitmux);
1197
1198   return res;
1199 fail:
1200   GST_SPLITMUX_UNLOCK (splitmux);
1201   return NULL;
1202 }
1203
1204 static void
1205 gst_splitmux_sink_release_pad (GstElement * element, GstPad * pad)
1206 {
1207   GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
1208   GstPad *mqsink, *mqsrc, *muxpad;
1209   MqStreamCtx *ctx =
1210       (MqStreamCtx *) (g_object_get_qdata ((GObject *) (pad), PAD_CONTEXT));
1211
1212   GST_SPLITMUX_LOCK (splitmux);
1213
1214   if (splitmux->muxer == NULL || splitmux->mq == NULL)
1215     goto fail;                  /* Elements don't exist yet - nothing to release */
1216
1217   GST_INFO_OBJECT (pad, "releasing request pad");
1218
1219   mqsink = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
1220   mqsrc = mq_sink_to_src (splitmux->mq, mqsink);
1221   muxpad = gst_pad_get_peer (mqsrc);
1222
1223   /* Remove the context from our consideration */
1224   splitmux->contexts = g_list_remove (splitmux->contexts, ctx);
1225
1226   if (ctx->sink_pad_block_id)
1227     gst_pad_remove_probe (ctx->sinkpad, ctx->sink_pad_block_id);
1228
1229   if (ctx->src_pad_block_id)
1230     gst_pad_remove_probe (ctx->srcpad, ctx->src_pad_block_id);
1231
1232   /* Can release the context now */
1233   mq_stream_ctx_unref (ctx);
1234
1235   /* Release and free the mq input */
1236   gst_element_release_request_pad (splitmux->mq, mqsink);
1237
1238   /* Release and free the muxer input */
1239   gst_element_release_request_pad (splitmux->muxer, muxpad);
1240
1241   gst_object_unref (mqsink);
1242   gst_object_unref (mqsrc);
1243   gst_object_unref (muxpad);
1244
1245   gst_element_remove_pad (element, pad);
1246
1247 fail:
1248   GST_SPLITMUX_UNLOCK (splitmux);
1249 }
1250
1251 static GstElement *
1252 create_element (GstSplitMuxSink * splitmux,
1253     const gchar * factory, const gchar * name)
1254 {
1255   GstElement *ret = gst_element_factory_make (factory, name);
1256   if (ret == NULL) {
1257     g_warning ("Failed to create %s - splitmuxsink will not work", name);
1258     return NULL;
1259   }
1260
1261   if (!gst_bin_add (GST_BIN (splitmux), ret)) {
1262     g_warning ("Could not add %s element - splitmuxsink will not work", name);
1263     gst_object_unref (ret);
1264     return NULL;
1265   }
1266
1267   return ret;
1268 }
1269
1270 static gboolean
1271 create_elements (GstSplitMuxSink * splitmux)
1272 {
1273   /* Create internal elements */
1274   if (splitmux->mq == NULL) {
1275     if ((splitmux->mq =
1276             create_element (splitmux, "multiqueue", "multiqueue")) == NULL)
1277       goto fail;
1278
1279     splitmux->mq_max_buffers = 5;
1280     /* No bytes or time limit, we limit buffers manually */
1281     g_object_set (splitmux->mq, "max-size-bytes", 0, "max-size-time",
1282         (guint64) 0, "max-size-buffers", splitmux->mq_max_buffers, NULL);
1283   }
1284
1285   if (splitmux->muxer == NULL) {
1286     GstElement *provided_muxer = NULL;
1287
1288     GST_OBJECT_LOCK (splitmux);
1289     if (splitmux->provided_muxer != NULL)
1290       provided_muxer = gst_object_ref (splitmux->provided_muxer);
1291     GST_OBJECT_UNLOCK (splitmux);
1292
1293     if (provided_muxer == NULL) {
1294       if ((splitmux->muxer =
1295               create_element (splitmux, "mp4mux", "muxer")) == NULL)
1296         goto fail;
1297     } else {
1298       if (!gst_bin_add (GST_BIN (splitmux), provided_muxer)) {
1299         g_warning ("Could not add muxer element - splitmuxsink will not work");
1300         gst_object_unref (provided_muxer);
1301         goto fail;
1302       }
1303
1304       splitmux->muxer = provided_muxer;
1305       gst_object_unref (provided_muxer);
1306     }
1307   }
1308
1309   return TRUE;
1310 fail:
1311   return FALSE;
1312 }
1313
1314 static GstElement *
1315 find_sink (GstElement * e)
1316 {
1317   GstElement *res = NULL;
1318   GstIterator *iter;
1319   gboolean done = FALSE;
1320   GValue data = { 0, };
1321
1322   if (!GST_IS_BIN (e))
1323     return e;
1324
1325   iter = gst_bin_iterate_sinks (GST_BIN (e));
1326   while (!done) {
1327     switch (gst_iterator_next (iter, &data)) {
1328       case GST_ITERATOR_OK:
1329       {
1330         GstElement *child = g_value_get_object (&data);
1331         if (g_object_class_find_property (G_OBJECT_GET_CLASS (child),
1332                 "location") != NULL) {
1333           res = child;
1334           done = TRUE;
1335         }
1336         g_value_reset (&data);
1337         break;
1338       }
1339       case GST_ITERATOR_RESYNC:
1340         gst_iterator_resync (iter);
1341         break;
1342       case GST_ITERATOR_DONE:
1343         done = TRUE;
1344         break;
1345       case GST_ITERATOR_ERROR:
1346         g_assert_not_reached ();
1347         break;
1348     }
1349   }
1350   g_value_unset (&data);
1351   gst_iterator_free (iter);
1352
1353   return res;
1354 }
1355
1356 static gboolean
1357 create_sink (GstSplitMuxSink * splitmux)
1358 {
1359   GstElement *provided_sink = NULL;
1360
1361   g_return_val_if_fail (splitmux->active_sink == NULL, TRUE);
1362
1363   GST_OBJECT_LOCK (splitmux);
1364   if (splitmux->provided_sink != NULL)
1365     provided_sink = gst_object_ref (splitmux->provided_sink);
1366   GST_OBJECT_UNLOCK (splitmux);
1367
1368   if (provided_sink == NULL) {
1369     if ((splitmux->sink =
1370             create_element (splitmux, DEFAULT_SINK, "sink")) == NULL)
1371       goto fail;
1372     splitmux->active_sink = splitmux->sink;
1373   } else {
1374     if (!gst_bin_add (GST_BIN (splitmux), provided_sink)) {
1375       g_warning ("Could not add sink elements - splitmuxsink will not work");
1376       gst_object_unref (provided_sink);
1377       goto fail;
1378     }
1379
1380     splitmux->active_sink = provided_sink;
1381
1382     /* The bin holds a ref now, we can drop our tmp ref */
1383     gst_object_unref (provided_sink);
1384
1385     /* Find the sink element */
1386     splitmux->sink = find_sink (splitmux->active_sink);
1387     if (splitmux->sink == NULL) {
1388       g_warning
1389           ("Could not locate sink element in provided sink - splitmuxsink will not work");
1390       goto fail;
1391     }
1392   }
1393
1394   if (!gst_element_link (splitmux->muxer, splitmux->active_sink)) {
1395     g_warning ("Failed to link muxer and sink- splitmuxsink will not work");
1396     goto fail;
1397   }
1398
1399   return TRUE;
1400 fail:
1401   return FALSE;
1402 }
1403
1404 #ifdef __GNUC__
1405 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1406 #endif
1407 static void
1408 set_next_filename (GstSplitMuxSink * splitmux)
1409 {
1410   if (splitmux->location) {
1411     gchar *fname;
1412
1413     fname = g_strdup_printf (splitmux->location, splitmux->fragment_id);
1414     GST_INFO_OBJECT (splitmux, "Setting file to %s", fname);
1415     g_object_set (splitmux->sink, "location", fname, NULL);
1416     g_free (fname);
1417
1418     splitmux->fragment_id++;
1419   }
1420 }
1421
1422 static GstStateChangeReturn
1423 gst_splitmux_sink_change_state (GstElement * element, GstStateChange transition)
1424 {
1425   GstStateChangeReturn ret;
1426   GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
1427
1428   switch (transition) {
1429     case GST_STATE_CHANGE_NULL_TO_READY:{
1430       GST_SPLITMUX_LOCK (splitmux);
1431       if (!create_elements (splitmux) || !create_sink (splitmux)) {
1432         ret = GST_STATE_CHANGE_FAILURE;
1433         GST_SPLITMUX_UNLOCK (splitmux);
1434         goto beach;
1435       }
1436       GST_SPLITMUX_UNLOCK (splitmux);
1437       splitmux->fragment_id = 0;
1438       set_next_filename (splitmux);
1439       break;
1440     }
1441     case GST_STATE_CHANGE_READY_TO_PAUSED:{
1442       GST_SPLITMUX_LOCK (splitmux);
1443       /* Start by collecting one input on each pad */
1444       splitmux->state = SPLITMUX_STATE_COLLECTING_GOP_START;
1445       splitmux->max_in_running_time = 0;
1446       splitmux->muxed_out_time = splitmux->mux_start_time = 0;
1447       splitmux->muxed_out_bytes = splitmux->mux_start_bytes = 0;
1448       GST_SPLITMUX_UNLOCK (splitmux);
1449       break;
1450     }
1451     case GST_STATE_CHANGE_PAUSED_TO_READY:
1452     case GST_STATE_CHANGE_READY_TO_NULL:
1453       GST_SPLITMUX_LOCK (splitmux);
1454       splitmux->state = SPLITMUX_STATE_STOPPED;
1455       /* Wake up any blocked threads */
1456       GST_LOG_OBJECT (splitmux,
1457           "State change -> NULL or READY. Waking threads");
1458       GST_SPLITMUX_BROADCAST (splitmux);
1459       GST_SPLITMUX_UNLOCK (splitmux);
1460       break;
1461     default:
1462       break;
1463   }
1464
1465   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1466   if (ret == GST_STATE_CHANGE_FAILURE)
1467     goto beach;
1468
1469   switch (transition) {
1470     case GST_STATE_CHANGE_READY_TO_NULL:
1471       GST_SPLITMUX_LOCK (splitmux);
1472       splitmux->fragment_id = 0;
1473       gst_splitmux_reset (splitmux);
1474       GST_SPLITMUX_UNLOCK (splitmux);
1475       break;
1476     default:
1477       break;
1478   }
1479
1480 beach:
1481
1482   if (transition == GST_STATE_CHANGE_NULL_TO_READY &&
1483       ret == GST_STATE_CHANGE_FAILURE) {
1484     /* Cleanup elements on failed transition out of NULL */
1485     gst_splitmux_reset (splitmux);
1486   }
1487   return ret;
1488 }
1489
1490 gboolean
1491 register_splitmuxsink (GstPlugin * plugin)
1492 {
1493   GST_DEBUG_CATEGORY_INIT (splitmux_debug, "splitmuxsink", 0,
1494       "Split File Muxing Sink");
1495
1496   return gst_element_register (plugin, "splitmuxsink", GST_RANK_NONE,
1497       GST_TYPE_SPLITMUX_SINK);
1498 }