Debian Codegraph @

gst/multifile/gstsplitmuxsink.c

raw symbols SCIP
1 /* GStreamer Muxer bin that splits output stream by size/time
2 * Copyright (C) <2014-2019> Jan Schmidt <[email protected]>
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 * @title: splitmuxsink
23 * @short_description: Muxer wrapper for splitting output stream by size or time
24 *
25 * This element wraps a muxer and a sink, and starts a new file when the mux
26 * contents are about to cross a threshold of maximum size of maximum time,
27 * splitting at video keyframe boundaries. Exactly one input video stream
28 * can be muxed, with as many accompanying audio and subtitle streams as
29 * desired.
30 *
31 * By default, it uses mp4mux and filesink, but they can be changed via
32 * the 'muxer' and 'sink' properties.
33 *
34 * The minimum file size is 1 GOP, however - so limits may be overrun if the
35 * distance between any 2 keyframes is larger than the limits.
36 *
37 * If a video stream is available, the splitting process is driven by the video
38 * stream contents, and the video stream must contain closed GOPs for the output
39 * file parts to be played individually correctly. In the absence of a video
40 * stream, the first available stream is used as reference for synchronization.
41 *
42 * In the async-finalize mode, when the threshold is crossed, the old muxer
43 * and sink is disconnected from the pipeline and left to finish the file
44 * asynchronously, and a new muxer and sink is created to continue with the
45 * next fragment. For that reason, instead of muxer and sink objects, the
46 * muxer-factory and sink-factory properties are used to construct the new
47 * objects, together with muxer-properties and sink-properties.
48 *
49 * ## Example pipelines
50 * |[
51 * 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
52 * ]|
53 * Records a video stream captured from a v4l2 device and muxes it into
54 * ISO mp4 files, splitting as needed to limit size/duration to 10 seconds
55 * and 1MB maximum size.
56 *
57 * |[
58 * 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.mkv max-size-time=10000000000 muxer-factory=matroskamux muxer-properties="properties,streamable=true"
59 * ]|
60 * Records a video stream captured from a v4l2 device and muxer it into
61 * streamable Matroska files, splitting as needed to limit size/duration to 10
62 * seconds. Each file will finalize asynchronously.
63 *
64 * |[
65 * gst-launch-1.0 videotestsrc num-buffers=10 ! jpegenc ! .video splitmuxsink muxer=qtmux muxer-pad-map=x-pad-map,video=video_1 location=test%05d.mp4 -v
66 * ]|
67 * Records 10 frames to an mp4 file, using a muxer-pad-map to make explicit mappings between the splitmuxsink sink pad and the corresponding muxer pad
68 * it will deliver to.
69 */
70
71 #ifdef HAVE_CONFIG_H
72 #include "config.h"
73 #endif
74
75 #include <string.h>
76 #include <glib/gstdio.h>
77 #include <gst/video/video.h>
78 #include "gstsplitmuxsink.h"
79 #include "location-utils.h"
80
81 GST_DEBUG_CATEGORY_STATIC (splitmux_debug);
82 #define GST_CAT_DEFAULT splitmux_debug
83
84 #define GST_SPLITMUX_STATE_LOCK(s) g_mutex_lock(&(s)->state_lock)
85 #define GST_SPLITMUX_STATE_UNLOCK(s) g_mutex_unlock(&(s)->state_lock)
86
87 #define GST_SPLITMUX_LOCK(s) g_mutex_lock(&(s)->lock)
88 #define GST_SPLITMUX_UNLOCK(s) g_mutex_unlock(&(s)->lock)
89 #define GST_SPLITMUX_WAIT_INPUT(s) g_cond_wait (&(s)->input_cond, &(s)->lock)
90 #define GST_SPLITMUX_BROADCAST_INPUT(s) g_cond_broadcast (&(s)->input_cond)
91
92 #define GST_SPLITMUX_WAIT_OUTPUT(s) g_cond_wait (&(s)->output_cond, &(s)->lock)
93 #define GST_SPLITMUX_BROADCAST_OUTPUT(s) g_cond_broadcast (&(s)->output_cond)
94
95 static void split_now (GstSplitMuxSink * splitmux);
96 static void split_after (GstSplitMuxSink * splitmux);
97 static void split_at_running_time (GstSplitMuxSink * splitmux,
98 GstClockTime split_time);
99
100 enum
101 {
102 PROP_0,
103 PROP_LOCATION,
104 PROP_START_INDEX,
105 PROP_MAX_SIZE_TIME,
106 PROP_MAX_SIZE_BYTES,
107 PROP_MAX_SIZE_TIMECODE,
108 PROP_SEND_KEYFRAME_REQUESTS,
109 PROP_MAX_FILES,
110 PROP_MUXER_OVERHEAD,
111 PROP_USE_ROBUST_MUXING,
112 PROP_ALIGNMENT_THRESHOLD,
113 PROP_MUXER,
114 PROP_SINK,
115 PROP_RESET_MUXER,
116 PROP_ASYNC_FINALIZE,
117 PROP_MUXER_FACTORY,
118 PROP_MUXER_PRESET,
119 PROP_MUXER_PROPERTIES,
120 PROP_SINK_FACTORY,
121 PROP_SINK_PRESET,
122 PROP_SINK_PROPERTIES,
123 PROP_MUXERPAD_MAP
124 };
125
126 #define DEFAULT_MAX_SIZE_TIME 0
127 #define DEFAULT_MAX_SIZE_BYTES 0
128 #define DEFAULT_MAX_FILES 0
129 #define DEFAULT_MUXER_OVERHEAD 0.02
130 #define DEFAULT_SEND_KEYFRAME_REQUESTS FALSE
131 #define DEFAULT_ALIGNMENT_THRESHOLD 0
132 #define DEFAULT_MUXER "mp4mux"
133 #define DEFAULT_SINK "filesink"
134 #define DEFAULT_USE_ROBUST_MUXING FALSE
135 #define DEFAULT_RESET_MUXER TRUE
136 #define DEFAULT_ASYNC_FINALIZE FALSE
137 #define DEFAULT_START_INDEX 0
138
139 typedef struct _AsyncEosHelper
140 {
141 MqStreamCtx *ctx;
142 GstPad *pad;
143 } AsyncEosHelper;
144
145 enum
146 {
147 SIGNAL_FORMAT_LOCATION,
148 SIGNAL_FORMAT_LOCATION_FULL,
149 SIGNAL_SPLIT_NOW,
150 SIGNAL_SPLIT_AFTER,
151 SIGNAL_SPLIT_AT_RUNNING_TIME,
152 SIGNAL_MUXER_ADDED,
153 SIGNAL_SINK_ADDED,
154 SIGNAL_LAST
155 };
156
157 static guint signals[SIGNAL_LAST];
158
159 static GstStaticPadTemplate video_sink_template =
160 GST_STATIC_PAD_TEMPLATE ("video",
161 GST_PAD_SINK,
162 GST_PAD_REQUEST,
163 GST_STATIC_CAPS_ANY);
164 static GstStaticPadTemplate video_aux_sink_template =
165 GST_STATIC_PAD_TEMPLATE ("video_aux_%u",
166 GST_PAD_SINK,
167 GST_PAD_REQUEST,
168 GST_STATIC_CAPS_ANY);
169 static GstStaticPadTemplate audio_sink_template =
170 GST_STATIC_PAD_TEMPLATE ("audio_%u",
171 GST_PAD_SINK,
172 GST_PAD_REQUEST,
173 GST_STATIC_CAPS_ANY);
174 static GstStaticPadTemplate subtitle_sink_template =
175 GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
176 GST_PAD_SINK,
177 GST_PAD_REQUEST,
178 GST_STATIC_CAPS_ANY);
179 static GstStaticPadTemplate caption_sink_template =
180 GST_STATIC_PAD_TEMPLATE ("caption_%u",
181 GST_PAD_SINK,
182 GST_PAD_REQUEST,
183 GST_STATIC_CAPS_ANY);
184
185 static GQuark PAD_CONTEXT;
186 static GQuark EOS_FROM_US;
187 static GQuark SINK_FRAGMENT_INFO;
188 static GQuark SENT_FRAGMENT_CLOSED;
189 /* EOS_FROM_US is only valid in async-finalize mode. We need to know whether
190 * to forward an incoming EOS message, but we cannot rely on the state of the
191 * splitmux anymore, so we set this qdata on the sink instead.
192 * The muxer and sink must be destroyed after both of these things have
193 * finished:
194 * 1) The EOS message has been sent when the fragment is ending
195 * 2) The muxer has been unlinked and relinked
196 * Therefore, EOS_FROM_US can have these two values:
197 * 0: EOS was not requested from us. Forward the message. The muxer and the
198 * sink will be destroyed together with the rest of the bin.
199 * 1: EOS was requested from us, but the other of the two tasks hasn't
200 * finished. Set EOS_FROM_US to 2 and do your stuff.
201 * 2: EOS was requested from us and the other of the two tasks has finished.
202 * Now we can destroy the muxer and the sink.
203 */
204
205 static void
206 _do_init (void)
207 {
208 PAD_CONTEXT = g_quark_from_static_string ("splitmuxsink-pad-context");
209 EOS_FROM_US = g_quark_from_static_string ("splitmuxsink-eos-from-us");
210 SINK_FRAGMENT_INFO =
211 g_quark_from_static_string ("splitmuxsink-fragment-info");
212 SENT_FRAGMENT_CLOSED =
213 g_quark_from_static_string ("splitmuxsink-sent-fragment-closed");
214 GST_DEBUG_CATEGORY_INIT (splitmux_debug, "splitmuxsink", 0,
215 "Split File Muxing Sink");
216 }
217
218 #define gst_splitmux_sink_parent_class parent_class
219 G_DEFINE_TYPE_EXTENDED (GstSplitMuxSink, gst_splitmux_sink, GST_TYPE_BIN, 0,
220 _do_init ());
221 GST_ELEMENT_REGISTER_DEFINE (splitmuxsink, "splitmuxsink", GST_RANK_NONE,
222 GST_TYPE_SPLITMUX_SINK);
223
224 static gboolean create_muxer (GstSplitMuxSink * splitmux);
225 static gboolean create_sink (GstSplitMuxSink * splitmux);
226 static void gst_splitmux_sink_set_property (GObject * object, guint prop_id,
227 const GValue * value, GParamSpec * pspec);
228 static void gst_splitmux_sink_get_property (GObject * object, guint prop_id,
229 GValue * value, GParamSpec * pspec);
230 static void gst_splitmux_sink_dispose (GObject * object);
231 static void gst_splitmux_sink_finalize (GObject * object);
232
233 static GstPad *gst_splitmux_sink_request_new_pad (GstElement * element,
234 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
235 static void gst_splitmux_sink_release_pad (GstElement * element, GstPad * pad);
236
237 static GstStateChangeReturn gst_splitmux_sink_change_state (GstElement *
238 element, GstStateChange transition);
239
240 static void bus_handler (GstBin * bin, GstMessage * msg);
241 static gboolean set_next_filename (GstSplitMuxSink * splitmux,
242 MqStreamCtx * ctx);
243 static GstFlowReturn start_next_fragment (GstSplitMuxSink * splitmux,
244 MqStreamCtx * ctx);
245 static void mq_stream_ctx_free (MqStreamCtx * ctx);
246 static void grow_blocked_queues (GstSplitMuxSink * splitmux);
247
248 static void gst_splitmux_sink_ensure_max_files (GstSplitMuxSink * splitmux);
249 static GstElement *create_element (GstSplitMuxSink * splitmux,
250 const gchar * factory, const gchar * name, gboolean locked);
251
252 static void do_async_done (GstSplitMuxSink * splitmux);
253
254 static GstClockTime calculate_next_max_timecode (GstSplitMuxSink * splitmux,
255 const GstVideoTimeCode * cur_tc, GstClockTime running_time,
256 GstVideoTimeCode ** next_tc);
257
258 static MqStreamBuf *
259 mq_stream_buf_new (void)
260 {
261 return g_new0 (MqStreamBuf, 1);
262 }
263
264 static void
265 mq_stream_buf_free (MqStreamBuf * data)
266 {
267 g_free (data);
268 }
269
270 static SplitMuxOutputCommand *
271 out_cmd_buf_new_finish_fragment (void)
272 {
273 SplitMuxOutputCommand *res = g_new0 (SplitMuxOutputCommand, 1);
274
275 res->cmd_type = SPLITMUX_OUTPUT_COMMAND_FINISH_FRAGMENT;
276 return res;
277 }
278
279 static SplitMuxOutputCommand *
280 out_cmd_buf_new_release_gop (GstClockTimeDiff max_output_ts)
281 {
282 SplitMuxOutputCommand *res = g_new0 (SplitMuxOutputCommand, 1);
283
284 res->cmd_type = SPLITMUX_OUTPUT_COMMAND_RELEASE_GOP;
285 res->release_gop.max_output_ts = max_output_ts;
286
287 return res;
288 }
289
290 static void
291 out_cmd_buf_free (SplitMuxOutputCommand * data)
292 {
293 g_free (data);
294 }
295
296 static void
297 input_gop_free (InputGop * gop)
298 {
299 g_clear_pointer (&gop->start_tc, gst_video_time_code_free);
300 g_free (gop);
301 }
302
303 static void
304 gst_splitmux_sink_class_init (GstSplitMuxSinkClass * klass)
305 {
306 GObjectClass *gobject_class = (GObjectClass *) klass;
307 GstElementClass *gstelement_class = (GstElementClass *) klass;
308 GstBinClass *gstbin_class = (GstBinClass *) klass;
309
310 gobject_class->set_property = gst_splitmux_sink_set_property;
311 gobject_class->get_property = gst_splitmux_sink_get_property;
312 gobject_class->dispose = gst_splitmux_sink_dispose;
313 gobject_class->finalize = gst_splitmux_sink_finalize;
314
315 gst_element_class_set_static_metadata (gstelement_class,
316 "Split Muxing Bin", "Generic/Bin/Muxer",
317 "Convenience bin that muxes incoming streams into multiple time/size limited files",
318 "Jan Schmidt <[email protected]>");
319
320 gst_element_class_add_static_pad_template (gstelement_class,
321 &video_sink_template);
322 gst_element_class_add_static_pad_template (gstelement_class,
323 &video_aux_sink_template);
324 gst_element_class_add_static_pad_template (gstelement_class,
325 &audio_sink_template);
326 gst_element_class_add_static_pad_template (gstelement_class,
327 &subtitle_sink_template);
328 gst_element_class_add_static_pad_template (gstelement_class,
329 &caption_sink_template);
330
331 gstelement_class->change_state =
332 GST_DEBUG_FUNCPTR (gst_splitmux_sink_change_state);
333 gstelement_class->request_new_pad =
334 GST_DEBUG_FUNCPTR (gst_splitmux_sink_request_new_pad);
335 gstelement_class->release_pad =
336 GST_DEBUG_FUNCPTR (gst_splitmux_sink_release_pad);
337
338 gstbin_class->handle_message = bus_handler;
339
340 g_object_class_install_property (gobject_class, PROP_LOCATION,
341 g_param_spec_string ("location", "File Output Pattern",
342 "Format string pattern for the location of the files to write (e.g. video%05d.mp4)",
343 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344 g_object_class_install_property (gobject_class, PROP_MUXER_OVERHEAD,
345 g_param_spec_double ("mux-overhead", "Muxing Overhead",
346 "Extra size overhead of muxing (0.02 = 2%)", 0.0, 1.0,
347 DEFAULT_MUXER_OVERHEAD,
348 G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
349
350 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
351 g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
352 "Max. amount of time per file (in ns, 0=disable)", 0, G_MAXUINT64,
353 DEFAULT_MAX_SIZE_TIME,
354 G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
355 G_PARAM_STATIC_STRINGS));
356 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
357 g_param_spec_uint64 ("max-size-bytes", "Max. size bytes",
358 "Max. amount of data per file (in bytes, 0=disable)", 0, G_MAXUINT64,
359 DEFAULT_MAX_SIZE_BYTES,
360 G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
361 G_PARAM_STATIC_STRINGS));
362 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIMECODE,
363 g_param_spec_string ("max-size-timecode", "Maximum timecode difference",
364 "Maximum difference in timecode between first and last frame. "
365 "Separator is assumed to be \":\" everywhere (e.g. 01:00:00:00). "
366 "Will only be effective if a timecode track is present.", NULL,
367 G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
368 G_PARAM_STATIC_STRINGS));
369 g_object_class_install_property (gobject_class, PROP_SEND_KEYFRAME_REQUESTS,
370 g_param_spec_boolean ("send-keyframe-requests",
371 "Request keyframes at max-size-time",
372 "Request a keyframe every max-size-time ns to try splitting at that point. "
373 "Needs max-size-bytes to be 0 in order to be effective.",
374 DEFAULT_SEND_KEYFRAME_REQUESTS,
375 G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
376 G_PARAM_STATIC_STRINGS));
377 g_object_class_install_property (gobject_class, PROP_MAX_FILES,
378 g_param_spec_uint ("max-files", "Max files",
379 "Maximum number of files to keep on disk. Once the maximum is reached,"
380 "old files start to be deleted to make room for new ones.", 0,
381 G_MAXUINT, DEFAULT_MAX_FILES,
382 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
383 g_object_class_install_property (gobject_class, PROP_ALIGNMENT_THRESHOLD,
384 g_param_spec_uint64 ("alignment-threshold", "Alignment threshold (ns)",
385 "Allow non-reference streams to be that many ns before the reference"
386 " stream", 0, G_MAXUINT64, DEFAULT_ALIGNMENT_THRESHOLD,
387 G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY |
388 G_PARAM_STATIC_STRINGS));
389
390 g_object_class_install_property (gobject_class, PROP_MUXER,
391 g_param_spec_object ("muxer", "Muxer",
392 "The muxer element to use (NULL = default mp4mux). "
393 "Valid only for async-finalize = FALSE",
394 GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
395 g_object_class_install_property (gobject_class, PROP_SINK,
396 g_param_spec_object ("sink", "Sink",
397 "The sink element (or element chain) to use (NULL = default filesink). "
398 "Valid only for async-finalize = FALSE",
399 GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400
401 g_object_class_install_property (gobject_class, PROP_USE_ROBUST_MUXING,
402 g_param_spec_boolean ("use-robust-muxing",
403 "Support robust-muxing mode of some muxers",
404 "Check if muxers support robust muxing via the reserved-max-duration and "
405 "reserved-duration-remaining properties and use them if so. "
406 "(Only present on qtmux and mp4mux for now). splitmuxsink may then also "
407 " create new fragments if the reserved header space is about to overflow. "
408 "Note that for mp4mux and qtmux, reserved-moov-update-period must be set "
409 "manually by the app to a non-zero value for robust muxing to have an effect.",
410 DEFAULT_USE_ROBUST_MUXING,
411 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
412
413 g_object_class_install_property (gobject_class, PROP_RESET_MUXER,
414 g_param_spec_boolean ("reset-muxer",
415 "Reset Muxer",
416 "Reset the muxer after each segment. Disabling this will not work for most muxers.",
417 DEFAULT_RESET_MUXER, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
418
419 g_object_class_install_property (gobject_class, PROP_ASYNC_FINALIZE,
420 g_param_spec_boolean ("async-finalize",
421 "Finalize fragments asynchronously",
422 "Finalize each fragment asynchronously and start a new one",
423 DEFAULT_ASYNC_FINALIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
424 g_object_class_install_property (gobject_class, PROP_MUXER_FACTORY,
425 g_param_spec_string ("muxer-factory", "Muxer factory",
426 "The muxer element factory to use (default = mp4mux). "
427 "Valid only for async-finalize = TRUE",
428 "mp4mux", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
429 /**
430 * GstSplitMuxSink:muxer-preset
431 *
432 * An optional #GstPreset name to use for the muxer. This only has an effect
433 * in `async-finalize=TRUE` mode.
434 *
435 * Since: 1.18
436 */
437 g_object_class_install_property (gobject_class, PROP_MUXER_PRESET,
438 g_param_spec_string ("muxer-preset", "Muxer preset",
439 "The muxer preset to use. "
440 "Valid only for async-finalize = TRUE",
441 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
442 g_object_class_install_property (gobject_class, PROP_MUXER_PROPERTIES,
443 g_param_spec_boxed ("muxer-properties", "Muxer properties",
444 "The muxer element properties to use. "
445 "Example: {properties,boolean-prop=true,string-prop=\"hi\"}. "
446 "Valid only for async-finalize = TRUE",
447 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
448 g_object_class_install_property (gobject_class, PROP_SINK_FACTORY,
449 g_param_spec_string ("sink-factory", "Sink factory",
450 "The sink element factory to use (default = filesink). "
451 "Valid only for async-finalize = TRUE",
452 "filesink", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
453 /**
454 * GstSplitMuxSink:sink-preset
455 *
456 * An optional #GstPreset name to use for the sink. This only has an effect
457 * in `async-finalize=TRUE` mode.
458 *
459 * Since: 1.18
460 */
461 g_object_class_install_property (gobject_class, PROP_SINK_PRESET,
462 g_param_spec_string ("sink-preset", "Sink preset",
463 "The sink preset to use. "
464 "Valid only for async-finalize = TRUE",
465 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
466 g_object_class_install_property (gobject_class, PROP_SINK_PROPERTIES,
467 g_param_spec_boxed ("sink-properties", "Sink properties",
468 "The sink element properties to use. "
469 "Example: {properties,boolean-prop=true,string-prop=\"hi\"}. "
470 "Valid only for async-finalize = TRUE",
471 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
472 g_object_class_install_property (gobject_class, PROP_START_INDEX,
473 g_param_spec_int ("start-index", "Start Index",
474 "Start value of fragment index.",
475 0, G_MAXINT, DEFAULT_START_INDEX,
476 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
477
478 /**
479 * GstSplitMuxSink::muxer-pad-map
480 *
481 * An optional GstStructure that provides a map from splitmuxsink sinkpad
482 * names to muxer pad names they should feed. Splitmuxsink has some default
483 * mapping behaviour to link video to video pads and audio to audio pads
484 * that usually works fine. This property is useful if you need to ensure
485 * a particular mapping to muxed streams.
486 *
487 * The GstStructure contains string fields like so:
488 * splitmuxsink muxer-pad-map=x-pad-map,video=video_1
489 *
490 * Since: 1.18
491 */
492 g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MUXERPAD_MAP,
493 g_param_spec_boxed ("muxer-pad-map", "Muxer pad map",
494 "A GstStructure specifies the mapping from splitmuxsink sink pads to muxer pads",
495 GST_TYPE_STRUCTURE,
496 (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
497
498 /**
499 * GstSplitMuxSink::format-location:
500 * @splitmux: the #GstSplitMuxSink
501 * @fragment_id: the sequence number of the file to be created
502 *
503 * Returns: the location to be used for the next output file. This must be
504 * a newly-allocated string which will be freed with g_free() by the
505 * splitmuxsink element when it no longer needs it, so use g_strdup() or
506 * g_strdup_printf() or similar functions to allocate it.
507 */
508 signals[SIGNAL_FORMAT_LOCATION] =
509 g_signal_new ("format-location", G_TYPE_FROM_CLASS (klass),
510 G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_STRING, 1, G_TYPE_UINT);
511
512 /**
513 * GstSplitMuxSink::format-location-full:
514 * @splitmux: the #GstSplitMuxSink
515 * @fragment_id: the sequence number of the file to be created
516 * @first_sample: A #GstSample containing the first buffer
517 * from the reference stream in the new file
518 *
519 * Returns: the location to be used for the next output file. This must be
520 * a newly-allocated string which will be freed with g_free() by the
521 * splitmuxsink element when it no longer needs it, so use g_strdup() or
522 * g_strdup_printf() or similar functions to allocate it.
523 *
524 * Since: 1.12
525 */
526 signals[SIGNAL_FORMAT_LOCATION_FULL] =
527 g_signal_new ("format-location-full", G_TYPE_FROM_CLASS (klass),
528 G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_STRING, 2, G_TYPE_UINT,
529 GST_TYPE_SAMPLE);
530
531 /**
532 * GstSplitMuxSink::split-now:
533 * @splitmux: the #GstSplitMuxSink
534 *
535 * When called by the user, this action signal splits the video file (and begins a new one) immediately.
536 * The current GOP will be output to the new file.
537 *
538 * Since: 1.14
539 */
540 signals[SIGNAL_SPLIT_NOW] =
541 g_signal_new ("split-now", G_TYPE_FROM_CLASS (klass),
542 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
543 G_STRUCT_OFFSET (GstSplitMuxSinkClass, split_now), NULL, NULL, NULL,
544 G_TYPE_NONE, 0);
545
546 /**
547 * GstSplitMuxSink::split-after:
548 * @splitmux: the #GstSplitMuxSink
549 *
550 * When called by the user, this action signal splits the video file (and begins a new one) immediately.
551 * Unlike the 'split-now' signal, with 'split-after', the current GOP will be output to the old file.
552 *
553 * Since: 1.16
554 */
555 signals[SIGNAL_SPLIT_AFTER] =
556 g_signal_new ("split-after", G_TYPE_FROM_CLASS (klass),
557 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
558 G_STRUCT_OFFSET (GstSplitMuxSinkClass, split_after), NULL, NULL, NULL,
559 G_TYPE_NONE, 0);
560
561 /**
562 * GstSplitMuxSink::split-at-running-time:
563 * @splitmux: the #GstSplitMuxSink
564 *
565 * When called by the user, this action signal splits the video file (and
566 * begins a new one) as soon as the given running time is reached. If this
567 * action signal is called multiple times, running times are queued up and
568 * processed in the order they were given.
569 *
570 * Note that this is prone to race conditions, where said running time is
571 * reached and surpassed before we had a chance to split. The file will
572 * still split immediately, but in order to make sure that the split doesn't
573 * happen too late, it is recommended to call this action signal from
574 * something that will prevent further buffers from flowing into
575 * splitmuxsink before the split is completed, such as a pad probe before
576 * splitmuxsink.
577 *
578 *
579 * Since: 1.16
580 */
581 signals[SIGNAL_SPLIT_AT_RUNNING_TIME] =
582 g_signal_new ("split-at-running-time", G_TYPE_FROM_CLASS (klass),
583 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
584 G_STRUCT_OFFSET (GstSplitMuxSinkClass, split_at_running_time), NULL, NULL,
585 NULL, G_TYPE_NONE, 1, G_TYPE_UINT64);
586
587 /**
588 * GstSplitMuxSink::muxer-added:
589 * @splitmux: the #GstSplitMuxSink
590 * @muxer: the newly added muxer element
591 *
592 * Since: 1.16
593 */
594 signals[SIGNAL_MUXER_ADDED] =
595 g_signal_new ("muxer-added", G_TYPE_FROM_CLASS (klass),
596 G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
597
598 /**
599 * GstSplitMuxSink::sink-added:
600 * @splitmux: the #GstSplitMuxSink
601 * @sink: the newly added sink element
602 *
603 * Since: 1.16
604 */
605 signals[SIGNAL_SINK_ADDED] =
606 g_signal_new ("sink-added", G_TYPE_FROM_CLASS (klass),
607 G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
608
609 klass->split_now = split_now;
610 klass->split_after = split_after;
611 klass->split_at_running_time = split_at_running_time;
612 }
613
614 static void
615 gst_splitmux_sink_init (GstSplitMuxSink * splitmux)
616 {
617 g_mutex_init (&splitmux->lock);
618 g_mutex_init (&splitmux->state_lock);
619 g_cond_init (&splitmux->input_cond);
620 g_cond_init (&splitmux->output_cond);
621 g_queue_init (&splitmux->out_cmd_q);
622
623 splitmux->mux_overhead = DEFAULT_MUXER_OVERHEAD;
624 splitmux->threshold_time = DEFAULT_MAX_SIZE_TIME;
625 splitmux->threshold_bytes = DEFAULT_MAX_SIZE_BYTES;
626 splitmux->max_files = DEFAULT_MAX_FILES;
627 splitmux->send_keyframe_requests = DEFAULT_SEND_KEYFRAME_REQUESTS;
628 splitmux->alignment_threshold = DEFAULT_ALIGNMENT_THRESHOLD;
629 splitmux->use_robust_muxing = DEFAULT_USE_ROBUST_MUXING;
630 splitmux->reset_muxer = DEFAULT_RESET_MUXER;
631
632 splitmux->threshold_timecode_str = NULL;
633
634 splitmux->async_finalize = DEFAULT_ASYNC_FINALIZE;
635 splitmux->muxer_factory = g_strdup (DEFAULT_MUXER);
636 splitmux->muxer_properties = NULL;
637 splitmux->sink_factory = g_strdup (DEFAULT_SINK);
638 splitmux->sink_properties = NULL;
639
640 GST_OBJECT_FLAG_SET (splitmux, GST_ELEMENT_FLAG_SINK);
641 splitmux->split_requested = FALSE;
642 splitmux->do_split_next_gop = FALSE;
643 splitmux->times_to_split = gst_vec_deque_new_for_struct (8, 8);
644 splitmux->next_fku_time = GST_CLOCK_TIME_NONE;
645
646 g_queue_init (&splitmux->pending_input_gops);
647 }
648
649 static void
650 gst_splitmux_reset_elements (GstSplitMuxSink * splitmux)
651 {
652 if (splitmux->muxer) {
653 gst_element_set_locked_state (splitmux->muxer, TRUE);
654 gst_element_set_state (splitmux->muxer, GST_STATE_NULL);
655 gst_bin_remove (GST_BIN (splitmux), splitmux->muxer);
656 }
657 if (splitmux->active_sink) {
658 gst_element_set_locked_state (splitmux->active_sink, TRUE);
659 gst_element_set_state (splitmux->active_sink, GST_STATE_NULL);
660 gst_bin_remove (GST_BIN (splitmux), splitmux->active_sink);
661 }
662
663 splitmux->sink = splitmux->active_sink = splitmux->muxer = NULL;
664 }
665
666 static void
667 gst_splitmux_sink_dispose (GObject * object)
668 {
669 GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
670
671 /* Calling parent dispose invalidates all child pointers */
672 splitmux->sink = splitmux->active_sink = splitmux->muxer = NULL;
673
674 G_OBJECT_CLASS (parent_class)->dispose (object);
675 }
676
677 static void
678 gst_splitmux_sink_finalize (GObject * object)
679 {
680 GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
681
682 g_cond_clear (&splitmux->input_cond);
683 g_cond_clear (&splitmux->output_cond);
684 g_mutex_clear (&splitmux->lock);
685 g_mutex_clear (&splitmux->state_lock);
686 g_queue_foreach (&splitmux->out_cmd_q, (GFunc) out_cmd_buf_free, NULL);
687 g_queue_clear (&splitmux->out_cmd_q);
688 g_queue_foreach (&splitmux->pending_input_gops, (GFunc) input_gop_free, NULL);
689 g_queue_clear (&splitmux->pending_input_gops);
690
691 g_clear_pointer (&splitmux->fragment_start_tc, gst_video_time_code_free);
692
693 if (splitmux->muxerpad_map)
694 gst_structure_free (splitmux->muxerpad_map);
695
696 if (splitmux->provided_sink)
697 gst_object_unref (splitmux->provided_sink);
698 if (splitmux->provided_muxer)
699 gst_object_unref (splitmux->provided_muxer);
700
701 if (splitmux->muxer_factory)
702 g_free (splitmux->muxer_factory);
703 if (splitmux->muxer_preset)
704 g_free (splitmux->muxer_preset);
705 if (splitmux->muxer_properties)
706 gst_structure_free (splitmux->muxer_properties);
707 if (splitmux->sink_factory)
708 g_free (splitmux->sink_factory);
709 if (splitmux->sink_preset)
710 g_free (splitmux->sink_preset);
711 if (splitmux->sink_properties)
712 gst_structure_free (splitmux->sink_properties);
713
714 if (splitmux->threshold_timecode_str)
715 g_free (splitmux->threshold_timecode_str);
716 if (splitmux->tc_interval)
717 gst_video_time_code_interval_free (splitmux->tc_interval);
718
719 if (splitmux->times_to_split)
720 gst_vec_deque_free (splitmux->times_to_split);
721
722 g_free (splitmux->location);
723
724 /* Make sure to free any un-released contexts. There should not be any,
725 * because the dispose will have freed all request pads though */
726 g_list_foreach (splitmux->contexts, (GFunc) mq_stream_ctx_free, NULL);
727 g_list_free (splitmux->contexts);
728
729 G_OBJECT_CLASS (parent_class)->finalize (object);
730 }
731
732 /*
733 * Set any time threshold to the muxer, if it has
734 * reserved-max-duration and reserved-duration-remaining
735 * properties. Called when creating/claiming the muxer
736 * in create_elements() */
737 static void
738 update_muxer_properties (GstSplitMuxSink * sink)
739 {
740 GObjectClass *klass;
741 GstClockTime threshold_time;
742
743 sink->muxer_has_reserved_props = FALSE;
744 if (sink->muxer == NULL)
745 return;
746 klass = G_OBJECT_GET_CLASS (sink->muxer);
747 if (g_object_class_find_property (klass, "reserved-max-duration") == NULL)
748 return;
749 if (g_object_class_find_property (klass,
750 "reserved-duration-remaining") == NULL)
751 return;
752 sink->muxer_has_reserved_props = TRUE;
753
754 GST_LOG_OBJECT (sink, "Setting muxer reserved time to %" GST_TIME_FORMAT,
755 GST_TIME_ARGS (sink->threshold_time));
756 GST_OBJECT_LOCK (sink);
757 threshold_time = sink->threshold_time;
758 GST_OBJECT_UNLOCK (sink);
759
760 if (threshold_time > 0) {
761 /* Tell the muxer how much space to reserve */
762 GstClockTime muxer_threshold = threshold_time;
763 g_object_set (sink->muxer, "reserved-max-duration", muxer_threshold, NULL);
764 }
765 }
766
767 static void
768 gst_splitmux_sink_set_property (GObject * object, guint prop_id,
769 const GValue * value, GParamSpec * pspec)
770 {
771 GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
772
773 switch (prop_id) {
774 case PROP_LOCATION:{
775 GST_OBJECT_LOCK (splitmux);
776 g_free (splitmux->location);
777 splitmux->location = g_value_dup_string (value);
778 GST_OBJECT_UNLOCK (splitmux);
779 break;
780 }
781 case PROP_START_INDEX:
782 GST_OBJECT_LOCK (splitmux);
783 splitmux->start_index = g_value_get_int (value);
784 GST_OBJECT_UNLOCK (splitmux);
785 break;
786 case PROP_MAX_SIZE_BYTES:
787 GST_OBJECT_LOCK (splitmux);
788 splitmux->threshold_bytes = g_value_get_uint64 (value);
789 GST_OBJECT_UNLOCK (splitmux);
790 break;
791 case PROP_MAX_SIZE_TIME:
792 GST_OBJECT_LOCK (splitmux);
793 splitmux->threshold_time = g_value_get_uint64 (value);
794 GST_OBJECT_UNLOCK (splitmux);
795 break;
796 case PROP_MAX_SIZE_TIMECODE:
797 GST_OBJECT_LOCK (splitmux);
798 g_free (splitmux->threshold_timecode_str);
799 /* will be calculated later */
800 g_clear_pointer (&splitmux->tc_interval,
801 gst_video_time_code_interval_free);
802
803 splitmux->threshold_timecode_str = g_value_dup_string (value);
804 if (splitmux->threshold_timecode_str) {
805 splitmux->tc_interval =
806 gst_video_time_code_interval_new_from_string
807 (splitmux->threshold_timecode_str);
808 if (!splitmux->tc_interval) {
809 g_warning ("Wrong timecode string %s",
810 splitmux->threshold_timecode_str);
811 g_free (splitmux->threshold_timecode_str);
812 splitmux->threshold_timecode_str = NULL;
813 }
814 }
815 splitmux->next_fragment_start_tc_time =
816 calculate_next_max_timecode (splitmux, splitmux->fragment_start_tc,
817 splitmux->fragment_start_time, NULL);
818 if (splitmux->tc_interval && splitmux->fragment_start_tc
819 && !GST_CLOCK_TIME_IS_VALID (splitmux->next_fragment_start_tc_time)) {
820 GST_WARNING_OBJECT (splitmux,
821 "Couldn't calculate next fragment start time for timecode mode");
822 }
823 GST_OBJECT_UNLOCK (splitmux);
824 break;
825 case PROP_SEND_KEYFRAME_REQUESTS:
826 GST_OBJECT_LOCK (splitmux);
827 splitmux->send_keyframe_requests = g_value_get_boolean (value);
828 GST_OBJECT_UNLOCK (splitmux);
829 break;
830 case PROP_MAX_FILES:
831 GST_OBJECT_LOCK (splitmux);
832 splitmux->max_files = g_value_get_uint (value);
833 GST_OBJECT_UNLOCK (splitmux);
834 break;
835 case PROP_MUXER_OVERHEAD:
836 GST_OBJECT_LOCK (splitmux);
837 splitmux->mux_overhead = g_value_get_double (value);
838 GST_OBJECT_UNLOCK (splitmux);
839 break;
840 case PROP_USE_ROBUST_MUXING:
841 GST_OBJECT_LOCK (splitmux);
842 splitmux->use_robust_muxing = g_value_get_boolean (value);
843 GST_OBJECT_UNLOCK (splitmux);
844 if (splitmux->use_robust_muxing)
845 update_muxer_properties (splitmux);
846 break;
847 case PROP_ALIGNMENT_THRESHOLD:
848 GST_OBJECT_LOCK (splitmux);
849 splitmux->alignment_threshold = g_value_get_uint64 (value);
850 GST_OBJECT_UNLOCK (splitmux);
851 break;
852 case PROP_SINK:
853 GST_OBJECT_LOCK (splitmux);
854 gst_clear_object (&splitmux->provided_sink);
855 splitmux->provided_sink = g_value_get_object (value);
856 if (splitmux->provided_sink)
857 gst_object_ref_sink (splitmux->provided_sink);
858 GST_OBJECT_UNLOCK (splitmux);
859 break;
860 case PROP_MUXER:
861 GST_OBJECT_LOCK (splitmux);
862 gst_clear_object (&splitmux->provided_muxer);
863 splitmux->provided_muxer = g_value_get_object (value);
864 if (splitmux->provided_muxer)
865 gst_object_ref_sink (splitmux->provided_muxer);
866 GST_OBJECT_UNLOCK (splitmux);
867 break;
868 case PROP_RESET_MUXER:
869 GST_OBJECT_LOCK (splitmux);
870 splitmux->reset_muxer = g_value_get_boolean (value);
871 GST_OBJECT_UNLOCK (splitmux);
872 break;
873 case PROP_ASYNC_FINALIZE:
874 GST_OBJECT_LOCK (splitmux);
875 splitmux->async_finalize = g_value_get_boolean (value);
876 GST_OBJECT_UNLOCK (splitmux);
877 break;
878 case PROP_MUXER_FACTORY:
879 GST_OBJECT_LOCK (splitmux);
880 if (splitmux->muxer_factory)
881 g_free (splitmux->muxer_factory);
882 splitmux->muxer_factory = g_value_dup_string (value);
883 GST_OBJECT_UNLOCK (splitmux);
884 break;
885 case PROP_MUXER_PRESET:
886 GST_OBJECT_LOCK (splitmux);
887 if (splitmux->muxer_preset)
888 g_free (splitmux->muxer_preset);
889 splitmux->muxer_preset = g_value_dup_string (value);
890 GST_OBJECT_UNLOCK (splitmux);
891 break;
892 case PROP_MUXER_PROPERTIES:
893 GST_OBJECT_LOCK (splitmux);
894 if (splitmux->muxer_properties)
895 gst_structure_free (splitmux->muxer_properties);
896 if (gst_value_get_structure (value))
897 splitmux->muxer_properties =
898 gst_structure_copy (gst_value_get_structure (value));
899 else
900 splitmux->muxer_properties = NULL;
901 GST_OBJECT_UNLOCK (splitmux);
902 break;
903 case PROP_SINK_FACTORY:
904 GST_OBJECT_LOCK (splitmux);
905 if (splitmux->sink_factory)
906 g_free (splitmux->sink_factory);
907 splitmux->sink_factory = g_value_dup_string (value);
908 GST_OBJECT_UNLOCK (splitmux);
909 break;
910 case PROP_SINK_PRESET:
911 GST_OBJECT_LOCK (splitmux);
912 if (splitmux->sink_preset)
913 g_free (splitmux->sink_preset);
914 splitmux->sink_preset = g_value_dup_string (value);
915 GST_OBJECT_UNLOCK (splitmux);
916 break;
917 case PROP_SINK_PROPERTIES:
918 GST_OBJECT_LOCK (splitmux);
919 if (splitmux->sink_properties)
920 gst_structure_free (splitmux->sink_properties);
921 if (gst_value_get_structure (value))
922 splitmux->sink_properties =
923 gst_structure_copy (gst_value_get_structure (value));
924 else
925 splitmux->sink_properties = NULL;
926 GST_OBJECT_UNLOCK (splitmux);
927 break;
928 case PROP_MUXERPAD_MAP:
929 {
930 const GstStructure *s = gst_value_get_structure (value);
931 GST_SPLITMUX_LOCK (splitmux);
932 if (splitmux->muxerpad_map) {
933 gst_structure_free (splitmux->muxerpad_map);
934 }
935 if (s)
936 splitmux->muxerpad_map = gst_structure_copy (s);
937 else
938 splitmux->muxerpad_map = NULL;
939 GST_SPLITMUX_UNLOCK (splitmux);
940 break;
941 }
942 default:
943 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
944 break;
945 }
946 }
947
948 static void
949 gst_splitmux_sink_get_property (GObject * object, guint prop_id,
950 GValue * value, GParamSpec * pspec)
951 {
952 GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
953
954 switch (prop_id) {
955 case PROP_LOCATION:
956 GST_OBJECT_LOCK (splitmux);
957 g_value_set_string (value, splitmux->location);
958 GST_OBJECT_UNLOCK (splitmux);
959 break;
960 case PROP_START_INDEX:
961 GST_OBJECT_LOCK (splitmux);
962 g_value_set_int (value, splitmux->start_index);
963 GST_OBJECT_UNLOCK (splitmux);
964 break;
965 case PROP_MAX_SIZE_BYTES:
966 GST_OBJECT_LOCK (splitmux);
967 g_value_set_uint64 (value, splitmux->threshold_bytes);
968 GST_OBJECT_UNLOCK (splitmux);
969 break;
970 case PROP_MAX_SIZE_TIME:
971 GST_OBJECT_LOCK (splitmux);
972 g_value_set_uint64 (value, splitmux->threshold_time);
973 GST_OBJECT_UNLOCK (splitmux);
974 break;
975 case PROP_MAX_SIZE_TIMECODE:
976 GST_OBJECT_LOCK (splitmux);
977 g_value_set_string (value, splitmux->threshold_timecode_str);
978 GST_OBJECT_UNLOCK (splitmux);
979 break;
980 case PROP_SEND_KEYFRAME_REQUESTS:
981 GST_OBJECT_LOCK (splitmux);
982 g_value_set_boolean (value, splitmux->send_keyframe_requests);
983 GST_OBJECT_UNLOCK (splitmux);
984 break;
985 case PROP_MAX_FILES:
986 GST_OBJECT_LOCK (splitmux);
987 g_value_set_uint (value, splitmux->max_files);
988 GST_OBJECT_UNLOCK (splitmux);
989 break;
990 case PROP_MUXER_OVERHEAD:
991 GST_OBJECT_LOCK (splitmux);
992 g_value_set_double (value, splitmux->mux_overhead);
993 GST_OBJECT_UNLOCK (splitmux);
994 break;
995 case PROP_USE_ROBUST_MUXING:
996 GST_OBJECT_LOCK (splitmux);
997 g_value_set_boolean (value, splitmux->use_robust_muxing);
998 GST_OBJECT_UNLOCK (splitmux);
999 break;
1000 case PROP_ALIGNMENT_THRESHOLD:
1001 GST_OBJECT_LOCK (splitmux);
1002 g_value_set_uint64 (value, splitmux->alignment_threshold);
1003 GST_OBJECT_UNLOCK (splitmux);
1004 break;
1005 case PROP_SINK:
1006 GST_OBJECT_LOCK (splitmux);
1007 g_value_set_object (value, splitmux->provided_sink);
1008 GST_OBJECT_UNLOCK (splitmux);
1009 break;
1010 case PROP_MUXER:
1011 GST_OBJECT_LOCK (splitmux);
1012 g_value_set_object (value, splitmux->provided_muxer);
1013 GST_OBJECT_UNLOCK (splitmux);
1014 break;
1015 case PROP_RESET_MUXER:
1016 GST_OBJECT_LOCK (splitmux);
1017 g_value_set_boolean (value, splitmux->reset_muxer);
1018 GST_OBJECT_UNLOCK (splitmux);
1019 break;
1020 case PROP_ASYNC_FINALIZE:
1021 GST_OBJECT_LOCK (splitmux);
1022 g_value_set_boolean (value, splitmux->async_finalize);
1023 GST_OBJECT_UNLOCK (splitmux);
1024 break;
1025 case PROP_MUXER_FACTORY:
1026 GST_OBJECT_LOCK (splitmux);
1027 g_value_set_string (value, splitmux->muxer_factory);
1028 GST_OBJECT_UNLOCK (splitmux);
1029 break;
1030 case PROP_MUXER_PRESET:
1031 GST_OBJECT_LOCK (splitmux);
1032 g_value_set_string (value, splitmux->muxer_preset);
1033 GST_OBJECT_UNLOCK (splitmux);
1034 break;
1035 case PROP_MUXER_PROPERTIES:
1036 GST_OBJECT_LOCK (splitmux);
1037 gst_value_set_structure (value, splitmux->muxer_properties);
1038 GST_OBJECT_UNLOCK (splitmux);
1039 break;
1040 case PROP_SINK_FACTORY:
1041 GST_OBJECT_LOCK (splitmux);
1042 g_value_set_string (value, splitmux->sink_factory);
1043 GST_OBJECT_UNLOCK (splitmux);
1044 break;
1045 case PROP_SINK_PRESET:
1046 GST_OBJECT_LOCK (splitmux);
1047 g_value_set_string (value, splitmux->sink_preset);
1048 GST_OBJECT_UNLOCK (splitmux);
1049 break;
1050 case PROP_SINK_PROPERTIES:
1051 GST_OBJECT_LOCK (splitmux);
1052 gst_value_set_structure (value, splitmux->sink_properties);
1053 GST_OBJECT_UNLOCK (splitmux);
1054 break;
1055 case PROP_MUXERPAD_MAP:
1056 GST_SPLITMUX_LOCK (splitmux);
1057 gst_value_set_structure (value, splitmux->muxerpad_map);
1058 GST_SPLITMUX_UNLOCK (splitmux);
1059 break;
1060 default:
1061 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1062 break;
1063 }
1064 }
1065
1066 /* Convenience function */
1067 static inline GstClockTimeDiff
1068 my_segment_to_running_time (GstSegment * segment, GstClockTime val)
1069 {
1070 GstClockTimeDiff res = GST_CLOCK_STIME_NONE;
1071
1072 if (GST_CLOCK_TIME_IS_VALID (val)) {
1073 gboolean sign =
1074 gst_segment_to_running_time_full (segment, GST_FORMAT_TIME, val, &val);
1075 if (sign > 0)
1076 res = val;
1077 else if (sign < 0)
1078 res = -val;
1079 }
1080 return res;
1081 }
1082
1083 static void
1084 mq_stream_ctx_reset (MqStreamCtx * ctx)
1085 {
1086 gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
1087 gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
1088 ctx->out_fragment_start_runts = ctx->in_running_time = ctx->out_running_time =
1089 GST_CLOCK_STIME_NONE;
1090 g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
1091 g_queue_clear (&ctx->queued_bufs);
1092 }
1093
1094 static MqStreamCtx *
1095 mq_stream_ctx_new (GstSplitMuxSink * splitmux)
1096 {
1097 MqStreamCtx *ctx;
1098
1099 ctx = g_new0 (MqStreamCtx, 1);
1100 ctx->splitmux = splitmux;
1101 g_queue_init (&ctx->queued_bufs);
1102 mq_stream_ctx_reset (ctx);
1103
1104 return ctx;
1105 }
1106
1107 static void
1108 mq_stream_ctx_free (MqStreamCtx * ctx)
1109 {
1110 if (ctx->q) {
1111 GstObject *parent = gst_object_get_parent (GST_OBJECT (ctx->q));
1112
1113 g_signal_handler_disconnect (ctx->q, ctx->q_overrun_id);
1114
1115 if (parent == GST_OBJECT_CAST (ctx->splitmux)) {
1116 gst_element_set_locked_state (ctx->q, TRUE);
1117 gst_element_set_state (ctx->q, GST_STATE_NULL);
1118 gst_bin_remove (GST_BIN (ctx->splitmux), ctx->q);
1119 gst_object_unref (parent);
1120 }
1121 gst_object_unref (ctx->q);
1122 }
1123 gst_object_unref (ctx->sinkpad);
1124 gst_object_unref (ctx->srcpad);
1125 g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
1126 g_queue_clear (&ctx->queued_bufs);
1127 g_free (ctx);
1128 }
1129
1130 static void
1131 send_fragment_opened_closed_msg (GstSplitMuxSink * splitmux, gboolean opened,
1132 GstElement * sink)
1133 {
1134 gchar *location = NULL;
1135 const gchar *msg_name = opened ?
1136 "splitmuxsink-fragment-opened" : "splitmuxsink-fragment-closed";
1137 OutputFragmentInfo *out_fragment_info = &splitmux->out_fragment_info;
1138
1139 if (!opened) {
1140 OutputFragmentInfo *sink_fragment_info =
1141 g_object_get_qdata (G_OBJECT (sink), SINK_FRAGMENT_INFO);
1142 if (sink_fragment_info != NULL) {
1143 out_fragment_info = sink_fragment_info;
1144 }
1145 }
1146
1147 if (g_object_class_find_property (G_OBJECT_GET_CLASS (sink),
1148 "location") != NULL) {
1149 g_object_get (sink, "location", &location, NULL);
1150 }
1151
1152 GST_DEBUG_OBJECT (splitmux,
1153 "Sending %s message. Running time %" GST_TIME_FORMAT " location %s",
1154 msg_name, GST_TIME_ARGS (out_fragment_info->last_running_time),
1155 GST_STR_NULL (location));
1156
1157 /* If it's in the middle of a teardown, the reference_ctc might have become
1158 * NULL */
1159 if (splitmux->reference_ctx) {
1160 GstStructure *s = gst_structure_new (msg_name,
1161 "fragment-id", G_TYPE_UINT, out_fragment_info->fragment_id,
1162 "location", G_TYPE_STRING, location,
1163 "running-time", GST_TYPE_CLOCK_TIME,
1164 out_fragment_info->last_running_time, "sink", GST_TYPE_ELEMENT,
1165 sink, NULL);
1166
1167 if (!opened) {
1168 GstClockTime offset = out_fragment_info->fragment_offset;
1169 GstClockTime duration = out_fragment_info->fragment_duration;
1170
1171 gst_structure_set (s,
1172 "fragment-offset", GST_TYPE_CLOCK_TIME, offset,
1173 "fragment-duration", GST_TYPE_CLOCK_TIME, duration, NULL);
1174 }
1175 GstMessage *msg = gst_message_new_element (GST_OBJECT (splitmux), s);
1176 gst_element_post_message (GST_ELEMENT_CAST (splitmux), msg);
1177 }
1178
1179 g_free (location);
1180 }
1181
1182 static void
1183 send_eos_async (GstSplitMuxSink * splitmux, AsyncEosHelper * helper)
1184 {
1185 GstEvent *eos;
1186 GstPad *pad;
1187 MqStreamCtx *ctx;
1188
1189 eos = gst_event_new_eos ();
1190 pad = helper->pad;
1191 ctx = helper->ctx;
1192
1193 GST_SPLITMUX_LOCK (splitmux);
1194 if (!pad)
1195 pad = gst_pad_get_peer (ctx->srcpad);
1196 GST_SPLITMUX_UNLOCK (splitmux);
1197
1198 gst_pad_send_event (pad, eos);
1199 GST_INFO_OBJECT (splitmux, "Sent async EOS on %" GST_PTR_FORMAT, pad);
1200
1201 gst_object_unref (pad);
1202 g_free (helper);
1203 }
1204
1205 /* Called with lock held, drops the lock to send EOS to the
1206 * pad
1207 */
1208 static void
1209 send_eos (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
1210 {
1211 GstEvent *eos;
1212 GstPad *pad;
1213
1214 eos = gst_event_new_eos ();
1215 pad = gst_pad_get_peer (ctx->srcpad);
1216
1217 ctx->out_eos = TRUE;
1218
1219 GST_INFO_OBJECT (splitmux, "Sending EOS on %" GST_PTR_FORMAT, pad);
1220 GST_SPLITMUX_UNLOCK (splitmux);
1221 gst_pad_send_event (pad, eos);
1222 GST_SPLITMUX_LOCK (splitmux);
1223
1224 gst_object_unref (pad);
1225 }
1226
1227 /* Called with lock held. Schedules an EOS event to the ctx pad
1228 * to happen in another thread */
1229 static void
1230 eos_context_async (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
1231 {
1232 AsyncEosHelper *helper = g_new0 (AsyncEosHelper, 1);
1233 GstPad *srcpad, *sinkpad;
1234
1235 srcpad = ctx->srcpad;
1236 sinkpad = gst_pad_get_peer (srcpad);
1237
1238 helper->ctx = ctx;
1239 helper->pad = sinkpad; /* Takes the reference */
1240
1241 ctx->out_eos_async_done = TRUE;
1242
1243 /* There used to be a bug here, where we had to explicitly remove
1244 * the SINK flag so that GstBin would ignore it for EOS purposes.
1245 * That fixed a race where if splitmuxsink really reaches EOS
1246 * before an asynchronous background element has finished, then
1247 * the bin wouldn't actually send EOS to the pipeline. Even after
1248 * finishing and removing the old element, the bin didn't re-check
1249 * EOS status on removing a SINK element. That bug was fixed
1250 * in core. */
1251 GST_DEBUG_OBJECT (splitmux, "scheduled EOS to pad %" GST_PTR_FORMAT " ctx %p",
1252 sinkpad, ctx);
1253
1254 g_assert_nonnull (helper->pad);
1255 gst_object_call_async (GST_OBJECT (splitmux),
1256 (GstObjectCallAsyncFunc) send_eos_async, helper);
1257 }
1258
1259 /* Called with lock held. TRUE iff all contexts have a
1260 * pending (or delivered) async eos event */
1261 static gboolean
1262 all_contexts_are_async_eos (GstSplitMuxSink * splitmux)
1263 {
1264 gboolean ret = TRUE;
1265 GList *item;
1266
1267 for (item = splitmux->contexts; item; item = item->next) {
1268 MqStreamCtx *ctx = item->data;
1269 ret &= ctx->out_eos_async_done;
1270 }
1271 return ret;
1272 }
1273
1274 /* Called with splitmux lock held before ending a fragment,
1275 * to update the fragment info used for sending fragment opened/closed messages */
1276 static void
1277 update_output_fragment_info (GstSplitMuxSink * splitmux)
1278 {
1279 // Update the fragment output info before finalization
1280
1281 GstClockTime offset =
1282 splitmux->out_fragment_start_runts - splitmux->out_start_runts;
1283
1284 GstClockTime duration = GST_CLOCK_TIME_NONE;
1285
1286 /* Look for the largest duration across all streams */
1287 for (GList * item = splitmux->contexts; item; item = item->next) {
1288 MqStreamCtx *ctx = item->data;
1289 if (ctx->out_running_time_end > splitmux->out_fragment_start_runts) {
1290 GstClockTime ctx_duration =
1291 ctx->out_running_time_end - splitmux->out_fragment_start_runts;
1292 if (!GST_CLOCK_TIME_IS_VALID (duration) || ctx_duration > duration) {
1293 duration = ctx_duration;
1294 }
1295 }
1296 }
1297
1298 GST_LOG_OBJECT (splitmux,
1299 "Updating fragment info with reference TS %" GST_STIME_FORMAT
1300 " with fragment-offset %" GST_TIMEP_FORMAT
1301 " and fragment-duration %" GST_TIMEP_FORMAT,
1302 GST_STIME_ARGS (splitmux->reference_ctx->out_running_time),
1303 &offset, &duration);
1304
1305 splitmux->out_fragment_info.fragment_id = splitmux->cur_fragment_id;
1306 splitmux->out_fragment_info.last_running_time =
1307 splitmux->reference_ctx->out_running_time;
1308 splitmux->out_fragment_info.fragment_offset = offset;
1309 splitmux->out_fragment_info.fragment_duration = duration;
1310 }
1311
1312 /* Called with splitmux lock held to check if this output
1313 * context needs to sleep to wait for the release of the
1314 * next GOP, or to send EOS to close out the current file
1315 */
1316 static GstFlowReturn
1317 complete_or_wait_on_out (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
1318 {
1319 if (ctx->caps_change)
1320 return GST_FLOW_OK;
1321
1322 do {
1323 /* When first starting up, the reference stream has to output
1324 * the first buffer to prepare the muxer and sink */
1325 gboolean can_output = (ctx->is_reference || splitmux->ready_for_output);
1326 GstClockTimeDiff my_max_out_running_time = splitmux->max_out_running_time;
1327
1328 if (my_max_out_running_time != GST_CLOCK_STIME_NONE
1329 && my_max_out_running_time != G_MAXINT64) {
1330 my_max_out_running_time -= splitmux->alignment_threshold;
1331 GST_LOG_OBJECT (ctx->srcpad,
1332 "Max out running time currently %" GST_STIME_FORMAT
1333 ", with threshold applied it is %" GST_STIME_FORMAT,
1334 GST_STIME_ARGS (splitmux->max_out_running_time),
1335 GST_STIME_ARGS (my_max_out_running_time));
1336 }
1337
1338 if (ctx->flushing
1339 || splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
1340 return GST_FLOW_FLUSHING;
1341
1342 GST_LOG_OBJECT (ctx->srcpad,
1343 "Checking running time %" GST_STIME_FORMAT " against max %"
1344 GST_STIME_FORMAT, GST_STIME_ARGS (ctx->out_running_time),
1345 GST_STIME_ARGS (my_max_out_running_time));
1346
1347 if (can_output) {
1348 /* Always outputting everything up to the next max_out_running_time
1349 * before advancing the state machine */
1350 if (splitmux->max_out_running_time != GST_CLOCK_STIME_NONE &&
1351 ctx->out_running_time < my_max_out_running_time) {
1352 return GST_FLOW_OK;
1353 }
1354
1355 switch (splitmux->output_state) {
1356 case SPLITMUX_OUTPUT_STATE_OUTPUT_GOP:
1357 /* We only get here if we've finished outputting a GOP and need to know
1358 * what to do next */
1359 splitmux->output_state = SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND;
1360 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1361 continue;
1362
1363 case SPLITMUX_OUTPUT_STATE_ENDING_FILE:
1364 case SPLITMUX_OUTPUT_STATE_ENDING_STREAM:
1365 /* We've reached the max out running_time to get here, so end this file now */
1366 if (ctx->out_eos == FALSE) {
1367 update_output_fragment_info (splitmux);
1368
1369 if (splitmux->async_finalize) {
1370 /* For async finalization, we must store the fragment timing
1371 * info on the element via qdata, because EOS will be processed
1372 * asynchronously */
1373
1374 OutputFragmentInfo *sink_fragment_info =
1375 g_new (OutputFragmentInfo, 1);
1376 *sink_fragment_info = splitmux->out_fragment_info;
1377 g_object_set_qdata_full (G_OBJECT (splitmux->sink),
1378 SINK_FRAGMENT_INFO, sink_fragment_info, g_free);
1379
1380 /* We must set EOS asynchronously at this point. We cannot defer
1381 * it, because we need all contexts to wake up, for the
1382 * reference context to eventually give us something at
1383 * START_NEXT_FILE. Otherwise, collectpads might choose another
1384 * context to give us the first buffer, and format-location-full
1385 * will not contain a valid sample. */
1386 g_object_set_qdata ((GObject *) splitmux->sink, EOS_FROM_US,
1387 GINT_TO_POINTER (1));
1388 eos_context_async (ctx, splitmux);
1389 if (all_contexts_are_async_eos (splitmux)) {
1390 GST_INFO_OBJECT (splitmux,
1391 "All contexts are async_eos. Moving to the next file.");
1392 /* We can start the next file once we've asked each pad to go EOS */
1393 splitmux->output_state = SPLITMUX_OUTPUT_STATE_START_NEXT_FILE;
1394 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1395 continue;
1396 }
1397 } else {
1398 send_eos (splitmux, ctx);
1399 continue;
1400 }
1401 } else if (splitmux->output_state ==
1402 SPLITMUX_OUTPUT_STATE_ENDING_STREAM) {
1403 GST_LOG_OBJECT (splitmux,
1404 "At end-of-stream state, and context %p is already EOS. Returning.",
1405 ctx);
1406 return GST_FLOW_OK;
1407 } else {
1408 GST_INFO_OBJECT (splitmux,
1409 "At end-of-file state, and context %p is already EOS.", ctx);
1410 }
1411 break;
1412 case SPLITMUX_OUTPUT_STATE_START_NEXT_FILE:
1413 if (ctx->is_reference) {
1414 GstFlowReturn ret = GST_FLOW_OK;
1415
1416 /* Special handling on the reference ctx to start new fragments
1417 * and collect commands from the command queue */
1418 /* drops the splitmux lock briefly: */
1419 /* We must have reference ctx in order for format-location-full to
1420 * have a sample */
1421 ret = start_next_fragment (splitmux, ctx);
1422 if (ret != GST_FLOW_OK)
1423 return ret;
1424
1425 continue;
1426 }
1427 break;
1428 case SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND:{
1429 do {
1430 SplitMuxOutputCommand *cmd =
1431 g_queue_pop_tail (&splitmux->out_cmd_q);
1432 if (cmd != NULL) {
1433 /* If we pop the last command, we need to make our queues bigger */
1434 if (g_queue_get_length (&splitmux->out_cmd_q) == 0)
1435 grow_blocked_queues (splitmux);
1436
1437 switch (cmd->cmd_type) {
1438 case SPLITMUX_OUTPUT_COMMAND_FINISH_FRAGMENT:
1439 {
1440 if (splitmux->muxed_out_bytes > 0) {
1441 GST_DEBUG_OBJECT (splitmux,
1442 "Got cmd to start new fragment");
1443 splitmux->output_state = SPLITMUX_OUTPUT_STATE_ENDING_FILE;
1444 } else {
1445 GST_DEBUG_OBJECT (splitmux,
1446 "Got cmd to start new fragment, but fragment is empty - ignoring.");
1447 }
1448 break;
1449 }
1450 case SPLITMUX_OUTPUT_COMMAND_RELEASE_GOP:
1451 {
1452 GstClockTimeDiff new_max_output_ts =
1453 cmd->release_gop.max_output_ts;
1454
1455 GST_DEBUG_OBJECT (splitmux,
1456 "Got new output cmd for time %" GST_STIME_FORMAT,
1457 GST_STIME_ARGS (new_max_output_ts));
1458
1459 /* Extend the output range immediately */
1460 if (splitmux->max_out_running_time == GST_CLOCK_STIME_NONE
1461 || new_max_output_ts > splitmux->max_out_running_time)
1462 splitmux->max_out_running_time = new_max_output_ts;
1463 GST_DEBUG_OBJECT (splitmux,
1464 "Max out running time now %" GST_STIME_FORMAT,
1465 GST_STIME_ARGS (splitmux->max_out_running_time));
1466 splitmux->output_state = SPLITMUX_OUTPUT_STATE_OUTPUT_GOP;
1467 break;
1468 }
1469 default:
1470 g_assert_not_reached ();
1471 break;
1472 }
1473
1474 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1475 out_cmd_buf_free (cmd);
1476 break;
1477 } else {
1478 GST_SPLITMUX_WAIT_OUTPUT (splitmux);
1479 }
1480 } while (!ctx->flushing && splitmux->output_state ==
1481 SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND);
1482 /* loop and re-check the state */
1483 continue;
1484 }
1485 case SPLITMUX_OUTPUT_STATE_STOPPED:
1486 return GST_FLOW_FLUSHING;
1487 }
1488 } else {
1489 GST_LOG_OBJECT (ctx->srcpad, "Not yet ready for output");
1490 }
1491
1492 GST_INFO_OBJECT (ctx->srcpad,
1493 "Sleeping for running time %"
1494 GST_STIME_FORMAT " (max %" GST_STIME_FORMAT ") or state change.",
1495 GST_STIME_ARGS (ctx->out_running_time),
1496 GST_STIME_ARGS (splitmux->max_out_running_time));
1497 GST_SPLITMUX_WAIT_OUTPUT (splitmux);
1498 GST_INFO_OBJECT (ctx->srcpad,
1499 "Woken for new max running time %" GST_STIME_FORMAT,
1500 GST_STIME_ARGS (splitmux->max_out_running_time));
1501 }
1502 while (1);
1503
1504 return GST_FLOW_OK;
1505 }
1506
1507 static GstClockTime
1508 calculate_next_max_timecode (GstSplitMuxSink * splitmux,
1509 const GstVideoTimeCode * cur_tc, GstClockTime running_time,
1510 GstVideoTimeCode ** next_tc)
1511 {
1512 GstVideoTimeCode *target_tc;
1513 GstClockTime cur_tc_time, target_tc_time, next_max_tc_time;
1514
1515 if (cur_tc == NULL || splitmux->tc_interval == NULL)
1516 return GST_CLOCK_TIME_NONE;
1517
1518 target_tc = gst_video_time_code_add_interval (cur_tc, splitmux->tc_interval);
1519 if (!target_tc) {
1520 GST_ELEMENT_ERROR (splitmux,
1521 STREAM, FAILED, (NULL), ("Couldn't calculate target timecode"));
1522 return GST_CLOCK_TIME_NONE;
1523 }
1524
1525 /* Convert to ns */
1526 target_tc_time = gst_video_time_code_nsec_since_daily_jam (target_tc);
1527 cur_tc_time = gst_video_time_code_nsec_since_daily_jam (cur_tc);
1528
1529 /* Add running_time, accounting for wraparound. */
1530 if (target_tc_time >= cur_tc_time) {
1531 next_max_tc_time = target_tc_time - cur_tc_time + running_time;
1532 } else {
1533 GstClockTime day_in_ns = 24 * 60 * 60 * GST_SECOND;
1534
1535 if ((cur_tc->config.flags & GST_VIDEO_TIME_CODE_FLAGS_DROP_FRAME) &&
1536 (cur_tc->config.fps_d == 1001)) {
1537 /* Checking fps_d is probably unneeded, but better safe than sorry
1538 * (e.g. someone accidentally set a flag) */
1539 GstVideoTimeCode *tc_for_offset;
1540
1541 /* Here, the duration of the 24:00:00;00 timecode isn't exactly one day,
1542 * but slightly less. Calculate that duration from a fake timecode. The
1543 * problem is that 24:00:00;00 isn't a valid timecode, so the workaround
1544 * is to add one frame to 23:59:59;29 */
1545 tc_for_offset =
1546 gst_video_time_code_new (cur_tc->config.fps_n, cur_tc->config.fps_d,
1547 NULL, cur_tc->config.flags, 23, 59, 59,
1548 cur_tc->config.fps_n / cur_tc->config.fps_d, 0);
1549 day_in_ns =
1550 gst_video_time_code_nsec_since_daily_jam (tc_for_offset) +
1551 gst_util_uint64_scale (GST_SECOND, cur_tc->config.fps_d,
1552 cur_tc->config.fps_n);
1553 gst_video_time_code_free (tc_for_offset);
1554 }
1555 next_max_tc_time = day_in_ns - cur_tc_time + target_tc_time + running_time;
1556 }
1557
1558 #ifndef GST_DISABLE_GST_DEBUG
1559 {
1560 gchar *next_max_tc_str, *cur_tc_str;
1561
1562 cur_tc_str = gst_video_time_code_to_string (cur_tc);
1563 next_max_tc_str = gst_video_time_code_to_string (target_tc);
1564
1565 GST_INFO_OBJECT (splitmux, "Next max timecode %s time: %" GST_TIME_FORMAT
1566 " from ref timecode %s time: %" GST_TIME_FORMAT,
1567 next_max_tc_str,
1568 GST_TIME_ARGS (next_max_tc_time),
1569 cur_tc_str, GST_TIME_ARGS (cur_tc_time));
1570
1571 g_free (next_max_tc_str);
1572 g_free (cur_tc_str);
1573 }
1574 #endif
1575
1576 if (next_tc)
1577 *next_tc = target_tc;
1578 else
1579 gst_video_time_code_free (target_tc);
1580
1581 return next_max_tc_time;
1582 }
1583
1584 static gboolean
1585 request_next_keyframe (GstSplitMuxSink * splitmux, GstBuffer * buffer,
1586 GstClockTimeDiff running_time_dts)
1587 {
1588 GstEvent *ev;
1589 GstClockTime target_time;
1590 gboolean timecode_based = FALSE;
1591 GstClockTime max_tc_time = GST_CLOCK_TIME_NONE;
1592 GstClockTime next_max_tc_time = GST_CLOCK_TIME_NONE;
1593 GstClockTime next_fku_time = GST_CLOCK_TIME_NONE;
1594 GstClockTime tc_rounding_error = 5 * GST_USECOND;
1595 InputGop *newest_gop = NULL;
1596 GList *l;
1597
1598 if (!splitmux->send_keyframe_requests)
1599 return TRUE;
1600
1601 /* Find the newest GOP where we passed in DTS the start PTS */
1602 for (l = splitmux->pending_input_gops.tail; l; l = l->prev) {
1603 InputGop *tmp = l->data;
1604
1605 GST_TRACE_OBJECT (splitmux,
1606 "Having pending input GOP with start PTS %" GST_STIME_FORMAT
1607 " and start time %" GST_STIME_FORMAT,
1608 GST_STIME_ARGS (tmp->start_time_pts), GST_STIME_ARGS (tmp->start_time));
1609
1610 if (tmp->sent_fku) {
1611 GST_DEBUG_OBJECT (splitmux,
1612 "Already checked for a keyframe request for this GOP");
1613 return TRUE;
1614 }
1615
1616 if (running_time_dts == GST_CLOCK_STIME_NONE ||
1617 tmp->start_time_pts == GST_CLOCK_STIME_NONE ||
1618 running_time_dts >= tmp->start_time_pts) {
1619 GST_DEBUG_OBJECT (splitmux,
1620 "Using GOP with start PTS %" GST_STIME_FORMAT " and start time %"
1621 GST_STIME_FORMAT, GST_STIME_ARGS (tmp->start_time_pts),
1622 GST_STIME_ARGS (tmp->start_time));
1623 newest_gop = tmp;
1624 break;
1625 }
1626 }
1627
1628 if (!newest_gop) {
1629 GST_DEBUG_OBJECT (splitmux, "Have no complete enough pending input GOP");
1630 return TRUE;
1631 }
1632
1633 if (splitmux->tc_interval) {
1634 if (newest_gop->start_tc
1635 && gst_video_time_code_is_valid (newest_gop->start_tc)) {
1636 GstVideoTimeCode *next_tc = NULL;
1637 max_tc_time =
1638 calculate_next_max_timecode (splitmux, newest_gop->start_tc,
1639 newest_gop->start_time, &next_tc);
1640
1641 /* calculate the next expected keyframe time to prevent too early fku
1642 * event */
1643 if (GST_CLOCK_TIME_IS_VALID (max_tc_time) && next_tc) {
1644 next_max_tc_time =
1645 calculate_next_max_timecode (splitmux, next_tc, max_tc_time, NULL);
1646 }
1647 if (next_tc)
1648 gst_video_time_code_free (next_tc);
1649
1650 timecode_based = GST_CLOCK_TIME_IS_VALID (max_tc_time) &&
1651 GST_CLOCK_TIME_IS_VALID (next_max_tc_time);
1652
1653 if (!timecode_based) {
1654 GST_WARNING_OBJECT (splitmux,
1655 "Couldn't calculate maximum fragment time for timecode mode");
1656 }
1657 } else {
1658 /* This can happen in the presence of GAP events that trigger
1659 * a new fragment start */
1660 GST_WARNING_OBJECT (splitmux,
1661 "No buffer available to calculate next timecode");
1662 }
1663 }
1664
1665 if ((splitmux->threshold_time == 0 && !timecode_based)
1666 || splitmux->threshold_bytes != 0)
1667 return TRUE;
1668
1669 if (timecode_based) {
1670 /* We might have rounding errors: aim slightly earlier */
1671 if (max_tc_time >= tc_rounding_error) {
1672 target_time = max_tc_time - tc_rounding_error;
1673 } else {
1674 /* unreliable target time */
1675 GST_DEBUG_OBJECT (splitmux, "tc time %" GST_TIME_FORMAT
1676 " is smaller than allowed rounding error, set it to zero",
1677 GST_TIME_ARGS (max_tc_time));
1678 target_time = 0;
1679 }
1680
1681 if (next_max_tc_time >= tc_rounding_error) {
1682 next_fku_time = next_max_tc_time - tc_rounding_error;
1683 } else {
1684 /* unreliable target time */
1685 GST_DEBUG_OBJECT (splitmux, "next tc time %" GST_TIME_FORMAT
1686 " is smaller than allowed rounding error, set it to zero",
1687 GST_TIME_ARGS (next_max_tc_time));
1688 next_fku_time = 0;
1689 }
1690 } else {
1691 target_time = newest_gop->start_time + splitmux->threshold_time;
1692 }
1693
1694 if (GST_CLOCK_TIME_IS_VALID (splitmux->next_fku_time)) {
1695 GstClockTime allowed_time = splitmux->next_fku_time;
1696
1697 if (timecode_based) {
1698 if (allowed_time >= tc_rounding_error) {
1699 allowed_time -= tc_rounding_error;
1700 } else {
1701 /* unreliable next force key unit time */
1702 GST_DEBUG_OBJECT (splitmux, "expected next force key unit time %"
1703 GST_TIME_FORMAT
1704 " is smaller than allowed rounding error, set it to zero",
1705 GST_TIME_ARGS (splitmux->next_fku_time));
1706 allowed_time = 0;
1707 }
1708 }
1709
1710 if (target_time < allowed_time) {
1711 GST_LOG_OBJECT (splitmux, "Target time %" GST_TIME_FORMAT
1712 " is smaller than expected next keyframe time %" GST_TIME_FORMAT
1713 ", rounding error compensated next keyframe time %" GST_TIME_FORMAT,
1714 GST_TIME_ARGS (target_time),
1715 GST_TIME_ARGS (splitmux->next_fku_time),
1716 GST_TIME_ARGS (allowed_time));
1717
1718 return TRUE;
1719 } else if (allowed_time != splitmux->next_fku_time &&
1720 target_time < splitmux->next_fku_time) {
1721 GST_DEBUG_OBJECT (splitmux, "Target time %" GST_TIME_FORMAT
1722 " is smaller than expected next keyframe time %" GST_TIME_FORMAT
1723 ", but the difference is smaller than allowed rounding error",
1724 GST_TIME_ARGS (target_time), GST_TIME_ARGS (splitmux->next_fku_time));
1725 }
1726 }
1727
1728 if (!timecode_based) {
1729 next_fku_time = target_time + splitmux->threshold_time;
1730 }
1731
1732 GST_INFO_OBJECT (splitmux, "Requesting keyframe at %" GST_TIME_FORMAT
1733 ", the next expected keyframe request time is %" GST_TIME_FORMAT,
1734 GST_TIME_ARGS (target_time), GST_TIME_ARGS (next_fku_time));
1735
1736 newest_gop->sent_fku = TRUE;
1737
1738 splitmux->next_fku_time = next_fku_time;
1739 ev = gst_video_event_new_upstream_force_key_unit (target_time, TRUE, 0);
1740
1741 return gst_pad_push_event (splitmux->reference_ctx->sinkpad, ev);
1742 }
1743
1744 static GstPadProbeReturn
1745 handle_mq_output (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
1746 {
1747 GstSplitMuxSink *splitmux = ctx->splitmux;
1748 MqStreamBuf *buf_info = NULL;
1749 GstFlowReturn ret = GST_FLOW_OK;
1750
1751 GST_LOG_OBJECT (pad, "Fired probe type 0x%x", info->type);
1752
1753 /* FIXME: Handle buffer lists, until then make it clear they won't work */
1754 if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
1755 g_warning ("Buffer list handling not implemented");
1756 return GST_PAD_PROBE_DROP;
1757 }
1758 if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM ||
1759 info->type & GST_PAD_PROBE_TYPE_EVENT_FLUSH) {
1760 GstEvent *event = gst_pad_probe_info_get_event (info);
1761 gboolean locked = FALSE, wait = !ctx->is_reference;
1762
1763 GST_LOG_OBJECT (pad, "Event %" GST_PTR_FORMAT, event);
1764
1765 switch (GST_EVENT_TYPE (event)) {
1766 case GST_EVENT_SEGMENT:
1767 gst_event_copy_segment (event, &ctx->out_segment);
1768 break;
1769 case GST_EVENT_FLUSH_STOP:
1770 GST_SPLITMUX_LOCK (splitmux);
1771 locked = TRUE;
1772 gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
1773 g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
1774 g_queue_clear (&ctx->queued_bufs);
1775 g_queue_clear (&ctx->queued_bufs);
1776 /* If this is the reference context, we just threw away any queued keyframes */
1777 if (ctx->is_reference)
1778 splitmux->queued_keyframes = 0;
1779 ctx->flushing = FALSE;
1780 wait = FALSE;
1781 break;
1782 case GST_EVENT_FLUSH_START:
1783 GST_SPLITMUX_LOCK (splitmux);
1784 locked = TRUE;
1785 GST_LOG_OBJECT (pad, "Flush start");
1786 ctx->flushing = TRUE;
1787 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
1788 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1789 break;
1790 case GST_EVENT_EOS:
1791 GST_SPLITMUX_LOCK (splitmux);
1792 locked = TRUE;
1793 if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
1794 goto beach;
1795
1796 GST_INFO_OBJECT (splitmux,
1797 "Have EOS event at pad %" GST_PTR_FORMAT " ctx %p", pad, ctx);
1798 ctx->out_eos = TRUE;
1799
1800 if (ctx == splitmux->reference_ctx) {
1801 GST_INFO_OBJECT (splitmux,
1802 "EOS on reference context - ending the recording");
1803 splitmux->output_state = SPLITMUX_OUTPUT_STATE_ENDING_STREAM;
1804 update_output_fragment_info (splitmux);
1805
1806 // Waiting before outputting will ensure the muxer end-of-stream
1807 // qdata is set without racing against this EOS event reaching the muxer
1808 wait = TRUE;
1809 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1810 }
1811
1812 break;
1813 case GST_EVENT_GAP:{
1814 GstClockTime gap_ts;
1815 GstClockTimeDiff rtime;
1816
1817 gst_event_parse_gap (event, &gap_ts, NULL);
1818 if (gap_ts == GST_CLOCK_TIME_NONE)
1819 break;
1820
1821 GST_SPLITMUX_LOCK (splitmux);
1822 locked = TRUE;
1823
1824 if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
1825 goto beach;
1826
1827 /* When we get a gap event on the
1828 * reference stream and we're trying to open a
1829 * new file, we need to store it until we get
1830 * the buffer afterwards
1831 */
1832 if (ctx->is_reference &&
1833 (splitmux->output_state != SPLITMUX_OUTPUT_STATE_OUTPUT_GOP)) {
1834 GST_DEBUG_OBJECT (pad, "Storing GAP event until buffer arrives");
1835 gst_event_replace (&ctx->pending_gap, event);
1836 GST_SPLITMUX_UNLOCK (splitmux);
1837 return GST_PAD_PROBE_HANDLED;
1838 }
1839
1840 rtime = my_segment_to_running_time (&ctx->out_segment, gap_ts);
1841
1842 GST_LOG_OBJECT (pad, "Have GAP w/ ts %" GST_STIME_FORMAT,
1843 GST_STIME_ARGS (rtime));
1844
1845 if (rtime != GST_CLOCK_STIME_NONE) {
1846 ctx->out_running_time = rtime;
1847 complete_or_wait_on_out (splitmux, ctx);
1848 }
1849 break;
1850 }
1851 case GST_EVENT_CUSTOM_DOWNSTREAM:{
1852 const GstStructure *s;
1853 GstClockTimeDiff ts = 0;
1854
1855 s = gst_event_get_structure (event);
1856 if (!gst_structure_has_name (s, "splitmuxsink-unblock"))
1857 break;
1858
1859 gst_structure_get_int64 (s, "timestamp", &ts);
1860
1861 GST_SPLITMUX_LOCK (splitmux);
1862 locked = TRUE;
1863
1864 if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
1865 goto beach;
1866 ctx->out_running_time = ts;
1867 if (!ctx->is_reference)
1868 ret = complete_or_wait_on_out (splitmux, ctx);
1869 GST_SPLITMUX_UNLOCK (splitmux);
1870 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
1871 return GST_PAD_PROBE_DROP;
1872 }
1873 case GST_EVENT_CAPS:{
1874 GstPad *peer;
1875
1876 if (!ctx->is_reference)
1877 break;
1878
1879 peer = gst_pad_get_peer (pad);
1880 if (peer) {
1881 gboolean ok = gst_pad_send_event (peer, gst_event_ref (event));
1882
1883 gst_object_unref (peer);
1884
1885 if (ok)
1886 break;
1887
1888 } else {
1889 break;
1890 }
1891 /* This is in the case the muxer doesn't allow this change of caps */
1892 GST_SPLITMUX_LOCK (splitmux);
1893 locked = TRUE;
1894 ctx->caps_change = TRUE;
1895
1896 if (splitmux->output_state != SPLITMUX_OUTPUT_STATE_START_NEXT_FILE) {
1897 GST_DEBUG_OBJECT (splitmux,
1898 "New caps were not accepted. Switching output file");
1899 if (ctx->out_eos == FALSE) {
1900 splitmux->output_state = SPLITMUX_OUTPUT_STATE_ENDING_FILE;
1901 update_output_fragment_info (splitmux);
1902 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1903 }
1904 }
1905
1906 /* Lets it fall through, if it fails again, then the muxer just can't
1907 * support this format, but at least we have a closed file.
1908 */
1909 break;
1910 }
1911 default:
1912 break;
1913 }
1914
1915 /* We need to make sure events aren't passed
1916 * until the muxer / sink are ready for it */
1917 if (!locked)
1918 GST_SPLITMUX_LOCK (splitmux);
1919 if (wait)
1920 ret = complete_or_wait_on_out (splitmux, ctx);
1921 GST_SPLITMUX_UNLOCK (splitmux);
1922
1923 /* Don't try to forward sticky events before the next buffer is there
1924 * because it would cause a new file to be created without the first
1925 * buffer being available.
1926 */
1927 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
1928 if (ctx->caps_change && GST_EVENT_IS_STICKY (event)) {
1929 gst_event_unref (event);
1930 return GST_PAD_PROBE_HANDLED;
1931 } else {
1932 return GST_PAD_PROBE_PASS;
1933 }
1934 }
1935
1936 /* Allow everything through until the configured next stopping point */
1937 GST_SPLITMUX_LOCK (splitmux);
1938
1939 buf_info = g_queue_pop_tail (&ctx->queued_bufs);
1940 if (buf_info == NULL) {
1941 /* Can only happen due to a poorly timed flush */
1942 ret = GST_FLOW_FLUSHING;
1943 goto beach;
1944 }
1945
1946 /* If we have popped a keyframe, decrement the queued_gop count */
1947 if (buf_info->keyframe && splitmux->queued_keyframes > 0 && ctx->is_reference)
1948 splitmux->queued_keyframes--;
1949
1950 ctx->out_running_time = buf_info->run_ts;
1951
1952 ctx->cur_out_buffer = gst_pad_probe_info_get_buffer (info);
1953
1954 GST_LOG_OBJECT (splitmux,
1955 "Pad %" GST_PTR_FORMAT " buffer with run TS %" GST_STIME_FORMAT
1956 " size %" G_GUINT64_FORMAT,
1957 pad, GST_STIME_ARGS (ctx->out_running_time), buf_info->buf_size);
1958
1959 ctx->caps_change = FALSE;
1960
1961 ret = complete_or_wait_on_out (splitmux, ctx);
1962
1963 splitmux->muxed_out_bytes += buf_info->buf_size;
1964
1965 if (GST_CLOCK_STIME_IS_VALID (buf_info->run_ts)) {
1966 if (!GST_CLOCK_STIME_IS_VALID (ctx->out_fragment_start_runts)) {
1967 ctx->out_fragment_start_runts = buf_info->run_ts;
1968
1969 /* For the first fragment check if this is the earliest of all start running times */
1970 if (splitmux->cur_fragment_id == splitmux->start_index) {
1971 if (!GST_CLOCK_STIME_IS_VALID (splitmux->out_start_runts)
1972 || (ctx->out_fragment_start_runts < splitmux->out_start_runts)) {
1973 splitmux->out_start_runts = ctx->out_fragment_start_runts;
1974 GST_LOG_OBJECT (splitmux,
1975 "Overall recording start TS now %" GST_STIMEP_FORMAT,
1976 &splitmux->out_start_runts);
1977 }
1978 }
1979
1980 if (!GST_CLOCK_STIME_IS_VALID (splitmux->out_fragment_start_runts)
1981 || (ctx->out_fragment_start_runts <
1982 splitmux->out_fragment_start_runts)) {
1983 splitmux->out_fragment_start_runts = ctx->out_fragment_start_runts;
1984
1985 GST_LOG_OBJECT (splitmux,
1986 "Overall fragment start TS now %" GST_STIMEP_FORMAT,
1987 &splitmux->out_fragment_start_runts);
1988 }
1989
1990 GST_LOG_OBJECT (splitmux,
1991 "Pad %" GST_PTR_FORMAT " buffer run TS %" GST_STIME_FORMAT
1992 " is first for this fragment", pad,
1993 GST_STIME_ARGS (ctx->out_fragment_start_runts));
1994 }
1995
1996 /* Extend the context end running time if it grew */
1997 GstClockTime end_run_ts = buf_info->run_ts;
1998 if (GST_CLOCK_TIME_IS_VALID (buf_info->duration)) {
1999 end_run_ts += buf_info->duration;
2000 }
2001 if (!GST_CLOCK_TIME_IS_VALID (ctx->out_running_time_end) ||
2002 end_run_ts > ctx->out_running_time_end) {
2003 ctx->out_running_time_end = end_run_ts;
2004
2005 GstClockTimeDiff duration = end_run_ts - ctx->out_fragment_start_runts;
2006 GST_LOG_OBJECT (splitmux,
2007 "Pad %" GST_PTR_FORMAT " fragment duration now %" GST_STIMEP_FORMAT,
2008 pad, &duration);
2009 }
2010 }
2011 #ifndef GST_DISABLE_GST_DEBUG
2012 {
2013 GstBuffer *buf = gst_pad_probe_info_get_buffer (info);
2014
2015 GST_LOG_OBJECT (pad, "Returning to pass buffer %" GST_PTR_FORMAT
2016 " run ts %" GST_STIME_FORMAT, buf,
2017 GST_STIME_ARGS (ctx->out_running_time));
2018 }
2019 #endif
2020
2021 ctx->cur_out_buffer = NULL;
2022 GST_SPLITMUX_UNLOCK (splitmux);
2023
2024 /* pending_gap is protected by the STREAM lock */
2025 if (ctx->pending_gap) {
2026 /* If we previously stored a gap event, send it now */
2027 GstPad *peer = gst_pad_get_peer (ctx->srcpad);
2028
2029 GST_DEBUG_OBJECT (splitmux,
2030 "Pad %" GST_PTR_FORMAT " sending pending GAP event", ctx->srcpad);
2031
2032 gst_pad_send_event (peer, ctx->pending_gap);
2033 ctx->pending_gap = NULL;
2034
2035 gst_object_unref (peer);
2036 }
2037
2038 mq_stream_buf_free (buf_info);
2039
2040 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
2041 return GST_PAD_PROBE_PASS;
2042
2043 beach:
2044 GST_SPLITMUX_UNLOCK (splitmux);
2045 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
2046 return GST_PAD_PROBE_DROP;
2047 }
2048
2049 static gboolean
2050 resend_sticky (GstPad * pad, GstEvent ** event, GstPad * peer)
2051 {
2052 return gst_pad_send_event (peer, gst_event_ref (*event));
2053 }
2054
2055 static void
2056 unlock_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
2057 {
2058 if (ctx->fragment_block_id > 0) {
2059 gst_pad_remove_probe (ctx->srcpad, ctx->fragment_block_id);
2060 ctx->fragment_block_id = 0;
2061 }
2062 }
2063
2064 static void
2065 restart_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
2066 {
2067 GstPad *peer = gst_pad_get_peer (ctx->srcpad);
2068
2069 gst_pad_sticky_events_foreach (ctx->srcpad,
2070 (GstPadStickyEventsForeachFunction) (resend_sticky), peer);
2071
2072 /* Clear EOS flag if not actually EOS */
2073 ctx->out_eos = GST_PAD_IS_EOS (ctx->srcpad);
2074 ctx->out_eos_async_done = ctx->out_eos;
2075 ctx->out_fragment_start_runts = GST_CLOCK_STIME_NONE;
2076
2077 gst_object_unref (peer);
2078 }
2079
2080 static void
2081 relink_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
2082 {
2083 GstPad *sinkpad, *srcpad, *newpad;
2084 GstPadTemplate *templ;
2085
2086 srcpad = ctx->srcpad;
2087 sinkpad = gst_pad_get_peer (srcpad);
2088
2089 templ = sinkpad->padtemplate;
2090 newpad =
2091 gst_element_request_pad (splitmux->muxer, templ,
2092 GST_PAD_NAME (sinkpad), NULL);
2093
2094 GST_DEBUG_OBJECT (splitmux, "Relinking ctx %p to pad %" GST_PTR_FORMAT, ctx,
2095 newpad);
2096 if (!gst_pad_unlink (srcpad, sinkpad)) {
2097 gst_object_unref (sinkpad);
2098 goto fail;
2099 }
2100 if (gst_pad_link_full (srcpad, newpad,
2101 GST_PAD_LINK_CHECK_NO_RECONFIGURE) != GST_PAD_LINK_OK) {
2102 gst_element_release_request_pad (splitmux->muxer, newpad);
2103 gst_object_unref (sinkpad);
2104 gst_object_unref (newpad);
2105 goto fail;
2106 }
2107 gst_object_unref (newpad);
2108 gst_object_unref (sinkpad);
2109 return;
2110
2111 fail:
2112 GST_ELEMENT_ERROR (splitmux, RESOURCE, SETTINGS,
2113 ("Could not create the new muxer/sink"), NULL);
2114 }
2115
2116 static GstPadProbeReturn
2117 _block_pad (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2118 {
2119 return GST_PAD_PROBE_OK;
2120 }
2121
2122 static void
2123 block_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
2124 {
2125 ctx->fragment_block_id =
2126 gst_pad_add_probe (ctx->srcpad, GST_PAD_PROBE_TYPE_BLOCK, _block_pad,
2127 NULL, NULL);
2128 }
2129
2130 static gboolean
2131 _set_property_from_structure (const GstIdStr * fieldname, const GValue * value,
2132 gpointer user_data)
2133 {
2134 const gchar *property_name = gst_id_str_as_str (fieldname);
2135 GObject *element = G_OBJECT (user_data);
2136
2137 g_object_set_property (element, property_name, value);
2138
2139 return TRUE;
2140 }
2141
2142 static void
2143 _lock_and_set_to_null (GstElement * element, GstSplitMuxSink * splitmux)
2144 {
2145 gst_element_set_locked_state (element, TRUE);
2146 gst_element_set_state (element, GST_STATE_NULL);
2147 GST_LOG_OBJECT (splitmux, "Removing old element %" GST_PTR_FORMAT, element);
2148 gst_bin_remove (GST_BIN (splitmux), element);
2149 }
2150
2151 static void
2152 _lock_and_set_to_null_async (GstElement * element, GstSplitMuxSink * splitmux)
2153 {
2154 _lock_and_set_to_null (element, splitmux);
2155 gst_object_unref (splitmux);
2156 }
2157
2158 static void
2159 _send_event (const GValue * value, gpointer user_data)
2160 {
2161 GstPad *pad = g_value_get_object (value);
2162 GstEvent *ev = user_data;
2163
2164 gst_pad_send_event (pad, gst_event_ref (ev));
2165 }
2166
2167 /* Called with lock held when a fragment
2168 * reaches EOS and it is time to restart
2169 * a new fragment
2170 */
2171 static GstFlowReturn
2172 start_next_fragment (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
2173 {
2174 GstElement *muxer, *sink;
2175
2176 g_assert (ctx->is_reference);
2177
2178 /* 1 change to new file */
2179 splitmux->switching_fragment = TRUE;
2180
2181 /* We need to drop the splitmux lock to acquire the state lock
2182 * here and ensure there's no racy state change going on elsewhere */
2183 muxer = gst_object_ref (splitmux->muxer);
2184 sink = gst_object_ref (splitmux->active_sink);
2185
2186 GST_SPLITMUX_UNLOCK (splitmux);
2187 GST_SPLITMUX_STATE_LOCK (splitmux);
2188
2189 if (splitmux->shutdown) {
2190 GST_DEBUG_OBJECT (splitmux,
2191 "Shutdown requested. Aborting fragment switch.");
2192 GST_SPLITMUX_LOCK (splitmux);
2193 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2194 gst_object_unref (muxer);
2195 gst_object_unref (sink);
2196 return GST_FLOW_FLUSHING;
2197 }
2198
2199 if (splitmux->async_finalize) {
2200 if (splitmux->muxed_out_bytes > 0
2201 || splitmux->cur_fragment_id != splitmux->start_index) {
2202 gchar *newname;
2203 GstElement *new_sink, *new_muxer;
2204
2205 GST_DEBUG_OBJECT (splitmux, "Starting fragment %u",
2206 splitmux->next_fragment_id);
2207 g_list_foreach (splitmux->contexts, (GFunc) block_context, splitmux);
2208 newname = g_strdup_printf ("sink_%u", splitmux->next_fragment_id);
2209 GST_SPLITMUX_LOCK (splitmux);
2210 if ((splitmux->sink =
2211 create_element (splitmux, splitmux->sink_factory, newname,
2212 TRUE)) == NULL)
2213 goto fail;
2214 if (splitmux->sink_preset && GST_IS_PRESET (splitmux->sink))
2215 gst_preset_load_preset (GST_PRESET (splitmux->sink),
2216 splitmux->sink_preset);
2217 if (splitmux->sink_properties)
2218 gst_structure_foreach_id_str (splitmux->sink_properties,
2219 _set_property_from_structure, splitmux->sink);
2220 splitmux->active_sink = splitmux->sink;
2221 g_signal_emit (splitmux, signals[SIGNAL_SINK_ADDED], 0, splitmux->sink);
2222 g_free (newname);
2223 newname = g_strdup_printf ("muxer_%u", splitmux->next_fragment_id);
2224 if ((splitmux->muxer =
2225 create_element (splitmux, splitmux->muxer_factory, newname,
2226 TRUE)) == NULL)
2227 goto fail;
2228 if (g_object_class_find_property (G_OBJECT_GET_CLASS (splitmux->sink),
2229 "async") != NULL) {
2230 /* async child elements are causing state change races and weird
2231 * failures, so let's try and turn that off */
2232 g_object_set (splitmux->sink, "async", FALSE, NULL);
2233 }
2234 if (splitmux->muxer_preset && GST_IS_PRESET (splitmux->muxer))
2235 gst_preset_load_preset (GST_PRESET (splitmux->muxer),
2236 splitmux->muxer_preset);
2237 if (splitmux->muxer_properties)
2238 gst_structure_foreach_id_str (splitmux->muxer_properties,
2239 _set_property_from_structure, splitmux->muxer);
2240 g_signal_emit (splitmux, signals[SIGNAL_MUXER_ADDED], 0, splitmux->muxer);
2241 g_free (newname);
2242 new_sink = splitmux->sink;
2243 new_muxer = splitmux->muxer;
2244 GST_SPLITMUX_UNLOCK (splitmux);
2245 g_list_foreach (splitmux->contexts, (GFunc) relink_context, splitmux);
2246 gst_element_link (new_muxer, new_sink);
2247
2248 if (g_object_get_qdata ((GObject *) sink, EOS_FROM_US)) {
2249 if (GPOINTER_TO_INT (g_object_get_qdata ((GObject *) sink,
2250 EOS_FROM_US)) == 2) {
2251 _lock_and_set_to_null (muxer, splitmux);
2252 _lock_and_set_to_null (sink, splitmux);
2253 } else {
2254 g_object_set_qdata ((GObject *) sink, EOS_FROM_US,
2255 GINT_TO_POINTER (2));
2256 }
2257 }
2258 gst_object_unref (muxer);
2259 gst_object_unref (sink);
2260 muxer = new_muxer;
2261 sink = new_sink;
2262 gst_object_ref (muxer);
2263 gst_object_ref (sink);
2264 }
2265 } else {
2266
2267 gst_element_set_locked_state (muxer, TRUE);
2268 gst_element_set_locked_state (sink, TRUE);
2269 gst_element_set_state (sink, GST_STATE_NULL);
2270
2271 if (splitmux->reset_muxer) {
2272 gst_element_set_state (muxer, GST_STATE_NULL);
2273 } else {
2274 GstIterator *it = gst_element_iterate_sink_pads (muxer);
2275 GstEvent *ev;
2276 guint32 seqnum;
2277
2278 ev = gst_event_new_flush_start ();
2279 seqnum = gst_event_get_seqnum (ev);
2280 while (gst_iterator_foreach (it, _send_event, ev) == GST_ITERATOR_RESYNC);
2281 gst_event_unref (ev);
2282
2283 gst_iterator_resync (it);
2284
2285 ev = gst_event_new_flush_stop (TRUE);
2286 gst_event_set_seqnum (ev, seqnum);
2287 while (gst_iterator_foreach (it, _send_event, ev) == GST_ITERATOR_RESYNC);
2288 gst_event_unref (ev);
2289
2290 gst_iterator_free (it);
2291 }
2292 }
2293
2294 GST_SPLITMUX_LOCK (splitmux);
2295 if (!set_next_filename (splitmux, ctx))
2296 goto fail_next_filename_with_lock_held;
2297
2298 splitmux->next_fragment_id++;
2299 splitmux->muxed_out_bytes = 0;
2300 splitmux->out_fragment_start_runts = GST_CLOCK_STIME_NONE;
2301 GST_SPLITMUX_UNLOCK (splitmux);
2302
2303 if (gst_element_set_state (sink,
2304 GST_STATE_TARGET (splitmux)) == GST_STATE_CHANGE_FAILURE) {
2305 gst_element_set_state (sink, GST_STATE_NULL);
2306 gst_element_set_locked_state (muxer, FALSE);
2307 gst_element_set_locked_state (sink, FALSE);
2308
2309 goto fail_output;
2310 }
2311
2312 if (gst_element_set_state (muxer,
2313 GST_STATE_TARGET (splitmux)) == GST_STATE_CHANGE_FAILURE) {
2314 gst_element_set_state (muxer, GST_STATE_NULL);
2315 gst_element_set_state (sink, GST_STATE_NULL);
2316 gst_element_set_locked_state (muxer, FALSE);
2317 gst_element_set_locked_state (sink, FALSE);
2318 goto fail_muxer;
2319 }
2320
2321 gst_element_set_locked_state (muxer, FALSE);
2322 gst_element_set_locked_state (sink, FALSE);
2323
2324 gst_object_unref (sink);
2325 gst_object_unref (muxer);
2326
2327 GST_SPLITMUX_LOCK (splitmux);
2328 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2329 splitmux->switching_fragment = FALSE;
2330 do_async_done (splitmux);
2331
2332 splitmux->ready_for_output = TRUE;
2333
2334 g_list_foreach (splitmux->contexts, (GFunc) unlock_context, splitmux);
2335 g_list_foreach (splitmux->contexts, (GFunc) restart_context, splitmux);
2336
2337 update_output_fragment_info (splitmux);
2338 g_object_set_qdata ((GObject *) sink, SENT_FRAGMENT_CLOSED, NULL);
2339 send_fragment_opened_closed_msg (splitmux, TRUE, sink);
2340
2341 /* FIXME: Is this always the correct next state? */
2342 GST_LOG_OBJECT (splitmux, "Resetting state to AWAITING_COMMAND");
2343 splitmux->output_state = SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND;
2344 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
2345 return GST_FLOW_OK;
2346
2347 fail:
2348 gst_object_unref (sink);
2349 gst_object_unref (muxer);
2350
2351 GST_SPLITMUX_LOCK (splitmux);
2352 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2353 GST_ELEMENT_ERROR (splitmux, RESOURCE, SETTINGS,
2354 ("Could not create the new muxer/sink"), NULL);
2355 return GST_FLOW_ERROR;
2356
2357 fail_next_filename_with_lock_held:
2358 gst_object_unref (sink);
2359 gst_object_unref (muxer);
2360
2361 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2362 splitmux->switching_fragment = FALSE;
2363 return GST_FLOW_ERROR;
2364
2365 fail_output:
2366 GST_ELEMENT_ERROR (splitmux, RESOURCE, SETTINGS,
2367 ("Could not start new output sink"), NULL);
2368 gst_object_unref (sink);
2369 gst_object_unref (muxer);
2370
2371 GST_SPLITMUX_LOCK (splitmux);
2372 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2373 splitmux->switching_fragment = FALSE;
2374 return GST_FLOW_ERROR;
2375
2376 fail_muxer:
2377 GST_ELEMENT_ERROR (splitmux, RESOURCE, SETTINGS,
2378 ("Could not start new muxer"), NULL);
2379 gst_object_unref (sink);
2380 gst_object_unref (muxer);
2381
2382 GST_SPLITMUX_LOCK (splitmux);
2383 GST_SPLITMUX_STATE_UNLOCK (splitmux);
2384 splitmux->switching_fragment = FALSE;
2385 return GST_FLOW_ERROR;
2386 }
2387
2388 static void
2389 bus_handler (GstBin * bin, GstMessage * message)
2390 {
2391 GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (bin);
2392
2393 switch (GST_MESSAGE_TYPE (message)) {
2394 case GST_MESSAGE_EOS:{
2395 /* If the state is draining out the current file, drop this EOS */
2396 GstElement *sink;
2397
2398 sink = GST_ELEMENT (GST_MESSAGE_SRC (message));
2399 GST_SPLITMUX_LOCK (splitmux);
2400
2401 if (!g_object_get_qdata ((GObject *) sink, SENT_FRAGMENT_CLOSED)) {
2402 send_fragment_opened_closed_msg (splitmux, FALSE, sink);
2403 g_object_set_qdata ((GObject *) sink, SENT_FRAGMENT_CLOSED,
2404 GINT_TO_POINTER (TRUE));
2405 }
2406
2407 if (splitmux->async_finalize) {
2408
2409 if (g_object_get_qdata ((GObject *) sink, EOS_FROM_US)) {
2410 if (GPOINTER_TO_INT (g_object_get_qdata ((GObject *) sink,
2411 EOS_FROM_US)) == 2) {
2412 GstElement *muxer;
2413 GstPad *sinksink, *muxersrc;
2414
2415 sinksink = gst_element_get_static_pad (sink, "sink");
2416 muxersrc = gst_pad_get_peer (sinksink);
2417 muxer = gst_pad_get_parent_element (muxersrc);
2418 gst_object_unref (sinksink);
2419 gst_object_unref (muxersrc);
2420
2421 gst_object_call_async (GST_OBJECT_CAST (muxer),
2422 (GstObjectCallAsyncFunc) _lock_and_set_to_null_async,
2423 gst_object_ref (splitmux));
2424 gst_object_call_async (GST_OBJECT_CAST (sink),
2425 (GstObjectCallAsyncFunc) _lock_and_set_to_null_async,
2426 gst_object_ref (splitmux));
2427 gst_object_unref (muxer);
2428 } else {
2429 g_object_set_qdata ((GObject *) sink, EOS_FROM_US,
2430 GINT_TO_POINTER (2));
2431 }
2432 GST_DEBUG_OBJECT (splitmux,
2433 "Caught async EOS from previous muxer+sink. Dropping.");
2434 /* We forward the EOS so that it gets aggregated as normal. If the sink
2435 * finishes and is removed before the end, it will be de-aggregated */
2436 gst_message_unref (message);
2437 GST_SPLITMUX_UNLOCK (splitmux);
2438 return;
2439 }
2440 } else if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_ENDING_STREAM) {
2441 GST_DEBUG_OBJECT (splitmux,
2442 "Passing EOS message. Output state %d max_out_running_time %"
2443 GST_STIME_FORMAT, splitmux->output_state,
2444 GST_STIME_ARGS (splitmux->max_out_running_time));
2445 } else {
2446 GST_DEBUG_OBJECT (splitmux, "Caught EOS at end of fragment, dropping");
2447 splitmux->output_state = SPLITMUX_OUTPUT_STATE_START_NEXT_FILE;
2448 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
2449
2450 gst_message_unref (message);
2451 GST_SPLITMUX_UNLOCK (splitmux);
2452 return;
2453 }
2454 GST_SPLITMUX_UNLOCK (splitmux);
2455 break;
2456 }
2457 case GST_MESSAGE_ASYNC_START:
2458 case GST_MESSAGE_ASYNC_DONE:
2459 /* Ignore state changes from our children while switching */
2460 GST_SPLITMUX_LOCK (splitmux);
2461 if (splitmux->switching_fragment) {
2462 if (GST_MESSAGE_SRC (message) == (GstObject *) splitmux->active_sink
2463 || GST_MESSAGE_SRC (message) == (GstObject *) splitmux->muxer) {
2464 GST_LOG_OBJECT (splitmux,
2465 "Ignoring state change from child %" GST_PTR_FORMAT
2466 " while switching", GST_MESSAGE_SRC (message));
2467 gst_message_unref (message);
2468 GST_SPLITMUX_UNLOCK (splitmux);
2469 return;
2470 }
2471 }
2472 GST_SPLITMUX_UNLOCK (splitmux);
2473 break;
2474 case GST_MESSAGE_WARNING:
2475 {
2476 GError *gerror = NULL;
2477
2478 gst_message_parse_warning (message, &gerror, NULL);
2479
2480 if (g_error_matches (gerror, GST_STREAM_ERROR, GST_STREAM_ERROR_FORMAT)) {
2481 GList *item;
2482 gboolean caps_change = FALSE;
2483
2484 GST_SPLITMUX_LOCK (splitmux);
2485
2486 for (item = splitmux->contexts; item; item = item->next) {
2487 MqStreamCtx *ctx = item->data;
2488
2489 if (ctx->caps_change) {
2490 caps_change = TRUE;
2491 break;
2492 }
2493 }
2494
2495 GST_SPLITMUX_UNLOCK (splitmux);
2496
2497 if (caps_change) {
2498 GST_LOG_OBJECT (splitmux,
2499 "Ignoring warning change from child %" GST_PTR_FORMAT
2500 " while switching caps", GST_MESSAGE_SRC (message));
2501 gst_message_unref (message);
2502 return;
2503 }
2504 }
2505 break;
2506 }
2507 default:
2508 break;
2509 }
2510
2511 GST_BIN_CLASS (parent_class)->handle_message (bin, message);
2512 }
2513
2514 static void
2515 ctx_set_unblock (MqStreamCtx * ctx)
2516 {
2517 ctx->need_unblock = TRUE;
2518 }
2519
2520 static gboolean
2521 need_new_fragment (GstSplitMuxSink * splitmux,
2522 GstClockTime queued_time, GstClockTime queued_gop_time,
2523 guint64 queued_bytes)
2524 {
2525 guint64 thresh_bytes;
2526 GstClockTime thresh_time;
2527 gboolean check_robust_muxing;
2528 GstClockTime time_to_split = GST_CLOCK_TIME_NONE;
2529 GstClockTime *ptr_to_time;
2530 const InputGop *gop, *next_gop;
2531
2532 GST_OBJECT_LOCK (splitmux);
2533 thresh_bytes = splitmux->threshold_bytes;
2534 thresh_time = splitmux->threshold_time;
2535 ptr_to_time = (GstClockTime *)
2536 gst_vec_deque_peek_head_struct (splitmux->times_to_split);
2537 if (ptr_to_time)
2538 time_to_split = *ptr_to_time;
2539 check_robust_muxing = splitmux->use_robust_muxing
2540 && splitmux->muxer_has_reserved_props;
2541 GST_OBJECT_UNLOCK (splitmux);
2542
2543 /* Have we muxed at least one thing from the reference
2544 * stream into the file? If not, no other streams can have
2545 * either */
2546 if (splitmux->fragment_reference_bytes <= 0) {
2547 GST_TRACE_OBJECT (splitmux,
2548 "Not ready to split - nothing muxed on the reference stream");
2549 return FALSE;
2550 }
2551
2552 /* User told us to split now */
2553 if (g_atomic_int_get (&(splitmux->do_split_next_gop)) == TRUE) {
2554 GST_TRACE_OBJECT (splitmux, "Forcing because split_next_gop is set");
2555 return TRUE;
2556 }
2557
2558 gop = g_queue_peek_head (&splitmux->pending_input_gops);
2559 /* We need a full GOP queued up at this point */
2560 g_assert (gop != NULL);
2561 next_gop = g_queue_peek_nth (&splitmux->pending_input_gops, 1);
2562 /* And the beginning of the next GOP or otherwise EOS */
2563
2564 /* User told us to split at this running time */
2565 if (gop->start_time >= time_to_split) {
2566 GST_OBJECT_LOCK (splitmux);
2567 /* Dequeue running time */
2568 gst_vec_deque_pop_head_struct (splitmux->times_to_split);
2569 /* Empty any running times after this that are past now */
2570 ptr_to_time = gst_vec_deque_peek_head_struct (splitmux->times_to_split);
2571 while (ptr_to_time) {
2572 time_to_split = *ptr_to_time;
2573 if (gop->start_time < time_to_split) {
2574 break;
2575 }
2576 gst_vec_deque_pop_head_struct (splitmux->times_to_split);
2577 ptr_to_time = gst_vec_deque_peek_head_struct (splitmux->times_to_split);
2578 }
2579 GST_TRACE_OBJECT (splitmux,
2580 "GOP start time %" GST_STIME_FORMAT " is after requested split point %"
2581 GST_TIME_FORMAT, GST_STIME_ARGS (gop->start_time),
2582 GST_TIME_ARGS (time_to_split));
2583 GST_OBJECT_UNLOCK (splitmux);
2584 return TRUE;
2585 }
2586
2587 if (thresh_bytes > 0 && queued_bytes > thresh_bytes) {
2588 GST_TRACE_OBJECT (splitmux,
2589 "queued bytes %" G_GUINT64_FORMAT " overruns byte limit", queued_bytes);
2590 return TRUE; /* Would overrun byte limit */
2591 }
2592
2593 if (thresh_time > 0 && queued_time > thresh_time) {
2594 GST_TRACE_OBJECT (splitmux,
2595 "queued time %" GST_TIME_FORMAT " overruns time limit",
2596 GST_TIME_ARGS (queued_time));
2597 return TRUE; /* Would overrun time limit */
2598 }
2599
2600 if (splitmux->tc_interval) {
2601 GstClockTimeDiff next_gop_start_time =
2602 next_gop ? next_gop->start_time : splitmux->max_in_running_time;
2603
2604 if (GST_CLOCK_TIME_IS_VALID (splitmux->next_fragment_start_tc_time) &&
2605 GST_CLOCK_STIME_IS_VALID (next_gop_start_time) &&
2606 next_gop_start_time >
2607 splitmux->next_fragment_start_tc_time + 5 * GST_USECOND) {
2608 GST_TRACE_OBJECT (splitmux,
2609 "in running time %" GST_STIME_FORMAT " overruns time limit %"
2610 GST_TIME_FORMAT, GST_STIME_ARGS (next_gop_start_time),
2611 GST_TIME_ARGS (splitmux->next_fragment_start_tc_time));
2612 return TRUE;
2613 }
2614 }
2615
2616 if (check_robust_muxing) {
2617 GstClockTime mux_reserved_remain;
2618
2619 g_object_get (splitmux->muxer,
2620 "reserved-duration-remaining", &mux_reserved_remain, NULL);
2621
2622 GST_LOG_OBJECT (splitmux,
2623 "Muxer robust muxing report - %" G_GUINT64_FORMAT
2624 " remaining. New GOP would enqueue %" G_GUINT64_FORMAT,
2625 mux_reserved_remain, queued_gop_time);
2626
2627 if (queued_gop_time >= mux_reserved_remain) {
2628 GST_INFO_OBJECT (splitmux,
2629 "File is about to run out of header room - %" G_GUINT64_FORMAT
2630 " remaining. New GOP would enqueue %" G_GUINT64_FORMAT
2631 ". Switching to new file", mux_reserved_remain, queued_gop_time);
2632 return TRUE;
2633 }
2634 }
2635
2636 /* Continue and mux this GOP */
2637 return FALSE;
2638 }
2639
2640 /* probably we want to add this API? */
2641 static void
2642 video_time_code_replace (GstVideoTimeCode ** old_tc, GstVideoTimeCode * new_tc)
2643 {
2644 GstVideoTimeCode *timecode = NULL;
2645
2646 g_return_if_fail (old_tc != NULL);
2647
2648 if (*old_tc == new_tc)
2649 return;
2650
2651 if (new_tc)
2652 timecode = gst_video_time_code_copy (new_tc);
2653
2654 if (*old_tc)
2655 gst_video_time_code_free (*old_tc);
2656
2657 *old_tc = timecode;
2658 }
2659
2660 /* Called with splitmux lock held */
2661 /* Called when entering ProcessingCompleteGop state
2662 * Assess if mq contents overflowed the current file
2663 * -> If yes, need to switch to new file
2664 * -> if no, set max_out_running_time to let this GOP in and
2665 * go to COLLECTING_GOP_START state
2666 */
2667 static void
2668 handle_gathered_gop (GstSplitMuxSink * splitmux, const InputGop * gop,
2669 GstClockTimeDiff next_gop_start_time, GstClockTimeDiff max_out_running_time)
2670 {
2671 guint64 queued_bytes;
2672 GstClockTimeDiff queued_time = 0;
2673 GstClockTimeDiff queued_gop_time = 0;
2674 SplitMuxOutputCommand *cmd;
2675
2676 /* Assess if the multiqueue contents overflowed the current file */
2677 /* When considering if a newly gathered GOP overflows
2678 * the time limit for the file, only consider the running time of the
2679 * reference stream. Other streams might have run ahead a little bit,
2680 * but extra pieces won't be released to the muxer beyond the reference
2681 * stream cut-off anyway - so it forms the limit. */
2682 queued_bytes = splitmux->fragment_total_bytes + gop->total_bytes;
2683 queued_time = next_gop_start_time;
2684 /* queued_gop_time tracks how much unwritten data there is waiting to
2685 * be written to this fragment including this GOP */
2686 if (splitmux->reference_ctx->out_running_time != GST_CLOCK_STIME_NONE)
2687 queued_gop_time = queued_time - splitmux->reference_ctx->out_running_time;
2688 else
2689 queued_gop_time = queued_time - gop->start_time;
2690
2691 GST_LOG_OBJECT (splitmux, " queued_bytes %" G_GUINT64_FORMAT, queued_bytes);
2692 GST_LOG_OBJECT (splitmux, "mq at TS %" GST_STIME_FORMAT
2693 " bytes %" G_GUINT64_FORMAT " in next gop start time %" GST_STIME_FORMAT
2694 " gop start time %" GST_STIME_FORMAT,
2695 GST_STIME_ARGS (queued_time), queued_bytes,
2696 GST_STIME_ARGS (next_gop_start_time), GST_STIME_ARGS (gop->start_time));
2697
2698 if (queued_gop_time < 0) {
2699 GST_WARNING_OBJECT (splitmux,
2700 "Queued GOP time is negative %" GST_STIME_FORMAT,
2701 -GST_STIME_ARGS (queued_gop_time));
2702 queued_gop_time = 0;
2703 }
2704
2705 if (queued_time < splitmux->fragment_start_time) {
2706 GST_WARNING_OBJECT (splitmux,
2707 "Queued time is negative. Input went backwards. queued_time - %"
2708 GST_STIME_FORMAT, GST_STIME_ARGS (queued_time));
2709 queued_time = splitmux->fragment_start_time;
2710 }
2711
2712 queued_time -= splitmux->fragment_start_time;
2713 if (queued_time < queued_gop_time)
2714 queued_gop_time = queued_time;
2715
2716 /* Expand queued bytes estimate by muxer overhead */
2717 queued_bytes += (queued_bytes * splitmux->mux_overhead);
2718
2719 /* Check for overrun - have we output at least one byte and overrun
2720 * either threshold? */
2721 if (need_new_fragment (splitmux, queued_time, queued_gop_time, queued_bytes)) {
2722 g_atomic_int_set (&(splitmux->do_split_next_gop), FALSE);
2723 /* Tell the output side to start a new fragment */
2724 GST_INFO_OBJECT (splitmux,
2725 "This GOP (dur %" GST_STIME_FORMAT
2726 ") would overflow the fragment, Sending start_new_fragment cmd",
2727 GST_STIME_ARGS (queued_gop_time));
2728 cmd = out_cmd_buf_new_finish_fragment ();
2729 g_queue_push_head (&splitmux->out_cmd_q, cmd);
2730 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
2731
2732 splitmux->fragment_start_time = gop->start_time;
2733 splitmux->fragment_start_time_pts = gop->start_time_pts;
2734 splitmux->fragment_total_bytes = 0;
2735 splitmux->fragment_reference_bytes = 0;
2736
2737 video_time_code_replace (&splitmux->fragment_start_tc, gop->start_tc);
2738 splitmux->next_fragment_start_tc_time =
2739 calculate_next_max_timecode (splitmux, splitmux->fragment_start_tc,
2740 splitmux->fragment_start_time, NULL);
2741 if (splitmux->tc_interval && splitmux->fragment_start_tc
2742 && !GST_CLOCK_TIME_IS_VALID (splitmux->next_fragment_start_tc_time)) {
2743 GST_WARNING_OBJECT (splitmux,
2744 "Couldn't calculate next fragment start time for timecode mode");
2745 }
2746 }
2747
2748 /* And set up to collect the next GOP */
2749 if (max_out_running_time != G_MAXINT64) {
2750 splitmux->input_state = SPLITMUX_INPUT_STATE_COLLECTING_GOP_START;
2751 } else {
2752 /* This is probably already the current state, but just in case: */
2753 splitmux->input_state = SPLITMUX_INPUT_STATE_FINISHING_UP;
2754 }
2755
2756 /* And wake all input contexts to send a wake-up event */
2757 g_list_foreach (splitmux->contexts, (GFunc) ctx_set_unblock, NULL);
2758 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
2759
2760 /* Now either way - either there was no overflow, or we requested a new fragment: release this GOP */
2761 splitmux->fragment_total_bytes += gop->total_bytes;
2762 splitmux->fragment_reference_bytes += gop->reference_bytes;
2763
2764 if (gop->total_bytes > 0) {
2765 GST_LOG_OBJECT (splitmux,
2766 "Releasing GOP to output. Bytes in fragment now %" G_GUINT64_FORMAT
2767 " time %" GST_STIME_FORMAT,
2768 splitmux->fragment_total_bytes, GST_STIME_ARGS (queued_time));
2769
2770 /* Send this GOP to the output command queue */
2771 cmd = out_cmd_buf_new_release_gop (max_out_running_time);
2772 GST_LOG_OBJECT (splitmux, "Sending GOP cmd to output for TS %"
2773 GST_STIME_FORMAT, GST_STIME_ARGS (max_out_running_time));
2774 g_queue_push_head (&splitmux->out_cmd_q, cmd);
2775
2776 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
2777 }
2778
2779 return;
2780 }
2781
2782 /* Called with splitmux lock held */
2783 /* Called from each input pad when it is has all the pieces
2784 * for a GOP or EOS, starting with the reference pad which has set the
2785 * splitmux->max_in_running_time
2786 */
2787 static void
2788 check_completed_gop (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
2789 {
2790 GList *cur;
2791 GstEvent *event;
2792
2793 /* On ENDING_FILE, the reference stream sends a command to start a new
2794 * fragment, then releases the GOP for output in the new fragment.
2795 * If some streams received no buffer during the last GOP that overran,
2796 * because its next buffer has a timestamp bigger than
2797 * ctx->max_in_running_time, its queue is empty. In that case the only
2798 * way to wakeup the output thread is by injecting an event in the
2799 * queue. This usually happen with subtitle streams.
2800 * See https://bugzilla.gnome.org/show_bug.cgi?id=763711. */
2801 if (ctx->need_unblock) {
2802 GST_LOG_OBJECT (ctx->sinkpad, "Sending splitmuxsink-unblock event");
2803 event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM |
2804 GST_EVENT_TYPE_SERIALIZED,
2805 gst_structure_new ("splitmuxsink-unblock", "timestamp",
2806 G_TYPE_INT64, splitmux->max_in_running_time, NULL));
2807
2808 GST_SPLITMUX_UNLOCK (splitmux);
2809 gst_pad_send_event (ctx->sinkpad, event);
2810 GST_SPLITMUX_LOCK (splitmux);
2811
2812 ctx->need_unblock = FALSE;
2813 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
2814 /* state may have changed while we were unlocked. Loop again if so */
2815 if (splitmux->input_state != SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT)
2816 return;
2817 }
2818
2819 do {
2820 GstClockTimeDiff next_gop_start = GST_CLOCK_STIME_NONE;
2821
2822 if (splitmux->input_state == SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT) {
2823 GstClockTimeDiff max_out_running_time;
2824 gboolean ready = TRUE;
2825 InputGop *gop;
2826 const InputGop *next_gop;
2827
2828 gop = g_queue_peek_head (&splitmux->pending_input_gops);
2829 next_gop = g_queue_peek_nth (&splitmux->pending_input_gops, 1);
2830
2831 /* If we have no GOP or no next GOP here then the reference context is
2832 * at EOS, otherwise use the start time of the next GOP if we're far
2833 * enough in the GOP to know it */
2834 if (gop && next_gop) {
2835 if (!splitmux->reference_ctx->in_eos
2836 && splitmux->max_in_running_time_dts != GST_CLOCK_STIME_NONE
2837 && splitmux->max_in_running_time_dts < next_gop->start_time_pts) {
2838 GST_LOG_OBJECT (splitmux,
2839 "No further GOPs finished collecting, waiting until current DTS %"
2840 GST_STIME_FORMAT " has passed next GOP start PTS %"
2841 GST_STIME_FORMAT,
2842 GST_STIME_ARGS (splitmux->max_in_running_time_dts),
2843 GST_STIME_ARGS (next_gop->start_time_pts));
2844 break;
2845 }
2846
2847 GST_LOG_OBJECT (splitmux,
2848 "Finished collecting GOP with start time %" GST_STIME_FORMAT
2849 ", next GOP start time %" GST_STIME_FORMAT,
2850 GST_STIME_ARGS (gop->start_time),
2851 GST_STIME_ARGS (next_gop->start_time));
2852 next_gop_start = next_gop->start_time;
2853 max_out_running_time =
2854 splitmux->reference_ctx->in_eos ? G_MAXINT64 : next_gop->start_time;
2855 } else if (!next_gop) {
2856 GST_LOG_OBJECT (splitmux, "Reference context is EOS");
2857 next_gop_start = splitmux->max_in_running_time;
2858 max_out_running_time = G_MAXINT64;
2859 } else if (!gop) {
2860 GST_LOG_OBJECT (splitmux, "No further GOPs finished collecting");
2861 break;
2862 } else {
2863 g_assert_not_reached ();
2864 }
2865
2866 g_assert (gop != NULL);
2867
2868 /* Iterate each pad, and check that the input running time is at least
2869 * up to the start running time of the next GOP or EOS, and if so handle
2870 * the collected GOP */
2871 GST_LOG_OBJECT (splitmux, "Checking GOP collected, next GOP start %"
2872 GST_STIME_FORMAT " ctx %p", GST_STIME_ARGS (next_gop_start), ctx);
2873 for (cur = g_list_first (splitmux->contexts); cur != NULL;
2874 cur = g_list_next (cur)) {
2875 MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
2876
2877 GST_LOG_OBJECT (splitmux,
2878 "Context %p sink pad %" GST_PTR_FORMAT " @ TS %" GST_STIME_FORMAT
2879 " EOS %d", tmpctx, tmpctx->sinkpad,
2880 GST_STIME_ARGS (tmpctx->in_running_time), tmpctx->in_eos);
2881
2882 if (next_gop_start != GST_CLOCK_STIME_NONE &&
2883 tmpctx->in_running_time < next_gop_start && !tmpctx->in_eos) {
2884 GST_LOG_OBJECT (splitmux,
2885 "Context %p sink pad %" GST_PTR_FORMAT " not ready. We'll sleep",
2886 tmpctx, tmpctx->sinkpad);
2887 ready = FALSE;
2888 break;
2889 }
2890 }
2891 if (ready) {
2892 GST_DEBUG_OBJECT (splitmux,
2893 "Collected GOP is complete. Processing (ctx %p)", ctx);
2894 /* All pads have a complete GOP, release it into the multiqueue */
2895 handle_gathered_gop (splitmux, gop, next_gop_start,
2896 max_out_running_time);
2897
2898 g_queue_pop_head (&splitmux->pending_input_gops);
2899 input_gop_free (gop);
2900
2901 /* The user has requested a split, we can split now that the previous GOP
2902 * has been collected to the correct location */
2903 if (g_atomic_int_compare_and_exchange (&(splitmux->split_requested),
2904 TRUE, FALSE)) {
2905 g_atomic_int_set (&(splitmux->do_split_next_gop), TRUE);
2906 }
2907 }
2908 }
2909
2910 /* If upstream reached EOS we are not expecting more data, no need to wait
2911 * here. */
2912 if (ctx->in_eos)
2913 return;
2914
2915 if (splitmux->input_state == SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT &&
2916 !ctx->flushing &&
2917 ctx->in_running_time >= next_gop_start &&
2918 next_gop_start != GST_CLOCK_STIME_NONE) {
2919 /* Some pad is not yet ready, or GOP is being pushed
2920 * either way, sleep and wait to get woken */
2921 GST_LOG_OBJECT (splitmux, "Sleeping for GOP collection (ctx %p)", ctx);
2922 GST_SPLITMUX_WAIT_INPUT (splitmux);
2923 GST_LOG_OBJECT (splitmux, "Done waiting for complete GOP (ctx %p)", ctx);
2924 } else {
2925 /* This pad is not ready or the state changed - break out and get another
2926 * buffer / event */
2927 break;
2928 }
2929 } while (splitmux->input_state == SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT);
2930 }
2931
2932 static GstPadProbeReturn
2933 handle_mq_input (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
2934 {
2935 GstSplitMuxSink *splitmux = ctx->splitmux;
2936 GstFlowReturn ret = GST_FLOW_OK;
2937 GstBuffer *buf;
2938 MqStreamBuf *buf_info = NULL;
2939 GstClockTime ts, pts, dts;
2940 GstClockTimeDiff running_time, running_time_pts, running_time_dts;
2941 gboolean loop_again;
2942 gboolean keyframe = FALSE;
2943
2944 GST_LOG_OBJECT (pad, "Fired probe type 0x%x", info->type);
2945
2946 /* FIXME: Handle buffer lists, until then make it clear they won't work */
2947 if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
2948 g_warning ("Buffer list handling not implemented");
2949 return GST_PAD_PROBE_DROP;
2950 }
2951 if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM ||
2952 info->type & GST_PAD_PROBE_TYPE_EVENT_FLUSH) {
2953 GstEvent *event = gst_pad_probe_info_get_event (info);
2954
2955 GST_LOG_OBJECT (pad, "Event %" GST_PTR_FORMAT, event);
2956
2957 switch (GST_EVENT_TYPE (event)) {
2958 case GST_EVENT_SEGMENT:
2959 gst_event_copy_segment (event, &ctx->in_segment);
2960 break;
2961 case GST_EVENT_FLUSH_STOP:
2962 GST_SPLITMUX_LOCK (splitmux);
2963 gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
2964 ctx->in_eos = FALSE;
2965 ctx->in_running_time = GST_CLOCK_STIME_NONE;
2966 GST_SPLITMUX_UNLOCK (splitmux);
2967 break;
2968 case GST_EVENT_EOS:
2969 GST_SPLITMUX_LOCK (splitmux);
2970 ctx->in_eos = TRUE;
2971
2972 if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED) {
2973 ret = GST_FLOW_FLUSHING;
2974 goto beach;
2975 }
2976
2977 if (ctx->is_reference) {
2978 GST_INFO_OBJECT (splitmux, "Got Reference EOS. Finishing up");
2979 /* check_completed_gop will act as if this is a new keyframe with infinite timestamp */
2980 splitmux->input_state = SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT;
2981 /* Wake up other input pads to collect this GOP */
2982 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
2983 if (g_queue_is_empty (&splitmux->pending_input_gops)) {
2984 GST_WARNING_OBJECT (splitmux,
2985 "EOS with no buffers received on the reference pad");
2986
2987 /* - child muxer and sink might be still locked state
2988 * (see gst_splitmux_reset_elements()) so should be unlocked
2989 * for state change of splitmuxsink to be applied to child
2990 * - would need to post async done message
2991 * - location on sink element is still null then it will post
2992 * error message on bus (muxer will produce something, header
2993 * data for example)
2994 *
2995 * Calls start_next_fragment() here, the method will address
2996 * everything the above mentioned one */
2997 ret = start_next_fragment (splitmux, ctx);
2998 if (ret != GST_FLOW_OK)
2999 goto beach;
3000 } else {
3001 check_completed_gop (splitmux, ctx);
3002 }
3003 } else if (splitmux->input_state ==
3004 SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT) {
3005 /* If we are waiting for a GOP to be completed (ie, for aux
3006 * pads to catch up), then this pad is complete, so check
3007 * if the whole GOP is.
3008 */
3009 if (!g_queue_is_empty (&splitmux->pending_input_gops))
3010 check_completed_gop (splitmux, ctx);
3011 }
3012 GST_SPLITMUX_UNLOCK (splitmux);
3013 break;
3014 case GST_EVENT_GAP:{
3015 GstClockTime gap_ts;
3016 GstClockTimeDiff rtime;
3017
3018 gst_event_parse_gap (event, &gap_ts, NULL);
3019 if (gap_ts == GST_CLOCK_TIME_NONE)
3020 break;
3021
3022 GST_SPLITMUX_LOCK (splitmux);
3023
3024 if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED) {
3025 ret = GST_FLOW_FLUSHING;
3026 goto beach;
3027 }
3028 rtime = my_segment_to_running_time (&ctx->in_segment, gap_ts);
3029
3030 GST_LOG_OBJECT (pad, "Have GAP w/ ts %" GST_STIME_FORMAT,
3031 GST_STIME_ARGS (rtime));
3032
3033 if (ctx->is_reference && GST_CLOCK_STIME_IS_VALID (rtime)) {
3034 /* If this GAP event happens before the first fragment then
3035 * initialize the fragment start time here. */
3036 if (!GST_CLOCK_STIME_IS_VALID (splitmux->fragment_start_time)) {
3037 splitmux->fragment_start_time = rtime;
3038 GST_LOG_OBJECT (splitmux,
3039 "Fragment start time now %" GST_STIME_FORMAT,
3040 GST_STIME_ARGS (splitmux->fragment_start_time));
3041
3042 /* Also take this as the first start time when starting up,
3043 * so that we start counting overflow from the first frame */
3044 if (!GST_CLOCK_STIME_IS_VALID (splitmux->max_in_running_time))
3045 splitmux->max_in_running_time = rtime;
3046 if (!GST_CLOCK_STIME_IS_VALID (splitmux->max_in_running_time_dts))
3047 splitmux->max_in_running_time_dts = rtime;
3048 }
3049
3050 /* Similarly take it as fragment start PTS and GOP start time if
3051 * these are not set */
3052 if (!GST_CLOCK_STIME_IS_VALID (splitmux->fragment_start_time_pts))
3053 splitmux->fragment_start_time_pts = rtime;
3054
3055 if (g_queue_is_empty (&splitmux->pending_input_gops)) {
3056 InputGop *gop = g_new0 (InputGop, 1);
3057
3058 gop->from_gap = TRUE;
3059 gop->start_time = rtime;
3060 gop->start_time_pts = rtime;
3061
3062 g_queue_push_tail (&splitmux->pending_input_gops, gop);
3063 }
3064 }
3065
3066 GST_SPLITMUX_UNLOCK (splitmux);
3067 break;
3068 }
3069 default:
3070 break;
3071 }
3072 return GST_PAD_PROBE_PASS;
3073 } else if (info->type & GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM) {
3074 switch (GST_QUERY_TYPE (GST_QUERY (info->data))) {
3075 case GST_QUERY_ALLOCATION:
3076 return GST_PAD_PROBE_DROP;
3077 default:
3078 return GST_PAD_PROBE_PASS;
3079 }
3080 } else if (info->type & GST_PAD_PROBE_TYPE_QUERY_UPSTREAM) {
3081 switch (GST_QUERY_TYPE (GST_QUERY (info->data))) {
3082 case GST_QUERY_LATENCY:
3083 // Override the latency query to pretend that everything downstream
3084 // of the sink pads is actually not live. splitmuxsink doesn't know
3085 // how much latency it will possibly introduce.
3086 if (info->type & GST_PAD_PROBE_TYPE_PUSH) {
3087 GST_DEBUG_OBJECT (pad,
3088 "Overriding latency query to pretend we're not live");
3089 gst_query_set_latency (info->data, FALSE, 0, GST_CLOCK_TIME_NONE);
3090 return GST_PAD_PROBE_HANDLED;
3091 } else {
3092 // Should not happen as we already handled it above.
3093 g_warn_if_reached ();
3094 return GST_PAD_PROBE_PASS;
3095 }
3096 default:
3097 return GST_PAD_PROBE_PASS;
3098 }
3099 }
3100
3101 buf = gst_pad_probe_info_get_buffer (info);
3102 buf_info = mq_stream_buf_new ();
3103
3104 pts = GST_BUFFER_PTS (buf);
3105 dts = GST_BUFFER_DTS (buf);
3106 if (GST_BUFFER_PTS_IS_VALID (buf))
3107 ts = GST_BUFFER_PTS (buf);
3108 else
3109 ts = GST_BUFFER_DTS (buf);
3110
3111 GST_LOG_OBJECT (pad,
3112 "Buffer TS is %" GST_TIME_FORMAT " (PTS %" GST_TIME_FORMAT ", DTS %"
3113 GST_TIME_FORMAT ")", GST_TIME_ARGS (ts), GST_TIME_ARGS (pts),
3114 GST_TIME_ARGS (dts));
3115
3116 GST_SPLITMUX_LOCK (splitmux);
3117
3118 if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED) {
3119 ret = GST_FLOW_FLUSHING;
3120 goto beach;
3121 }
3122
3123 /* If this buffer has a timestamp, advance the input timestamp of the
3124 * stream */
3125 if (GST_CLOCK_TIME_IS_VALID (ts)) {
3126 running_time = my_segment_to_running_time (&ctx->in_segment, ts);
3127
3128 GST_LOG_OBJECT (pad, "Buffer running TS is %" GST_STIME_FORMAT,
3129 GST_STIME_ARGS (running_time));
3130
3131 /* in running time is always the maximum PTS (or DTS) that was observed so far */
3132 if (GST_CLOCK_STIME_IS_VALID (running_time)
3133 && running_time > ctx->in_running_time)
3134 ctx->in_running_time = running_time;
3135 } else {
3136 running_time = ctx->in_running_time;
3137 }
3138
3139 if (GST_CLOCK_TIME_IS_VALID (pts))
3140 running_time_pts = my_segment_to_running_time (&ctx->in_segment, pts);
3141 else
3142 running_time_pts = GST_CLOCK_STIME_NONE;
3143
3144 if (GST_CLOCK_TIME_IS_VALID (dts)) {
3145 running_time_dts = my_segment_to_running_time (&ctx->in_segment, dts);
3146
3147 /* DTS > PTS makes conceptually no sense so catch such invalid DTS here
3148 * by clamping to the PTS */
3149 running_time_dts = MIN (running_time_pts, running_time_dts);
3150 } else {
3151 /* If there is no DTS then assume PTS=DTS */
3152 running_time_dts = running_time_pts;
3153 }
3154
3155 /* Try to make sure we have a valid running time */
3156 if (!GST_CLOCK_STIME_IS_VALID (ctx->in_running_time)) {
3157 ctx->in_running_time =
3158 my_segment_to_running_time (&ctx->in_segment, ctx->in_segment.start);
3159 }
3160
3161 GST_LOG_OBJECT (pad, "in running time now %" GST_STIME_FORMAT,
3162 GST_STIME_ARGS (ctx->in_running_time));
3163
3164 buf_info->run_ts = ctx->in_running_time;
3165 buf_info->buf_size = gst_buffer_get_size (buf);
3166 buf_info->duration = GST_BUFFER_DURATION (buf);
3167
3168 if (ctx->is_reference) {
3169 InputGop *gop = NULL;
3170 GstVideoTimeCodeMeta *tc_meta = gst_buffer_get_video_time_code_meta (buf);
3171
3172 /* initialize fragment_start_time if it was not set yet (i.e. for the
3173 * first fragment), or otherwise set it to the minimum observed time */
3174 if (!GST_CLOCK_STIME_IS_VALID (splitmux->fragment_start_time)
3175 || splitmux->fragment_start_time > running_time) {
3176 if (!GST_CLOCK_STIME_IS_VALID (splitmux->fragment_start_time))
3177 splitmux->fragment_start_time_pts = running_time_pts;
3178 splitmux->fragment_start_time = running_time;
3179
3180 GST_LOG_OBJECT (splitmux,
3181 "Fragment start time now %" GST_STIME_FORMAT " (initial PTS %"
3182 GST_STIME_FORMAT ")", GST_STIME_ARGS (splitmux->fragment_start_time),
3183 GST_STIME_ARGS (splitmux->fragment_start_time_pts));
3184
3185 /* Also take this as the first start time when starting up,
3186 * so that we start counting overflow from the first frame */
3187 if (!GST_CLOCK_STIME_IS_VALID (splitmux->max_in_running_time)
3188 || splitmux->max_in_running_time < splitmux->fragment_start_time)
3189 splitmux->max_in_running_time = splitmux->fragment_start_time;
3190
3191 if (!GST_CLOCK_STIME_IS_VALID (splitmux->max_in_running_time_dts))
3192 splitmux->max_in_running_time_dts = running_time_dts;
3193
3194 if (tc_meta) {
3195 video_time_code_replace (&splitmux->fragment_start_tc, &tc_meta->tc);
3196
3197 splitmux->next_fragment_start_tc_time =
3198 calculate_next_max_timecode (splitmux, &tc_meta->tc,
3199 running_time, NULL);
3200 if (splitmux->tc_interval
3201 && !GST_CLOCK_TIME_IS_VALID (splitmux->next_fragment_start_tc_time))
3202 {
3203 GST_WARNING_OBJECT (splitmux,
3204 "Couldn't calculate next fragment start time for timecode mode");
3205 }
3206 #ifndef GST_DISABLE_GST_DEBUG
3207 {
3208 gchar *tc_str;
3209
3210 tc_str = gst_video_time_code_to_string (&tc_meta->tc);
3211 GST_DEBUG_OBJECT (splitmux,
3212 "Initialize fragment start timecode %s, next fragment start timecode time %"
3213 GST_TIME_FORMAT, tc_str,
3214 GST_TIME_ARGS (splitmux->next_fragment_start_tc_time));
3215 g_free (tc_str);
3216 }
3217 #endif
3218 }
3219 }
3220
3221
3222 /* First check if we're at the very first GOP and the tracking was created
3223 * from a GAP event. In that case don't start a new GOP on keyframes but
3224 * just updated it as needed */
3225 gop = g_queue_peek_tail (&splitmux->pending_input_gops);
3226
3227 if (!gop || (!gop->from_gap
3228 && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT))) {
3229 gop = g_new0 (InputGop, 1);
3230
3231 gop->start_time = running_time;
3232 gop->start_time_pts = running_time_pts;
3233
3234 GST_LOG_OBJECT (splitmux,
3235 "Next GOP start time now %" GST_STIME_FORMAT " (initial PTS %"
3236 GST_STIME_FORMAT ")", GST_STIME_ARGS (gop->start_time),
3237 GST_STIME_ARGS (gop->start_time_pts));
3238
3239 if (tc_meta) {
3240 video_time_code_replace (&gop->start_tc, &tc_meta->tc);
3241
3242 #ifndef GST_DISABLE_GST_DEBUG
3243 {
3244 gchar *tc_str;
3245
3246 tc_str = gst_video_time_code_to_string (&tc_meta->tc);
3247 GST_DEBUG_OBJECT (splitmux, "Next GOP start timecode %s", tc_str);
3248 g_free (tc_str);
3249 }
3250 #endif
3251 }
3252
3253 g_queue_push_tail (&splitmux->pending_input_gops, gop);
3254 } else {
3255 gop->from_gap = FALSE;
3256
3257 if (!GST_CLOCK_STIME_IS_VALID (gop->start_time)
3258 || gop->start_time > running_time) {
3259 gop->start_time = running_time;
3260
3261 GST_LOG_OBJECT (splitmux,
3262 "GOP start time updated now %" GST_STIME_FORMAT " (initial PTS %"
3263 GST_STIME_FORMAT ")", GST_STIME_ARGS (gop->start_time),
3264 GST_STIME_ARGS (gop->start_time_pts));
3265
3266 if (tc_meta) {
3267 video_time_code_replace (&gop->start_tc, &tc_meta->tc);
3268
3269 #ifndef GST_DISABLE_GST_DEBUG
3270 {
3271 gchar *tc_str;
3272
3273 tc_str = gst_video_time_code_to_string (&tc_meta->tc);
3274 GST_DEBUG_OBJECT (splitmux, "Next GOP start timecode updated %s",
3275 tc_str);
3276 g_free (tc_str);
3277 }
3278 #endif
3279 }
3280 }
3281 }
3282
3283 /* Check whether we need to request next keyframe depending on
3284 * current running time */
3285 if (request_next_keyframe (splitmux, buf, running_time_dts) == FALSE) {
3286 GST_WARNING_OBJECT (splitmux,
3287 "Could not request a keyframe. Files may not split at the exact location they should");
3288 }
3289 }
3290
3291 {
3292 InputGop *gop = g_queue_peek_tail (&splitmux->pending_input_gops);
3293
3294 if (gop) {
3295 GST_DEBUG_OBJECT (pad, "Buf TS %" GST_STIME_FORMAT
3296 " total GOP bytes %" G_GUINT64_FORMAT ", total next GOP bytes %"
3297 G_GUINT64_FORMAT, GST_STIME_ARGS (buf_info->run_ts),
3298 gop->total_bytes, gop->total_bytes);
3299 }
3300 }
3301
3302 loop_again = TRUE;
3303 do {
3304 if (ctx->flushing) {
3305 ret = GST_FLOW_FLUSHING;
3306 goto beach;
3307 }
3308
3309 switch (splitmux->input_state) {
3310 case SPLITMUX_INPUT_STATE_COLLECTING_GOP_START:
3311 if (ctx->is_reference) {
3312 const InputGop *gop GST_UNUSED_ASSERT, *next_gop;
3313
3314 /* This is the reference context. If it's a keyframe,
3315 * it marks the start of a new GOP and we should wait in
3316 * check_completed_gop before continuing, but either way
3317 * (keyframe or no, we'll pass this buffer through after
3318 * so set loop_again to FALSE */
3319 loop_again = FALSE;
3320
3321 #ifndef G_DISABLE_ASSERT
3322 gop = g_queue_peek_head (&splitmux->pending_input_gops);
3323 g_assert (gop != NULL);
3324 #endif
3325 next_gop = g_queue_peek_nth (&splitmux->pending_input_gops, 1);
3326
3327 if (ctx->in_running_time > splitmux->max_in_running_time)
3328 splitmux->max_in_running_time = ctx->in_running_time;
3329 if (running_time_dts > splitmux->max_in_running_time_dts)
3330 splitmux->max_in_running_time_dts = running_time_dts;
3331
3332 GST_LOG_OBJECT (splitmux,
3333 "Max in running time now %" GST_STIME_FORMAT ", DTS %"
3334 GST_STIME_FORMAT, GST_STIME_ARGS (splitmux->max_in_running_time),
3335 GST_STIME_ARGS (splitmux->max_in_running_time_dts));
3336
3337 if (!next_gop) {
3338 GST_DEBUG_OBJECT (pad, "Waiting for end of GOP");
3339 /* Allow other input pads to catch up to here too */
3340 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
3341 break;
3342 }
3343
3344 if (!GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
3345 GST_INFO_OBJECT (pad,
3346 "Have keyframe with running time %" GST_STIME_FORMAT,
3347 GST_STIME_ARGS (ctx->in_running_time));
3348 keyframe = TRUE;
3349 }
3350
3351 if (running_time_dts != GST_CLOCK_STIME_NONE
3352 && running_time_dts < next_gop->start_time_pts) {
3353 GST_DEBUG_OBJECT (splitmux,
3354 "Waiting until DTS (%" GST_STIME_FORMAT
3355 ") has passed next GOP start PTS (%" GST_STIME_FORMAT ")",
3356 GST_STIME_ARGS (running_time_dts),
3357 GST_STIME_ARGS (next_gop->start_time_pts));
3358 /* Allow other input pads to catch up to here too */
3359 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
3360 break;
3361 }
3362
3363 splitmux->input_state = SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT;
3364 /* Wake up other input pads to collect this GOP */
3365 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
3366 check_completed_gop (splitmux, ctx);
3367 } else {
3368 /* Pass this buffer if the reference ctx is far enough ahead */
3369 if (ctx->in_running_time < splitmux->max_in_running_time) {
3370 loop_again = FALSE;
3371 break;
3372 }
3373
3374 /* We're still waiting for a keyframe on the reference pad, sleep */
3375 GST_LOG_OBJECT (pad, "Sleeping for GOP start");
3376 GST_SPLITMUX_WAIT_INPUT (splitmux);
3377 GST_LOG_OBJECT (pad,
3378 "Done sleeping for GOP start input state now %d",
3379 splitmux->input_state);
3380 }
3381 break;
3382 case SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT:{
3383 /* We're collecting a GOP, this is only ever called for non-reference
3384 * contexts as the reference context would be waiting inside
3385 * check_completed_gop() */
3386
3387 g_assert (!ctx->is_reference);
3388
3389 /* If we overran the target timestamp, it might be time to process
3390 * the GOP, otherwise bail out for more data. */
3391 GST_LOG_OBJECT (pad,
3392 "Checking TS %" GST_STIME_FORMAT " against max %"
3393 GST_STIME_FORMAT, GST_STIME_ARGS (ctx->in_running_time),
3394 GST_STIME_ARGS (splitmux->max_in_running_time));
3395
3396 if (ctx->in_running_time < splitmux->max_in_running_time) {
3397 loop_again = FALSE;
3398 break;
3399 }
3400
3401 GST_LOG_OBJECT (pad,
3402 "Collected last packet of GOP. Checking other pads");
3403
3404 if (g_queue_is_empty (&splitmux->pending_input_gops)) {
3405 GST_WARNING_OBJECT (pad,
3406 "Reference was closed without GOP, dropping");
3407 goto drop;
3408 }
3409
3410 check_completed_gop (splitmux, ctx);
3411 break;
3412 }
3413 case SPLITMUX_INPUT_STATE_FINISHING_UP:
3414 loop_again = FALSE;
3415 break;
3416 default:
3417 loop_again = FALSE;
3418 break;
3419 }
3420 }
3421 while (loop_again);
3422
3423 if (keyframe && ctx->is_reference)
3424 splitmux->queued_keyframes++;
3425 buf_info->keyframe = keyframe;
3426
3427 /* Update total input byte counter for overflow detect unless we're after
3428 * EOS now */
3429 if (splitmux->input_state != SPLITMUX_INPUT_STATE_FINISHING_UP
3430 && splitmux->input_state != SPLITMUX_INPUT_STATE_STOPPED) {
3431 InputGop *gop = g_queue_peek_tail (&splitmux->pending_input_gops);
3432
3433 /* We must have a GOP at this point */
3434 g_assert (gop != NULL);
3435
3436 gop->total_bytes += buf_info->buf_size;
3437 if (ctx->is_reference) {
3438 gop->reference_bytes += buf_info->buf_size;
3439 }
3440 }
3441
3442 /* Now add this buffer to the queue just before returning */
3443 g_queue_push_head (&ctx->queued_bufs, buf_info);
3444
3445 GST_LOG_OBJECT (pad, "Returning to queue buffer %" GST_PTR_FORMAT
3446 " run ts %" GST_STIME_FORMAT, buf, GST_STIME_ARGS (ctx->in_running_time));
3447
3448 GST_SPLITMUX_UNLOCK (splitmux);
3449 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
3450 return GST_PAD_PROBE_PASS;
3451
3452 beach:
3453 GST_SPLITMUX_UNLOCK (splitmux);
3454 if (buf_info)
3455 mq_stream_buf_free (buf_info);
3456 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = ret;
3457 return GST_PAD_PROBE_PASS;
3458 drop:
3459 GST_SPLITMUX_UNLOCK (splitmux);
3460 if (buf_info)
3461 mq_stream_buf_free (buf_info);
3462 GST_PAD_PROBE_INFO_FLOW_RETURN (info) = GST_FLOW_EOS;
3463 return GST_PAD_PROBE_DROP;
3464 }
3465
3466 static void
3467 grow_blocked_queues (GstSplitMuxSink * splitmux)
3468 {
3469 GList *cur;
3470
3471 /* Scan other queues for full-ness and grow them */
3472 for (cur = g_list_first (splitmux->contexts);
3473 cur != NULL; cur = g_list_next (cur)) {
3474 MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
3475 guint cur_limit;
3476 guint cur_len = g_queue_get_length (&tmpctx->queued_bufs);
3477
3478 g_object_get (tmpctx->q, "max-size-buffers", &cur_limit, NULL);
3479 GST_LOG_OBJECT (tmpctx->q, "Queue len %u", cur_len);
3480
3481 if (cur_len >= cur_limit) {
3482 cur_limit = cur_len + 1;
3483 GST_DEBUG_OBJECT (tmpctx->q,
3484 "Queue overflowed and needs enlarging. Growing to %u buffers",
3485 cur_limit);
3486 g_object_set (tmpctx->q, "max-size-buffers", cur_limit, NULL);
3487 }
3488 }
3489 }
3490
3491 static void
3492 handle_q_underrun (GstElement * q, gpointer user_data)
3493 {
3494 MqStreamCtx *ctx = (MqStreamCtx *) (user_data);
3495 GstSplitMuxSink *splitmux = ctx->splitmux;
3496
3497 GST_SPLITMUX_LOCK (splitmux);
3498 GST_DEBUG_OBJECT (q,
3499 "Queue reported underrun with %d keyframes and %d cmds enqueued",
3500 splitmux->queued_keyframes, g_queue_get_length (&splitmux->out_cmd_q));
3501 grow_blocked_queues (splitmux);
3502 GST_SPLITMUX_UNLOCK (splitmux);
3503 }
3504
3505 static void
3506 handle_q_overrun (GstElement * q, gpointer user_data)
3507 {
3508 MqStreamCtx *ctx = (MqStreamCtx *) (user_data);
3509 GstSplitMuxSink *splitmux = ctx->splitmux;
3510 gboolean allow_grow = FALSE;
3511
3512 GST_SPLITMUX_LOCK (splitmux);
3513 GST_DEBUG_OBJECT (q,
3514 "Queue reported overrun with %d keyframes and %d cmds enqueued",
3515 splitmux->queued_keyframes, g_queue_get_length (&splitmux->out_cmd_q));
3516
3517 if (splitmux->queued_keyframes < 2) {
3518 /* Less than a full GOP queued, grow the queue */
3519 allow_grow = TRUE;
3520 } else if (g_queue_get_length (&splitmux->out_cmd_q) < 1) {
3521 allow_grow = TRUE;
3522 } else {
3523 /* If another queue is starved, grow */
3524 GList *cur;
3525 for (cur = g_list_first (splitmux->contexts);
3526 cur != NULL; cur = g_list_next (cur)) {
3527 MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);
3528 if (tmpctx != ctx && g_queue_get_length (&tmpctx->queued_bufs) < 1) {
3529 allow_grow = TRUE;
3530 }
3531 }
3532 }
3533 GST_SPLITMUX_UNLOCK (splitmux);
3534
3535 if (allow_grow) {
3536 guint cur_limit;
3537
3538 g_object_get (q, "max-size-buffers", &cur_limit, NULL);
3539 cur_limit++;
3540
3541 GST_DEBUG_OBJECT (q,
3542 "Queue overflowed and needs enlarging. Growing to %u buffers",
3543 cur_limit);
3544
3545 g_object_set (q, "max-size-buffers", cur_limit, NULL);
3546 }
3547 }
3548
3549 /* Called with SPLITMUX lock held */
3550 static const gchar *
3551 lookup_muxer_pad (GstSplitMuxSink * splitmux, const gchar * sinkpad_name)
3552 {
3553 const gchar *ret = NULL;
3554
3555 if (splitmux->muxerpad_map == NULL)
3556 return NULL;
3557
3558 if (sinkpad_name == NULL) {
3559 GST_WARNING_OBJECT (splitmux,
3560 "Can't look up request pad in pad map without providing a pad name");
3561 return NULL;
3562 }
3563
3564 ret = gst_structure_get_string (splitmux->muxerpad_map, sinkpad_name);
3565 if (ret) {
3566 GST_INFO_OBJECT (splitmux, "Sink pad %s maps to muxer pad %s", sinkpad_name,
3567 ret);
3568 return g_strdup (ret);
3569 }
3570
3571 return NULL;
3572 }
3573
3574 static GstPad *
3575 gst_splitmux_sink_request_new_pad (GstElement * element,
3576 GstPadTemplate * templ, const gchar * name, const GstCaps * caps)
3577 {
3578 GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
3579 GstPadTemplate *mux_template = NULL;
3580 GstPad *ret = NULL, *muxpad = NULL;
3581 GstElement *q;
3582 GstPad *q_sink = NULL, *q_src = NULL;
3583 gchar *gname, *qname;
3584 gboolean is_primary_video = FALSE, is_video = FALSE,
3585 muxer_is_requestpad = FALSE;
3586 MqStreamCtx *ctx;
3587 const gchar *muxer_padname = NULL;
3588
3589 GST_DEBUG_OBJECT (splitmux, "templ:%s, name:%s", templ->name_template, name);
3590
3591 GST_SPLITMUX_LOCK (splitmux);
3592 if (!create_muxer (splitmux))
3593 goto fail;
3594 g_signal_emit (splitmux, signals[SIGNAL_MUXER_ADDED], 0, splitmux->muxer);
3595
3596 if (g_str_equal (templ->name_template, "video") ||
3597 g_str_has_prefix (templ->name_template, "video_aux_")) {
3598 is_primary_video = g_str_equal (templ->name_template, "video");
3599 if (is_primary_video && splitmux->have_video)
3600 goto already_have_video;
3601 is_video = TRUE;
3602 }
3603
3604 /* See if there's a pad map and it lists this pad */
3605 muxer_padname = lookup_muxer_pad (splitmux, name);
3606
3607 if (muxer_padname == NULL) {
3608 if (is_video) {
3609 /* FIXME: Look for a pad template with matching caps, rather than by name */
3610 GST_DEBUG_OBJECT (element,
3611 "searching for pad-template with name 'video_%%u'");
3612 mux_template =
3613 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3614 (splitmux->muxer), "video_%u");
3615
3616 /* Fallback to find sink pad templates named 'video' (flvmux) */
3617 if (!mux_template) {
3618 GST_DEBUG_OBJECT (element,
3619 "searching for pad-template with name 'video'");
3620 mux_template =
3621 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3622 (splitmux->muxer), "video");
3623 }
3624 name = NULL;
3625 } else {
3626 GST_DEBUG_OBJECT (element, "searching for pad-template with name '%s'",
3627 templ->name_template);
3628 mux_template =
3629 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3630 (splitmux->muxer), templ->name_template);
3631
3632 /* Fallback to find sink pad templates named 'audio' (flvmux) */
3633 if (!mux_template && g_str_has_prefix (templ->name_template, "audio_")) {
3634 GST_DEBUG_OBJECT (element,
3635 "searching for pad-template with name 'audio'");
3636 mux_template =
3637 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3638 (splitmux->muxer), "audio");
3639 name = NULL;
3640 }
3641 }
3642
3643 if (mux_template == NULL) {
3644 GST_DEBUG_OBJECT (element,
3645 "searching for pad-template with name 'sink_%%d'");
3646 mux_template =
3647 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3648 (splitmux->muxer), "sink_%d");
3649 name = NULL;
3650 }
3651 if (mux_template == NULL) {
3652 GST_DEBUG_OBJECT (element,
3653 "searching for pad-template with name 'sink_%%u'");
3654 mux_template =
3655 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3656 (splitmux->muxer), "sink_%u");
3657 name = NULL;
3658 }
3659 if (mux_template == NULL) {
3660 GST_DEBUG_OBJECT (element, "searching for pad-template with name 'sink'");
3661 mux_template =
3662 gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS
3663 (splitmux->muxer), "sink");
3664 name = NULL;
3665 }
3666
3667 if (mux_template == NULL) {
3668 GST_ERROR_OBJECT (element,
3669 "unable to find a suitable sink pad-template on the muxer");
3670 goto fail;
3671 }
3672 GST_DEBUG_OBJECT (element, "found sink pad-template '%s' on the muxer",
3673 mux_template->name_template);
3674
3675 if (mux_template->presence == GST_PAD_REQUEST) {
3676 GST_DEBUG_OBJECT (element, "requesting pad from pad-template");
3677
3678 muxpad =
3679 gst_element_request_pad (splitmux->muxer, mux_template, name, caps);
3680 muxer_is_requestpad = TRUE;
3681 } else if (mux_template->presence == GST_PAD_ALWAYS) {
3682 GST_DEBUG_OBJECT (element, "accessing always pad from pad-template");
3683
3684 muxpad =
3685 gst_element_get_static_pad (splitmux->muxer,
3686 mux_template->name_template);
3687 } else {
3688 GST_ERROR_OBJECT (element,
3689 "unexpected pad presence %d", mux_template->presence);
3690 goto fail;
3691 }
3692 } else {
3693 /* Have a muxer pad name */
3694 if (!(muxpad = gst_element_get_static_pad (splitmux->muxer, muxer_padname))) {
3695 if ((muxpad =
3696 gst_element_request_pad_simple (splitmux->muxer, muxer_padname)))
3697 muxer_is_requestpad = TRUE;
3698 }
3699 g_free ((gchar *) muxer_padname);
3700 muxer_padname = NULL;
3701 }
3702
3703 /* One way or another, we must have a muxer pad by now */
3704 if (muxpad == NULL)
3705 goto fail;
3706
3707 if (is_primary_video)
3708 gname = g_strdup ("video");
3709 else if (name == NULL)
3710 gname = gst_pad_get_name (muxpad);
3711 else
3712 gname = g_strdup (name);
3713
3714 qname = g_strdup_printf ("queue_%s", gname);
3715 if ((q = create_element (splitmux, "queue", qname, FALSE)) == NULL) {
3716 g_free (qname);
3717 goto fail;
3718 }
3719 g_free (qname);
3720
3721 gst_element_set_state (q, GST_STATE_TARGET (splitmux));
3722
3723 g_object_set (q, "max-size-bytes", 0, "max-size-time", (guint64) (0),
3724 "max-size-buffers", 5, NULL);
3725
3726 q_sink = gst_element_get_static_pad (q, "sink");
3727 q_src = gst_element_get_static_pad (q, "src");
3728
3729 if (gst_pad_link (q_src, muxpad) != GST_PAD_LINK_OK) {
3730 if (muxer_is_requestpad)
3731 gst_element_release_request_pad (splitmux->muxer, muxpad);
3732 gst_object_unref (GST_OBJECT (muxpad));
3733 goto fail;
3734 }
3735
3736 gst_object_unref (GST_OBJECT (muxpad));
3737
3738 ctx = mq_stream_ctx_new (splitmux);
3739 /* Context holds a ref: */
3740 ctx->q = gst_object_ref (q);
3741 ctx->srcpad = q_src;
3742 ctx->sinkpad = q_sink;
3743 ctx->q_overrun_id =
3744 g_signal_connect (q, "overrun", (GCallback) handle_q_overrun, ctx);
3745 g_signal_connect (q, "underrun", (GCallback) handle_q_underrun, ctx);
3746
3747 ctx->src_pad_block_id =
3748 gst_pad_add_probe (q_src,
3749 GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM | GST_PAD_PROBE_TYPE_EVENT_FLUSH,
3750 (GstPadProbeCallback) handle_mq_output, ctx, NULL);
3751 if (is_primary_video && splitmux->reference_ctx != NULL) {
3752 splitmux->reference_ctx->is_reference = FALSE;
3753 splitmux->reference_ctx = NULL;
3754 }
3755 if (splitmux->reference_ctx == NULL) {
3756 splitmux->reference_ctx = ctx;
3757 ctx->is_reference = TRUE;
3758 }
3759
3760 ret = gst_ghost_pad_new_from_template (gname, q_sink, templ);
3761 g_object_set_qdata ((GObject *) (ret), PAD_CONTEXT, ctx);
3762
3763 ctx->sink_pad_block_id =
3764 gst_pad_add_probe (q_sink,
3765 GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM | GST_PAD_PROBE_TYPE_EVENT_FLUSH |
3766 GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM | GST_PAD_PROBE_TYPE_QUERY_UPSTREAM,
3767 (GstPadProbeCallback) handle_mq_input, ctx, NULL);
3768
3769 GST_DEBUG_OBJECT (splitmux, "splitmuxsink pad %" GST_PTR_FORMAT
3770 " feeds queue pad %" GST_PTR_FORMAT, ret, q_sink);
3771
3772 ctx->ctx_id = g_list_length (splitmux->contexts);
3773 splitmux->contexts = g_list_append (splitmux->contexts, ctx);
3774
3775 g_free (gname);
3776
3777 if (is_primary_video)
3778 splitmux->have_video = TRUE;
3779
3780 gst_pad_set_active (ret, TRUE);
3781 gst_element_add_pad (GST_ELEMENT (splitmux), ret);
3782
3783 GST_SPLITMUX_UNLOCK (splitmux);
3784
3785 return ret;
3786 fail:
3787 GST_SPLITMUX_UNLOCK (splitmux);
3788
3789 if (q_sink)
3790 gst_object_unref (q_sink);
3791 if (q_src)
3792 gst_object_unref (q_src);
3793 return NULL;
3794 already_have_video:
3795 GST_DEBUG_OBJECT (splitmux, "video sink pad already requested");
3796 GST_SPLITMUX_UNLOCK (splitmux);
3797 return NULL;
3798 }
3799
3800 static void
3801 gst_splitmux_sink_release_pad (GstElement * element, GstPad * pad)
3802 {
3803 GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
3804 GstPad *muxpad = NULL;
3805 MqStreamCtx *ctx =
3806 (MqStreamCtx *) (g_object_get_qdata ((GObject *) (pad), PAD_CONTEXT));
3807
3808 GST_SPLITMUX_LOCK (splitmux);
3809
3810 if (splitmux->muxer == NULL)
3811 goto fail; /* Elements don't exist yet - nothing to release */
3812
3813 GST_INFO_OBJECT (pad, "releasing request pad");
3814
3815 muxpad = gst_pad_get_peer (ctx->srcpad);
3816
3817 /* Remove the context from our consideration */
3818 splitmux->contexts = g_list_remove (splitmux->contexts, ctx);
3819
3820 ctx->flushing = TRUE;
3821 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
3822
3823 GST_SPLITMUX_UNLOCK (splitmux);
3824
3825 if (ctx->sink_pad_block_id) {
3826 gst_pad_remove_probe (ctx->sinkpad, ctx->sink_pad_block_id);
3827 gst_pad_send_event (ctx->sinkpad, gst_event_new_flush_start ());
3828 }
3829
3830 if (ctx->src_pad_block_id)
3831 gst_pad_remove_probe (ctx->srcpad, ctx->src_pad_block_id);
3832
3833 /* Wait for the pad to be free */
3834 GST_PAD_STREAM_LOCK (pad);
3835 GST_SPLITMUX_LOCK (splitmux);
3836 GST_PAD_STREAM_UNLOCK (pad);
3837
3838 /* Can release the context now */
3839 mq_stream_ctx_free (ctx);
3840 if (ctx == splitmux->reference_ctx)
3841 splitmux->reference_ctx = NULL;
3842
3843 /* Release and free the muxer input */
3844 if (muxpad) {
3845 gst_element_release_request_pad (splitmux->muxer, muxpad);
3846 gst_object_unref (muxpad);
3847 }
3848
3849 if (GST_PAD_PAD_TEMPLATE (pad) &&
3850 g_str_equal (GST_PAD_TEMPLATE_NAME_TEMPLATE (GST_PAD_PAD_TEMPLATE
3851 (pad)), "video"))
3852 splitmux->have_video = FALSE;
3853
3854 gst_element_remove_pad (element, pad);
3855
3856 /* Reset the internal elements only after all request pads are released */
3857 if (splitmux->contexts == NULL)
3858 gst_splitmux_reset_elements (splitmux);
3859
3860 /* Wake up other input streams to check if the completion conditions have
3861 * changed */
3862 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
3863
3864 fail:
3865 GST_SPLITMUX_UNLOCK (splitmux);
3866 }
3867
3868 static GstElement *
3869 create_element (GstSplitMuxSink * splitmux,
3870 const gchar * factory, const gchar * name, gboolean locked)
3871 {
3872 GstElement *ret = gst_element_factory_make (factory, name);
3873 if (ret == NULL) {
3874 g_warning ("Failed to create %s - splitmuxsink will not work", name);
3875 return NULL;
3876 }
3877
3878 if (locked) {
3879 /* Ensure the sink starts in locked state and NULL - it will be changed
3880 * by the filename setting code */
3881 gst_element_set_locked_state (ret, TRUE);
3882 gst_element_set_state (ret, GST_STATE_NULL);
3883 }
3884
3885 if (!gst_bin_add (GST_BIN (splitmux), ret)) {
3886 g_warning ("Could not add %s element - splitmuxsink will not work", name);
3887 gst_object_unref (ret);
3888 return NULL;
3889 }
3890
3891 return ret;
3892 }
3893
3894 static gboolean
3895 create_muxer (GstSplitMuxSink * splitmux)
3896 {
3897 /* Create internal elements */
3898 if (splitmux->muxer == NULL) {
3899 GstElement *provided_muxer = NULL;
3900
3901 GST_OBJECT_LOCK (splitmux);
3902 if (splitmux->provided_muxer != NULL)
3903 provided_muxer = gst_object_ref (splitmux->provided_muxer);
3904 GST_OBJECT_UNLOCK (splitmux);
3905
3906 if ((!splitmux->async_finalize && provided_muxer == NULL) ||
3907 (splitmux->async_finalize && splitmux->muxer_factory == NULL)) {
3908 if ((splitmux->muxer =
3909 create_element (splitmux,
3910 splitmux->muxer_factory ? splitmux->
3911 muxer_factory : DEFAULT_MUXER, "muxer", FALSE)) == NULL)
3912 goto fail;
3913 } else if (splitmux->async_finalize) {
3914 if ((splitmux->muxer =
3915 create_element (splitmux, splitmux->muxer_factory, "muxer",
3916 FALSE)) == NULL)
3917 goto fail;
3918 if (splitmux->muxer_preset && GST_IS_PRESET (splitmux->muxer))
3919 gst_preset_load_preset (GST_PRESET (splitmux->muxer),
3920 splitmux->muxer_preset);
3921 if (splitmux->muxer_properties)
3922 gst_structure_foreach_id_str (splitmux->muxer_properties,
3923 _set_property_from_structure, splitmux->muxer);
3924 } else {
3925 /* Ensure it's not in locked state (we might be reusing an old element) */
3926 gst_element_set_locked_state (provided_muxer, FALSE);
3927 if (!gst_bin_add (GST_BIN (splitmux), provided_muxer)) {
3928 g_warning ("Could not add muxer element - splitmuxsink will not work");
3929 gst_object_unref (provided_muxer);
3930 goto fail;
3931 }
3932
3933 splitmux->muxer = provided_muxer;
3934 gst_object_unref (provided_muxer);
3935 }
3936
3937 if (splitmux->use_robust_muxing) {
3938 update_muxer_properties (splitmux);
3939 }
3940 }
3941
3942 return TRUE;
3943 fail:
3944 return FALSE;
3945 }
3946
3947 static GstElement *
3948 find_sink (GstElement * e)
3949 {
3950 GstElement *res = NULL;
3951 GstIterator *iter;
3952 gboolean done = FALSE;
3953 GValue data = { 0, };
3954
3955 if (!GST_IS_BIN (e))
3956 return e;
3957
3958 if (g_object_class_find_property (G_OBJECT_GET_CLASS (e), "location") != NULL)
3959 return e;
3960
3961 iter = gst_bin_iterate_sinks (GST_BIN (e));
3962 while (!done) {
3963 switch (gst_iterator_next (iter, &data)) {
3964 case GST_ITERATOR_OK:
3965 {
3966 GstElement *child = g_value_get_object (&data);
3967 if (g_object_class_find_property (G_OBJECT_GET_CLASS (child),
3968 "location") != NULL) {
3969 res = child;
3970 done = TRUE;
3971 }
3972 g_value_reset (&data);
3973 break;
3974 }
3975 case GST_ITERATOR_RESYNC:
3976 gst_iterator_resync (iter);
3977 break;
3978 case GST_ITERATOR_DONE:
3979 done = TRUE;
3980 break;
3981 case GST_ITERATOR_ERROR:
3982 g_assert_not_reached ();
3983 break;
3984 }
3985 }
3986 g_value_unset (&data);
3987 gst_iterator_free (iter);
3988
3989 return res;
3990 }
3991
3992 static gboolean
3993 create_sink (GstSplitMuxSink * splitmux)
3994 {
3995 GstElement *provided_sink = NULL;
3996
3997 if (splitmux->active_sink == NULL) {
3998
3999 GST_OBJECT_LOCK (splitmux);
4000 if (splitmux->provided_sink != NULL)
4001 provided_sink = gst_object_ref (splitmux->provided_sink);
4002 GST_OBJECT_UNLOCK (splitmux);
4003
4004 if ((!splitmux->async_finalize && provided_sink == NULL) ||
4005 (splitmux->async_finalize && splitmux->sink_factory == NULL)) {
4006 if ((splitmux->sink =
4007 create_element (splitmux, DEFAULT_SINK, "sink", TRUE)) == NULL)
4008 goto fail;
4009 splitmux->active_sink = splitmux->sink;
4010 } else if (splitmux->async_finalize) {
4011 if ((splitmux->sink =
4012 create_element (splitmux, splitmux->sink_factory, "sink",
4013 TRUE)) == NULL)
4014 goto fail;
4015 if (splitmux->sink_preset && GST_IS_PRESET (splitmux->sink))
4016 gst_preset_load_preset (GST_PRESET (splitmux->sink),
4017 splitmux->sink_preset);
4018 if (splitmux->sink_properties)
4019 gst_structure_foreach_id_str (splitmux->sink_properties,
4020 _set_property_from_structure, splitmux->sink);
4021 splitmux->active_sink = splitmux->sink;
4022 } else {
4023 /* Ensure the sink starts in locked state and NULL - it will be changed
4024 * by the filename setting code */
4025 gst_element_set_locked_state (provided_sink, TRUE);
4026 gst_element_set_state (provided_sink, GST_STATE_NULL);
4027 if (!gst_bin_add (GST_BIN (splitmux), provided_sink)) {
4028 g_warning ("Could not add sink elements - splitmuxsink will not work");
4029 gst_object_unref (provided_sink);
4030 goto fail;
4031 }
4032
4033 splitmux->active_sink = provided_sink;
4034
4035 /* The bin holds a ref now, we can drop our tmp ref */
4036 gst_object_unref (provided_sink);
4037
4038 /* Find the sink element */
4039 splitmux->sink = find_sink (splitmux->active_sink);
4040 if (splitmux->sink == NULL) {
4041 g_warning
4042 ("Could not locate sink element in provided sink - splitmuxsink will not work");
4043 goto fail;
4044 }
4045 }
4046
4047 #if 1
4048 if (g_object_class_find_property (G_OBJECT_GET_CLASS (splitmux->sink),
4049 "async") != NULL) {
4050 /* async child elements are causing state change races and weird
4051 * failures, so let's try and turn that off */
4052 g_object_set (splitmux->sink, "async", FALSE, NULL);
4053 }
4054 #endif
4055
4056 if (!gst_element_link (splitmux->muxer, splitmux->active_sink)) {
4057 g_warning ("Failed to link muxer and sink- splitmuxsink will not work");
4058 goto fail;
4059 }
4060 }
4061
4062 return TRUE;
4063 fail:
4064 return FALSE;
4065 }
4066
4067 #ifdef __GNUC__
4068 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
4069 #endif
4070 static gboolean
4071 set_next_filename (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
4072 {
4073 gchar *fname = NULL;
4074 GstSample *sample;
4075 GstCaps *caps;
4076 gboolean res = TRUE;
4077
4078 gst_splitmux_sink_ensure_max_files (splitmux);
4079
4080 if (ctx->cur_out_buffer == NULL) {
4081 GST_WARNING_OBJECT (splitmux, "Starting next file without buffer");
4082 }
4083
4084 caps = gst_pad_get_current_caps (ctx->srcpad);
4085 sample = gst_sample_new (ctx->cur_out_buffer, caps, &ctx->out_segment, NULL);
4086 g_signal_emit (splitmux, signals[SIGNAL_FORMAT_LOCATION_FULL], 0,
4087 splitmux->next_fragment_id, sample, &fname);
4088 gst_sample_unref (sample);
4089 if (caps)
4090 gst_caps_unref (caps);
4091
4092 if (fname == NULL) {
4093 /* Fallback to the old signal if the new one returned nothing */
4094 g_signal_emit (splitmux, signals[SIGNAL_FORMAT_LOCATION], 0,
4095 splitmux->next_fragment_id, &fname);
4096 }
4097
4098 if (fname == NULL && splitmux->location != NULL) {
4099 fname = multifile_utils_printf_string_from_template (splitmux,
4100 splitmux->location, splitmux->next_fragment_id);
4101
4102 if (fname == NULL) {
4103 GST_ELEMENT_ERROR (splitmux, RESOURCE, SETTINGS,
4104 ("Invalid location"), ("%s", splitmux->location));
4105 res = FALSE;
4106 }
4107 }
4108
4109 if (fname) {
4110 GST_INFO_OBJECT (splitmux, "Setting file to %s", fname);
4111 if (g_object_class_find_property (G_OBJECT_GET_CLASS (splitmux->sink),
4112 "location") != NULL) {
4113 g_object_set (splitmux->sink, "location", fname, NULL);
4114 }
4115 g_free (fname);
4116 }
4117 splitmux->cur_fragment_id = splitmux->next_fragment_id;
4118
4119 return res;
4120 }
4121
4122 /* called with GST_SPLITMUX_LOCK */
4123 static void
4124 do_async_start (GstSplitMuxSink * splitmux)
4125 {
4126 GstMessage *message;
4127
4128 if (!splitmux->need_async_start) {
4129 GST_INFO_OBJECT (splitmux, "no async_start needed");
4130 return;
4131 }
4132
4133 splitmux->async_pending = TRUE;
4134
4135 GST_INFO_OBJECT (splitmux, "Sending async_start message");
4136 message = gst_message_new_async_start (GST_OBJECT_CAST (splitmux));
4137
4138 GST_SPLITMUX_UNLOCK (splitmux);
4139 GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST
4140 (splitmux), message);
4141 GST_SPLITMUX_LOCK (splitmux);
4142 }
4143
4144 /* called with GST_SPLITMUX_LOCK */
4145 static void
4146 do_async_done (GstSplitMuxSink * splitmux)
4147 {
4148 GstMessage *message;
4149
4150 if (splitmux->async_pending) {
4151 GST_INFO_OBJECT (splitmux, "Sending async_done message");
4152 splitmux->async_pending = FALSE;
4153 GST_SPLITMUX_UNLOCK (splitmux);
4154
4155 message =
4156 gst_message_new_async_done (GST_OBJECT_CAST (splitmux),
4157 GST_CLOCK_TIME_NONE);
4158 GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST
4159 (splitmux), message);
4160 GST_SPLITMUX_LOCK (splitmux);
4161 }
4162
4163 splitmux->need_async_start = FALSE;
4164 }
4165
4166 static void
4167 gst_splitmux_sink_reset (GstSplitMuxSink * splitmux)
4168 {
4169 splitmux->max_in_running_time = GST_CLOCK_STIME_NONE;
4170 splitmux->max_in_running_time_dts = GST_CLOCK_STIME_NONE;
4171
4172 splitmux->fragment_start_time = GST_CLOCK_STIME_NONE;
4173 splitmux->fragment_start_time_pts = GST_CLOCK_STIME_NONE;
4174 g_clear_pointer (&splitmux->fragment_start_tc, gst_video_time_code_free);
4175
4176 g_queue_foreach (&splitmux->pending_input_gops, (GFunc) input_gop_free, NULL);
4177 g_queue_clear (&splitmux->pending_input_gops);
4178
4179 splitmux->max_out_running_time = GST_CLOCK_STIME_NONE;
4180 splitmux->fragment_total_bytes = 0;
4181 splitmux->fragment_reference_bytes = 0;
4182 splitmux->muxed_out_bytes = 0;
4183 splitmux->ready_for_output = FALSE;
4184
4185 g_atomic_int_set (&(splitmux->split_requested), FALSE);
4186 g_atomic_int_set (&(splitmux->do_split_next_gop), FALSE);
4187
4188 splitmux->next_fku_time = GST_CLOCK_TIME_NONE;
4189 gst_vec_deque_clear (splitmux->times_to_split);
4190
4191 g_list_foreach (splitmux->contexts, (GFunc) mq_stream_ctx_reset, NULL);
4192 splitmux->queued_keyframes = 0;
4193
4194 g_queue_foreach (&splitmux->out_cmd_q, (GFunc) out_cmd_buf_free, NULL);
4195 g_queue_clear (&splitmux->out_cmd_q);
4196
4197 splitmux->out_fragment_start_runts = splitmux->out_start_runts =
4198 GST_CLOCK_STIME_NONE;
4199 }
4200
4201 static GstStateChangeReturn
4202 gst_splitmux_sink_change_state (GstElement * element, GstStateChange transition)
4203 {
4204 GstStateChangeReturn ret;
4205 GstSplitMuxSink *splitmux = (GstSplitMuxSink *) element;
4206
4207 switch (transition) {
4208 case GST_STATE_CHANGE_NULL_TO_READY:{
4209 GST_SPLITMUX_LOCK (splitmux);
4210 if (!create_muxer (splitmux) || !create_sink (splitmux)) {
4211 ret = GST_STATE_CHANGE_FAILURE;
4212 GST_SPLITMUX_UNLOCK (splitmux);
4213 goto beach;
4214 }
4215 g_signal_emit (splitmux, signals[SIGNAL_MUXER_ADDED], 0, splitmux->muxer);
4216 g_signal_emit (splitmux, signals[SIGNAL_SINK_ADDED], 0, splitmux->sink);
4217 GST_SPLITMUX_UNLOCK (splitmux);
4218 splitmux->next_fragment_id = splitmux->start_index;
4219 break;
4220 }
4221 case GST_STATE_CHANGE_READY_TO_PAUSED:{
4222 GST_SPLITMUX_LOCK (splitmux);
4223 /* Make sure contexts and tracking times are cleared, in case we're being reused */
4224 gst_splitmux_sink_reset (splitmux);
4225 /* Start by collecting one input on each pad */
4226 splitmux->input_state = SPLITMUX_INPUT_STATE_COLLECTING_GOP_START;
4227 splitmux->output_state = SPLITMUX_OUTPUT_STATE_START_NEXT_FILE;
4228
4229 GST_SPLITMUX_UNLOCK (splitmux);
4230
4231 GST_SPLITMUX_STATE_LOCK (splitmux);
4232 splitmux->shutdown = FALSE;
4233 GST_SPLITMUX_STATE_UNLOCK (splitmux);
4234 break;
4235 }
4236 case GST_STATE_CHANGE_PAUSED_TO_READY:
4237 case GST_STATE_CHANGE_READY_TO_READY:
4238 g_atomic_int_set (&(splitmux->split_requested), FALSE);
4239 g_atomic_int_set (&(splitmux->do_split_next_gop), FALSE);
4240 /* Fall through */
4241 case GST_STATE_CHANGE_READY_TO_NULL:
4242 GST_SPLITMUX_STATE_LOCK (splitmux);
4243 splitmux->shutdown = TRUE;
4244 GST_SPLITMUX_STATE_UNLOCK (splitmux);
4245
4246 GST_SPLITMUX_LOCK (splitmux);
4247 gst_splitmux_sink_reset (splitmux);
4248 splitmux->output_state = SPLITMUX_OUTPUT_STATE_STOPPED;
4249 splitmux->input_state = SPLITMUX_INPUT_STATE_STOPPED;
4250 /* Wake up any blocked threads */
4251 GST_LOG_OBJECT (splitmux,
4252 "State change -> NULL or READY. Waking threads");
4253 GST_SPLITMUX_BROADCAST_INPUT (splitmux);
4254 GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
4255 GST_SPLITMUX_UNLOCK (splitmux);
4256 break;
4257 default:
4258 break;
4259 }
4260
4261 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4262 if (ret == GST_STATE_CHANGE_FAILURE)
4263 goto beach;
4264
4265 switch (transition) {
4266 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4267 splitmux->need_async_start = TRUE;
4268 break;
4269 case GST_STATE_CHANGE_READY_TO_PAUSED:{
4270 /* Change state async, because our child sink might not
4271 * be ready to do that for us yet if it's state is still locked */
4272
4273 splitmux->need_async_start = TRUE;
4274 /* we want to go async to PAUSED until we managed to configure and add the
4275 * sink */
4276 GST_SPLITMUX_LOCK (splitmux);
4277 do_async_start (splitmux);
4278 GST_SPLITMUX_UNLOCK (splitmux);
4279 ret = GST_STATE_CHANGE_ASYNC;
4280 break;
4281 }
4282 case GST_STATE_CHANGE_READY_TO_NULL:
4283 GST_SPLITMUX_LOCK (splitmux);
4284 splitmux->cur_fragment_id = splitmux->next_fragment_id = 0;
4285 /* Reset internal elements only if no pad contexts are using them */
4286 if (splitmux->contexts == NULL)
4287 gst_splitmux_reset_elements (splitmux);
4288 do_async_done (splitmux);
4289 GST_SPLITMUX_UNLOCK (splitmux);
4290 break;
4291 default:
4292 break;
4293 }
4294
4295 return ret;
4296
4297 beach:
4298 if (transition == GST_STATE_CHANGE_NULL_TO_READY) {
4299 /* Cleanup elements on failed transition out of NULL */
4300 gst_splitmux_reset_elements (splitmux);
4301 GST_SPLITMUX_LOCK (splitmux);
4302 do_async_done (splitmux);
4303 GST_SPLITMUX_UNLOCK (splitmux);
4304 }
4305 if (transition == GST_STATE_CHANGE_READY_TO_READY) {
4306 /* READY to READY transition only happens when we're already
4307 * in READY state, but a child element is in NULL, which
4308 * happens when there's an error changing the state of the sink.
4309 * We need to make sure not to fail the state transition, or
4310 * the core won't transition us back to NULL successfully */
4311 ret = GST_STATE_CHANGE_SUCCESS;
4312 }
4313 return ret;
4314 }
4315
4316 static void
4317 gst_splitmux_sink_ensure_max_files (GstSplitMuxSink * splitmux)
4318 {
4319 if (splitmux->max_files && splitmux->next_fragment_id >= splitmux->max_files) {
4320 splitmux->next_fragment_id = 0;
4321 }
4322 }
4323
4324 static void
4325 split_now (GstSplitMuxSink * splitmux)
4326 {
4327 g_atomic_int_set (&(splitmux->do_split_next_gop), TRUE);
4328 }
4329
4330 static void
4331 split_after (GstSplitMuxSink * splitmux)
4332 {
4333 g_atomic_int_set (&(splitmux->split_requested), TRUE);
4334 }
4335
4336 static void
4337 split_at_running_time (GstSplitMuxSink * splitmux, GstClockTime split_time)
4338 {
4339 gboolean send_keyframe_requests;
4340
4341 GST_SPLITMUX_LOCK (splitmux);
4342 gst_vec_deque_push_tail_struct (splitmux->times_to_split, &split_time);
4343 send_keyframe_requests = splitmux->send_keyframe_requests;
4344 GST_SPLITMUX_UNLOCK (splitmux);
4345
4346 if (send_keyframe_requests) {
4347 GstEvent *ev =
4348 gst_video_event_new_upstream_force_key_unit (split_time, TRUE, 0);
4349 GST_INFO_OBJECT (splitmux, "Requesting next keyframe at %" GST_TIME_FORMAT,
4350 GST_TIME_ARGS (split_time));
4351 if (!gst_pad_push_event (splitmux->reference_ctx->sinkpad, ev)) {
4352 GST_WARNING_OBJECT (splitmux,
4353 "Could not request keyframe at %" GST_TIME_FORMAT,
4354 GST_TIME_ARGS (split_time));
4355 }
4356 }
4357 }