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