gstsplitmuxsink.c 82.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* GStreamer Muxer bin that splits output stream by size/time
 * Copyright (C) <2014> Jan Schmidt <jan@centricular.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

/**
 * SECTION:element-splitmuxsink
 * @short_description: Muxer wrapper for splitting output stream by size or time
 *
 * This element wraps a muxer and a sink, and starts a new file when the mux
 * contents are about to cross a threshold of maximum size of maximum time,
 * splitting at video keyframe boundaries. Exactly one input video stream
27
 * can be muxed, with as many accompanying audio and subtitle streams as
28 29 30 31 32 33 34 35
 * desired.
 *
 * By default, it uses mp4mux and filesink, but they can be changed via
 * the 'muxer' and 'sink' properties.
 *
 * The minimum file size is 1 GOP, however - so limits may be overrun if the
 * distance between any 2 keyframes is larger than the limits.
 *
36 37 38 39
 * If a video stream is available, the splitting process is driven by the video
 * stream contents, and the video stream must contain closed GOPs for the output
 * file parts to be played individually correctly. In the absence of a video
 * stream, the first available stream is used as reference for synchronization.
40 41 42 43
 *
 * <refsect2>
 * <title>Example pipelines</title>
 * |[
44
 * gst-launch-1.0 -e v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! queue ! timeoverlay ! x264enc key-int-max=10 ! h264parse ! splitmuxsink location=video%02d.mov max-size-time=10000000000 max-size-bytes=1000000
45 46 47 48 49 50 51 52 53 54 55 56
 * ]|
 * Records a video stream captured from a v4l2 device and muxes it into
 * ISO mp4 files, splitting as needed to limit size/duration to 10 seconds
 * and 1MB maximum size.
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
57
#include <glib/gstdio.h>
58
#include <gst/video/video.h>
59 60 61 62 63 64 65
#include "gstsplitmuxsink.h"

GST_DEBUG_CATEGORY_STATIC (splitmux_debug);
#define GST_CAT_DEFAULT splitmux_debug

#define GST_SPLITMUX_LOCK(s) g_mutex_lock(&(s)->lock)
#define GST_SPLITMUX_UNLOCK(s) g_mutex_unlock(&(s)->lock)
66 67 68 69 70
#define GST_SPLITMUX_WAIT_INPUT(s) g_cond_wait (&(s)->input_cond, &(s)->lock)
#define GST_SPLITMUX_BROADCAST_INPUT(s) g_cond_broadcast (&(s)->input_cond)

#define GST_SPLITMUX_WAIT_OUTPUT(s) g_cond_wait (&(s)->output_cond, &(s)->lock)
#define GST_SPLITMUX_BROADCAST_OUTPUT(s) g_cond_broadcast (&(s)->output_cond)
71

72 73
static void split_now (GstSplitMuxSink * splitmux);

74 75 76 77 78 79
enum
{
  PROP_0,
  PROP_LOCATION,
  PROP_MAX_SIZE_TIME,
  PROP_MAX_SIZE_BYTES,
80
  PROP_MAX_SIZE_TIMECODE,
81
  PROP_SEND_KEYFRAME_REQUESTS,
82
  PROP_MAX_FILES,
83
  PROP_MUXER_OVERHEAD,
84
  PROP_USE_ROBUST_MUXING,
85
  PROP_ALIGNMENT_THRESHOLD,
86 87 88 89 90 91
  PROP_MUXER,
  PROP_SINK
};

#define DEFAULT_MAX_SIZE_TIME       0
#define DEFAULT_MAX_SIZE_BYTES      0
92
#define DEFAULT_MAX_FILES           0
93
#define DEFAULT_MUXER_OVERHEAD      0.02
94
#define DEFAULT_SEND_KEYFRAME_REQUESTS FALSE
95
#define DEFAULT_ALIGNMENT_THRESHOLD 0
96 97
#define DEFAULT_MUXER "mp4mux"
#define DEFAULT_SINK "filesink"
98
#define DEFAULT_USE_ROBUST_MUXING FALSE
99

100 101 102
enum
{
  SIGNAL_FORMAT_LOCATION,
103
  SIGNAL_FORMAT_LOCATION_FULL,
104
  SIGNAL_SPLIT_NOW,
105 106 107 108 109
  SIGNAL_LAST
};

static guint signals[SIGNAL_LAST];

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
static GstStaticPadTemplate video_sink_template =
GST_STATIC_PAD_TEMPLATE ("video",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS_ANY);
static GstStaticPadTemplate audio_sink_template =
GST_STATIC_PAD_TEMPLATE ("audio_%u",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS_ANY);
static GstStaticPadTemplate subtitle_sink_template =
GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS_ANY);

static GQuark PAD_CONTEXT;

static void
_do_init (void)
{
  PAD_CONTEXT = g_quark_from_static_string ("pad-context");
}

#define gst_splitmux_sink_parent_class parent_class
G_DEFINE_TYPE_EXTENDED (GstSplitMuxSink, gst_splitmux_sink, GST_TYPE_BIN, 0,
    _do_init ());

138
static gboolean create_muxer (GstSplitMuxSink * splitmux);
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
static gboolean create_sink (GstSplitMuxSink * splitmux);
static void gst_splitmux_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_splitmux_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
static void gst_splitmux_sink_dispose (GObject * object);
static void gst_splitmux_sink_finalize (GObject * object);

static GstPad *gst_splitmux_sink_request_new_pad (GstElement * element,
    GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
static void gst_splitmux_sink_release_pad (GstElement * element, GstPad * pad);

static GstStateChangeReturn gst_splitmux_sink_change_state (GstElement *
    element, GstStateChange transition);

static void bus_handler (GstBin * bin, GstMessage * msg);
155 156
static void set_next_filename (GstSplitMuxSink * splitmux, MqStreamCtx * ctx);
static void start_next_fragment (GstSplitMuxSink * splitmux, MqStreamCtx * ctx);
157
static void mq_stream_ctx_unref (MqStreamCtx * ctx);
158
static void grow_blocked_queues (GstSplitMuxSink * splitmux);
159

160
static void gst_splitmux_sink_ensure_max_files (GstSplitMuxSink * splitmux);
161 162
static GstElement *create_element (GstSplitMuxSink * splitmux,
    const gchar * factory, const gchar * name, gboolean locked);
163

164 165
static void do_async_done (GstSplitMuxSink * splitmux);

166 167 168 169 170 171 172 173 174 175 176 177
static MqStreamBuf *
mq_stream_buf_new (void)
{
  return g_slice_new0 (MqStreamBuf);
}

static void
mq_stream_buf_free (MqStreamBuf * data)
{
  g_slice_free (MqStreamBuf, data);
}

178 179 180 181 182 183 184 185 186 187 188 189
static SplitMuxOutputCommand *
out_cmd_buf_new (void)
{
  return g_slice_new0 (SplitMuxOutputCommand);
}

static void
out_cmd_buf_free (SplitMuxOutputCommand * data)
{
  g_slice_free (SplitMuxOutputCommand, data);
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
static void
gst_splitmux_sink_class_init (GstSplitMuxSinkClass * klass)
{
  GObjectClass *gobject_class = (GObjectClass *) klass;
  GstElementClass *gstelement_class = (GstElementClass *) klass;
  GstBinClass *gstbin_class = (GstBinClass *) klass;

  gobject_class->set_property = gst_splitmux_sink_set_property;
  gobject_class->get_property = gst_splitmux_sink_get_property;
  gobject_class->dispose = gst_splitmux_sink_dispose;
  gobject_class->finalize = gst_splitmux_sink_finalize;

  gst_element_class_set_static_metadata (gstelement_class,
      "Split Muxing Bin", "Generic/Bin/Muxer",
      "Convenience bin that muxes incoming streams into multiple time/size limited files",
      "Jan Schmidt <jan@centricular.com>");

207 208 209 210 211 212
  gst_element_class_add_static_pad_template (gstelement_class,
      &video_sink_template);
  gst_element_class_add_static_pad_template (gstelement_class,
      &audio_sink_template);
  gst_element_class_add_static_pad_template (gstelement_class,
      &subtitle_sink_template);
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_splitmux_sink_change_state);
  gstelement_class->request_new_pad =
      GST_DEBUG_FUNCPTR (gst_splitmux_sink_request_new_pad);
  gstelement_class->release_pad =
      GST_DEBUG_FUNCPTR (gst_splitmux_sink_release_pad);

  gstbin_class->handle_message = bus_handler;

  g_object_class_install_property (gobject_class, PROP_LOCATION,
      g_param_spec_string ("location", "File Output Pattern",
          "Format string pattern for the location of the files to write (e.g. video%05d.mp4)",
          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_MUXER_OVERHEAD,
      g_param_spec_double ("mux-overhead", "Muxing Overhead",
          "Extra size overhead of muxing (0.02 = 2%)", 0.0, 1.0,
          DEFAULT_MUXER_OVERHEAD,
          G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
      g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
          "Max. amount of time per file (in ns, 0=disable)", 0, G_MAXUINT64,
          DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
      g_param_spec_uint64 ("max-size-bytes", "Max. size bytes",
          "Max. amount of data per file (in bytes, 0=disable)", 0, G_MAXUINT64,
          DEFAULT_MAX_SIZE_BYTES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
241 242 243 244 245 246
  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIMECODE,
      g_param_spec_string ("max-size-timecode", "Maximum timecode difference",
          "Maximum difference in timecode between first and last frame. "
          "Separator is assumed to be \":\" everywhere (e.g. 01:00:00:00). "
          "Will only be effective if a timecode track is present.",
          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
247 248 249 250 251 252 253
  g_object_class_install_property (gobject_class, PROP_SEND_KEYFRAME_REQUESTS,
      g_param_spec_boolean ("send-keyframe-requests",
          "Request keyframes at max-size-time",
          "Request a keyframe every max-size-time ns to try splitting at that point. "
          "Needs max-size-bytes to be 0 in order to be effective.",
          DEFAULT_SEND_KEYFRAME_REQUESTS,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
254 255 256
  g_object_class_install_property (gobject_class, PROP_MAX_FILES,
      g_param_spec_uint ("max-files", "Max files",
          "Maximum number of files to keep on disk. Once the maximum is reached,"
257 258
          "old files start to be deleted to make room for new ones.", 0,
          G_MAXUINT, DEFAULT_MAX_FILES,
259
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
260 261 262 263 264 265
  g_object_class_install_property (gobject_class, PROP_ALIGNMENT_THRESHOLD,
      g_param_spec_uint64 ("alignment-threshold", "Alignment threshold (ns)",
          "Allow non-reference streams to be that many ns before the reference"
          " stream",
          0, G_MAXUINT64, DEFAULT_ALIGNMENT_THRESHOLD,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266 267 268 269 270 271 272 273 274

  g_object_class_install_property (gobject_class, PROP_MUXER,
      g_param_spec_object ("muxer", "Muxer",
          "The muxer element to use (NULL = default mp4mux)",
          GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_SINK,
      g_param_spec_object ("sink", "Sink",
          "The sink element (or element chain) to use (NULL = default filesink)",
          GST_TYPE_ELEMENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
275

276 277 278 279 280 281 282 283 284 285 286
  g_object_class_install_property (gobject_class, PROP_USE_ROBUST_MUXING,
      g_param_spec_boolean ("use-robust-muxing",
          "Support robust-muxing mode of some muxers",
          "Check if muxers support robust muxing via the reserved-max-duration and "
          "reserved-duration-remaining properties and use them if so. "
          "(Only present on qtmux and mp4mux for now). splitmuxsink may then also "
          " create new fragments if the reserved header space is about to overflow. "
          "Note this does not set reserved-moov-update-period - apps should do that manually",
          DEFAULT_USE_ROBUST_MUXING,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

287 288 289 290 291 292 293 294 295 296
  /**
   * GstSplitMuxSink::format-location:
   * @splitmux: the #GstSplitMuxSink
   * @fragment_id: the sequence number of the file to be created
   *
   * Returns: the location to be used for the next output file
   */
  signals[SIGNAL_FORMAT_LOCATION] =
      g_signal_new ("format-location", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_STRING, 1, G_TYPE_UINT);
297 298 299 300 301 302 303 304 305 306 307 308 309 310

  /**
   * GstSplitMuxSink::format-location-full:
   * @splitmux: the #GstSplitMuxSink
   * @fragment_id: the sequence number of the file to be created
   * @first_sample: A #GstSample containing the first buffer
   *   from the reference stream in the new file
   *
   * Returns: the location to be used for the next output file
   */
  signals[SIGNAL_FORMAT_LOCATION_FULL] =
      g_signal_new ("format-location-full", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_STRING, 2, G_TYPE_UINT,
      GST_TYPE_SAMPLE);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

  /**
   * GstSplitMuxSink::split-now:
   * @splitmux: the #GstSplitMuxSink
   *
   * When called by the user, this action signal splits the video file (and begins a new one) immediately.
   *
   *
   * Since: 1.14
   */

  signals[SIGNAL_SPLIT_NOW] =
      g_signal_new ("split-now", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstSplitMuxSinkClass,
          split_now), NULL, NULL, NULL, G_TYPE_NONE, 0);

  klass->split_now = split_now;
328 329 330 331 332 333
}

static void
gst_splitmux_sink_init (GstSplitMuxSink * splitmux)
{
  g_mutex_init (&splitmux->lock);
334 335 336
  g_cond_init (&splitmux->input_cond);
  g_cond_init (&splitmux->output_cond);
  g_queue_init (&splitmux->out_cmd_q);
337 338 339 340

  splitmux->mux_overhead = DEFAULT_MUXER_OVERHEAD;
  splitmux->threshold_time = DEFAULT_MAX_SIZE_TIME;
  splitmux->threshold_bytes = DEFAULT_MAX_SIZE_BYTES;
341
  splitmux->max_files = DEFAULT_MAX_FILES;
342
  splitmux->send_keyframe_requests = DEFAULT_SEND_KEYFRAME_REQUESTS;
343
  splitmux->next_max_tc_time = GST_CLOCK_TIME_NONE;
344
  splitmux->alignment_threshold = DEFAULT_ALIGNMENT_THRESHOLD;
345
  splitmux->use_robust_muxing = DEFAULT_USE_ROBUST_MUXING;
346 347

  splitmux->threshold_timecode_str = NULL;
348 349

  GST_OBJECT_FLAG_SET (splitmux, GST_ELEMENT_FLAG_SINK);
350
  splitmux->split_now = FALSE;
351 352 353 354 355
}

static void
gst_splitmux_reset (GstSplitMuxSink * splitmux)
{
356 357 358
  if (splitmux->muxer) {
    gst_element_set_locked_state (splitmux->muxer, TRUE);
    gst_element_set_state (splitmux->muxer, GST_STATE_NULL);
359
    gst_bin_remove (GST_BIN (splitmux), splitmux->muxer);
360 361 362 363
  }
  if (splitmux->active_sink) {
    gst_element_set_locked_state (splitmux->active_sink, TRUE);
    gst_element_set_state (splitmux->active_sink, GST_STATE_NULL);
364
    gst_bin_remove (GST_BIN (splitmux), splitmux->active_sink);
365
  }
366

367
  splitmux->sink = splitmux->active_sink = splitmux->muxer = NULL;
368 369 370 371 372 373 374 375
}

static void
gst_splitmux_sink_dispose (GObject * object)
{
  GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);

  /* Calling parent dispose invalidates all child pointers */
376
  splitmux->sink = splitmux->active_sink = splitmux->muxer = NULL;
377 378

  G_OBJECT_CLASS (parent_class)->dispose (object);
379 380 381 382 383 384
}

static void
gst_splitmux_sink_finalize (GObject * object)
{
  GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);
385 386
  g_cond_clear (&splitmux->input_cond);
  g_cond_clear (&splitmux->output_cond);
387
  g_mutex_clear (&splitmux->lock);
388 389 390
  g_queue_foreach (&splitmux->out_cmd_q, (GFunc) out_cmd_buf_free, NULL);
  g_queue_clear (&splitmux->out_cmd_q);

391 392
  if (splitmux->provided_sink)
    gst_object_unref (splitmux->provided_sink);
393 394
  if (splitmux->provided_muxer)
    gst_object_unref (splitmux->provided_muxer);
395

396 397 398
  if (splitmux->threshold_timecode_str)
    g_free (splitmux->threshold_timecode_str);

399 400
  g_free (splitmux->location);

401 402 403 404
  /* Make sure to free any un-released contexts */
  g_list_foreach (splitmux->contexts, (GFunc) mq_stream_ctx_unref, NULL);
  g_list_free (splitmux->contexts);

405 406 407
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/*
 * Set any time threshold to the muxer, if it has
 * reserved-max-duration and reserved-duration-remaining
 * properties. Called when creating/claiming the muxer
 * in create_elements() */
static void
update_muxer_properties (GstSplitMuxSink * sink)
{
  GObjectClass *klass;
  GstClockTime threshold_time;

  sink->muxer_has_reserved_props = FALSE;
  if (sink->muxer == NULL)
    return;
  klass = G_OBJECT_GET_CLASS (sink->muxer);
  if (g_object_class_find_property (klass, "reserved-max-duration") == NULL)
    return;
  if (g_object_class_find_property (klass,
          "reserved-duration-remaining") == NULL)
    return;
  sink->muxer_has_reserved_props = TRUE;

  GST_LOG_OBJECT (sink, "Setting muxer reserved time to %" GST_TIME_FORMAT,
      GST_TIME_ARGS (sink->threshold_time));
  GST_OBJECT_LOCK (sink);
  threshold_time = sink->threshold_time;
  GST_OBJECT_UNLOCK (sink);

  if (threshold_time > 0) {
    /* Tell the muxer how much space to reserve */
    GstClockTime muxer_threshold = threshold_time;
    g_object_set (sink->muxer, "reserved-max-duration", muxer_threshold, NULL);
  }
}

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
static void
gst_splitmux_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);

  switch (prop_id) {
    case PROP_LOCATION:{
      GST_OBJECT_LOCK (splitmux);
      g_free (splitmux->location);
      splitmux->location = g_value_dup_string (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
    }
    case PROP_MAX_SIZE_BYTES:
      GST_OBJECT_LOCK (splitmux);
      splitmux->threshold_bytes = g_value_get_uint64 (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
    case PROP_MAX_SIZE_TIME:
      GST_OBJECT_LOCK (splitmux);
      splitmux->threshold_time = g_value_get_uint64 (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
467 468 469 470 471
    case PROP_MAX_SIZE_TIMECODE:
      GST_OBJECT_LOCK (splitmux);
      splitmux->threshold_timecode_str = g_value_dup_string (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
472 473 474 475 476
    case PROP_SEND_KEYFRAME_REQUESTS:
      GST_OBJECT_LOCK (splitmux);
      splitmux->send_keyframe_requests = g_value_get_boolean (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
477 478 479 480 481
    case PROP_MAX_FILES:
      GST_OBJECT_LOCK (splitmux);
      splitmux->max_files = g_value_get_uint (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
482 483 484 485 486
    case PROP_MUXER_OVERHEAD:
      GST_OBJECT_LOCK (splitmux);
      splitmux->mux_overhead = g_value_get_double (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
487 488 489 490 491 492 493
    case PROP_USE_ROBUST_MUXING:
      GST_OBJECT_LOCK (splitmux);
      splitmux->use_robust_muxing = g_value_get_boolean (value);
      GST_OBJECT_UNLOCK (splitmux);
      if (splitmux->use_robust_muxing)
        update_muxer_properties (splitmux);
      break;
494 495 496 497 498
    case PROP_ALIGNMENT_THRESHOLD:
      GST_OBJECT_LOCK (splitmux);
      splitmux->alignment_threshold = g_value_get_uint64 (value);
      GST_OBJECT_UNLOCK (splitmux);
      break;
499
    case PROP_SINK:
500
      GST_OBJECT_LOCK (splitmux);
501 502
      if (splitmux->provided_sink)
        gst_object_unref (splitmux->provided_sink);
503 504
      splitmux->provided_sink = g_value_get_object (value);
      gst_object_ref_sink (splitmux->provided_sink);
505
      GST_OBJECT_UNLOCK (splitmux);
506 507
      break;
    case PROP_MUXER:
508
      GST_OBJECT_LOCK (splitmux);
509 510
      if (splitmux->provided_muxer)
        gst_object_unref (splitmux->provided_muxer);
511 512
      splitmux->provided_muxer = g_value_get_object (value);
      gst_object_ref_sink (splitmux->provided_muxer);
513
      GST_OBJECT_UNLOCK (splitmux);
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_splitmux_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (object);

  switch (prop_id) {
    case PROP_LOCATION:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_string (value, splitmux->location);
      GST_OBJECT_UNLOCK (splitmux);
      break;
    case PROP_MAX_SIZE_BYTES:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_uint64 (value, splitmux->threshold_bytes);
      GST_OBJECT_UNLOCK (splitmux);
      break;
    case PROP_MAX_SIZE_TIME:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_uint64 (value, splitmux->threshold_time);
      GST_OBJECT_UNLOCK (splitmux);
      break;
543 544 545 546 547
    case PROP_MAX_SIZE_TIMECODE:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_string (value, splitmux->threshold_timecode_str);
      GST_OBJECT_UNLOCK (splitmux);
      break;
548 549 550 551 552
    case PROP_SEND_KEYFRAME_REQUESTS:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_boolean (value, splitmux->send_keyframe_requests);
      GST_OBJECT_UNLOCK (splitmux);
      break;
553 554 555 556 557
    case PROP_MAX_FILES:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_uint (value, splitmux->max_files);
      GST_OBJECT_UNLOCK (splitmux);
      break;
558 559 560 561 562
    case PROP_MUXER_OVERHEAD:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_double (value, splitmux->mux_overhead);
      GST_OBJECT_UNLOCK (splitmux);
      break;
563 564 565 566 567
    case PROP_USE_ROBUST_MUXING:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_boolean (value, splitmux->use_robust_muxing);
      GST_OBJECT_UNLOCK (splitmux);
      break;
568 569 570 571 572
    case PROP_ALIGNMENT_THRESHOLD:
      GST_OBJECT_LOCK (splitmux);
      g_value_set_uint64 (value, splitmux->alignment_threshold);
      GST_OBJECT_UNLOCK (splitmux);
      break;
573
    case PROP_SINK:
574
      GST_OBJECT_LOCK (splitmux);
575
      g_value_set_object (value, splitmux->provided_sink);
576
      GST_OBJECT_UNLOCK (splitmux);
577 578
      break;
    case PROP_MUXER:
579
      GST_OBJECT_LOCK (splitmux);
580
      g_value_set_object (value, splitmux->provided_muxer);
581
      GST_OBJECT_UNLOCK (splitmux);
582 583 584 585 586 587 588
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
/* Convenience function */
static inline GstClockTimeDiff
my_segment_to_running_time (GstSegment * segment, GstClockTime val)
{
  GstClockTimeDiff res = GST_CLOCK_STIME_NONE;

  if (GST_CLOCK_TIME_IS_VALID (val)) {
    gboolean sign =
        gst_segment_to_running_time_full (segment, GST_FORMAT_TIME, val, &val);
    if (sign > 0)
      res = val;
    else if (sign < 0)
      res = -val;
  }
  return res;
}

606 607 608 609 610 611 612 613 614 615
static MqStreamCtx *
mq_stream_ctx_new (GstSplitMuxSink * splitmux)
{
  MqStreamCtx *ctx;

  ctx = g_new0 (MqStreamCtx, 1);
  g_atomic_int_set (&ctx->refcount, 1);
  ctx->splitmux = splitmux;
  gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
  gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
616
  ctx->in_running_time = ctx->out_running_time = GST_CLOCK_STIME_NONE;
617 618 619 620 621 622 623
  g_queue_init (&ctx->queued_bufs);
  return ctx;
}

static void
mq_stream_ctx_free (MqStreamCtx * ctx)
{
624 625 626 627 628 629 630
  if (ctx->q) {
    g_signal_handler_disconnect (ctx->q, ctx->q_overrun_id);
    gst_element_set_locked_state (ctx->q, TRUE);
    gst_element_set_state (ctx->q, GST_STATE_NULL);
    gst_bin_remove (GST_BIN (ctx->splitmux), ctx->q);
    gst_object_unref (ctx->q);
  }
631
  gst_buffer_replace (&ctx->prev_in_keyframe, NULL);
632 633
  gst_object_unref (ctx->sinkpad);
  gst_object_unref (ctx->srcpad);
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
  g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
  g_queue_clear (&ctx->queued_bufs);
  g_free (ctx);
}

static void
mq_stream_ctx_unref (MqStreamCtx * ctx)
{
  if (g_atomic_int_dec_and_test (&ctx->refcount))
    mq_stream_ctx_free (ctx);
}

static void
mq_stream_ctx_ref (MqStreamCtx * ctx)
{
  g_atomic_int_inc (&ctx->refcount);
}

static void
_pad_block_destroy_sink_notify (MqStreamCtx * ctx)
{
  ctx->sink_pad_block_id = 0;
  mq_stream_ctx_unref (ctx);
}

static void
_pad_block_destroy_src_notify (MqStreamCtx * ctx)
{
  ctx->src_pad_block_id = 0;
  mq_stream_ctx_unref (ctx);
}

666 667 668 669 670 671 672 673 674 675
static void
send_fragment_opened_closed_msg (GstSplitMuxSink * splitmux, gboolean opened)
{
  gchar *location = NULL;
  GstMessage *msg;
  const gchar *msg_name = opened ?
      "splitmuxsink-fragment-opened" : "splitmuxsink-fragment-closed";

  g_object_get (splitmux->sink, "location", &location, NULL);

676 677 678 679 680 681 682 683 684 685
  /* If it's in the middle of a teardown, the reference_ctc might have become
   * NULL */
  if (splitmux->reference_ctx) {
    msg = gst_message_new_element (GST_OBJECT (splitmux),
        gst_structure_new (msg_name,
            "location", G_TYPE_STRING, location,
            "running-time", GST_TYPE_CLOCK_TIME,
            splitmux->reference_ctx->out_running_time, NULL));
    gst_element_post_message (GST_ELEMENT_CAST (splitmux), msg);
  }
686 687 688 689

  g_free (location);
}

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
/* Called with lock held, drops the lock to send EOS to the
 * pad
 */
static void
send_eos (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
{
  GstEvent *eos;
  GstPad *pad;

  eos = gst_event_new_eos ();
  pad = gst_pad_get_peer (ctx->srcpad);

  ctx->out_eos = TRUE;

  GST_INFO_OBJECT (splitmux, "Sending EOS on %" GST_PTR_FORMAT, pad);
  GST_SPLITMUX_UNLOCK (splitmux);
  gst_pad_send_event (pad, eos);
  GST_SPLITMUX_LOCK (splitmux);

  gst_object_unref (pad);
}

/* Called with splitmux lock held to check if this output
 * context needs to sleep to wait for the release of the
 * next GOP, or to send EOS to close out the current file
 */
static void
complete_or_wait_on_out (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
{
719 720 721
  if (ctx->caps_change)
    return;

722
  do {
723 724 725
    /* When first starting up, the reference stream has to output
     * the first buffer to prepare the muxer and sink */
    gboolean can_output = (ctx->is_reference || splitmux->ready_for_output);
726 727 728 729 730 731 732 733 734 735 736 737 738
    GstClockTimeDiff my_max_out_running_time = splitmux->max_out_running_time;

    if (!(splitmux->max_out_running_time == 0 ||
            splitmux->max_out_running_time == GST_CLOCK_STIME_NONE ||
            splitmux->alignment_threshold == 0 ||
            splitmux->max_out_running_time < splitmux->alignment_threshold)) {
      my_max_out_running_time -= splitmux->alignment_threshold;
      GST_LOG_OBJECT (ctx->srcpad,
          "Max out running time currently %" GST_STIME_FORMAT
          ", with threshold applied it is %" GST_STIME_FORMAT,
          GST_STIME_ARGS (splitmux->max_out_running_time),
          GST_STIME_ARGS (my_max_out_running_time));
    }
739 740 741 742

    if (ctx->flushing
        || splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
      return;
743 744

    GST_LOG_OBJECT (ctx->srcpad,
745 746
        "Checking running time %" GST_STIME_FORMAT " against max %"
        GST_STIME_FORMAT, GST_STIME_ARGS (ctx->out_running_time),
747
        GST_STIME_ARGS (my_max_out_running_time));
748

749 750
    if (can_output) {
      if (splitmux->max_out_running_time == GST_CLOCK_STIME_NONE ||
751
          ctx->out_running_time < my_max_out_running_time) {
752 753
        return;
      }
754

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
      switch (splitmux->output_state) {
        case SPLITMUX_OUTPUT_STATE_OUTPUT_GOP:
          /* We only get here if we've finished outputting a GOP and need to know
           * what to do next */
          splitmux->output_state = SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND;
          GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
          continue;

        case SPLITMUX_OUTPUT_STATE_ENDING_FILE:
          /* We've reached the max out running_time to get here, so end this file now */
          if (ctx->out_eos == FALSE) {
            send_eos (splitmux, ctx);
            continue;
          }
          break;
        case SPLITMUX_OUTPUT_STATE_START_NEXT_FILE:
          if (ctx->is_reference) {
            /* Special handling on the reference ctx to start new fragments
             * and collect commands from the command queue */
            /* drops the splitmux lock briefly: */
            start_next_fragment (splitmux, ctx);
            continue;
          }
          break;
779

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        case SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND:{
          do {
            SplitMuxOutputCommand *cmd =
                g_queue_pop_tail (&splitmux->out_cmd_q);
            if (cmd != NULL) {
              /* If we pop the last command, we need to make our queues bigger */
              if (g_queue_get_length (&splitmux->out_cmd_q) == 0)
                grow_blocked_queues (splitmux);

              if (cmd->start_new_fragment) {
                GST_DEBUG_OBJECT (splitmux, "Got cmd to start new fragment");
                splitmux->output_state = SPLITMUX_OUTPUT_STATE_ENDING_FILE;
              } else {
                GST_DEBUG_OBJECT (splitmux,
                    "Got new output cmd for time %" GST_STIME_FORMAT,
                    GST_STIME_ARGS (cmd->max_output_ts));

                /* Extend the output range immediately */
                splitmux->max_out_running_time = cmd->max_output_ts;
                splitmux->output_state = SPLITMUX_OUTPUT_STATE_OUTPUT_GOP;
              }
              GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);

              out_cmd_buf_free (cmd);
              break;
            } else {
              GST_SPLITMUX_WAIT_OUTPUT (splitmux);
            }
          } while (splitmux->output_state ==
              SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND);
          /* loop and re-check the state */
          continue;
        }
        case SPLITMUX_OUTPUT_STATE_STOPPED:
          return;
815 816 817 818 819
      }
    }

    GST_INFO_OBJECT (ctx->srcpad,
        "Sleeping for running time %"
820
        GST_STIME_FORMAT " (max %" GST_STIME_FORMAT ") or state change.",
821 822
        GST_STIME_ARGS (ctx->out_running_time),
        GST_STIME_ARGS (splitmux->max_out_running_time));
823
    GST_SPLITMUX_WAIT_OUTPUT (splitmux);
824
    GST_INFO_OBJECT (ctx->srcpad,
825 826
        "Woken for new max running time %" GST_STIME_FORMAT,
        GST_STIME_ARGS (splitmux->max_out_running_time));
827 828
  }
  while (1);
829 830
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
static GstClockTime
calculate_next_max_timecode (GstSplitMuxSink * splitmux,
    const GstVideoTimeCode * cur_tc)
{
  GstVideoTimeCode *target_tc;
  GstVideoTimeCodeInterval *tc_inter;
  GstClockTime cur_tc_time, target_tc_time, next_max_tc_time;

  if (cur_tc == NULL || splitmux->threshold_timecode_str == NULL)
    return GST_CLOCK_TIME_NONE;

  tc_inter =
      gst_video_time_code_interval_new_from_string
      (splitmux->threshold_timecode_str);
  target_tc = gst_video_time_code_add_interval (cur_tc, tc_inter);
  gst_video_time_code_interval_free (tc_inter);

  /* Convert to ns */
  target_tc_time = gst_video_time_code_nsec_since_daily_jam (target_tc);
  cur_tc_time = gst_video_time_code_nsec_since_daily_jam (cur_tc);

  /* Add fragment_start_time, accounting for wraparound */
  if (target_tc_time >= cur_tc_time) {
    next_max_tc_time =
        target_tc_time - cur_tc_time + splitmux->fragment_start_time;
  } else {
    GstClockTime day_in_ns = 24 * 60 * 60 * GST_SECOND;

    next_max_tc_time =
        day_in_ns - cur_tc_time + target_tc_time +
        splitmux->fragment_start_time;
  }
  GST_INFO_OBJECT (splitmux, "Next max TC time: %" GST_TIME_FORMAT
      " from ref TC: %" GST_TIME_FORMAT, GST_TIME_ARGS (next_max_tc_time),
      GST_TIME_ARGS (cur_tc_time));
  gst_video_time_code_free (target_tc);

  return next_max_tc_time;
}

871
static gboolean
872
request_next_keyframe (GstSplitMuxSink * splitmux, GstBuffer * buffer)
873 874
{
  GstEvent *ev;
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
  GstClockTime target_time;
  gboolean timecode_based = FALSE;

  splitmux->next_max_tc_time = GST_CLOCK_TIME_NONE;
  if (splitmux->threshold_timecode_str) {
    GstVideoTimeCodeMeta *tc_meta;

    if (buffer != NULL) {
      tc_meta = gst_buffer_get_video_time_code_meta (buffer);
      if (tc_meta) {
        splitmux->next_max_tc_time =
            calculate_next_max_timecode (splitmux, &tc_meta->tc);
        timecode_based = (splitmux->next_max_tc_time != GST_CLOCK_TIME_NONE);
      }
    } else {
      /* This can happen in the presence of GAP events that trigger
       * a new fragment start */
      GST_WARNING_OBJECT (splitmux,
          "No buffer available to calculate next timecode");
    }
  }
896

897
  if (splitmux->send_keyframe_requests == FALSE
898 899
      || (splitmux->threshold_time == 0 && !timecode_based)
      || splitmux->threshold_bytes != 0)
900 901
    return TRUE;

902 903 904 905 906 907 908 909 910
  if (timecode_based) {
    /* We might have rounding errors: aim slightly earlier */
    target_time = splitmux->next_max_tc_time - 5 * GST_USECOND;
  } else {
    target_time = splitmux->fragment_start_time + splitmux->threshold_time;
  }
  ev = gst_video_event_new_upstream_force_key_unit (target_time, TRUE, 0);
  GST_INFO_OBJECT (splitmux, "Requesting next keyframe at %" GST_TIME_FORMAT,
      GST_TIME_ARGS (target_time));
911 912 913
  return gst_pad_push_event (splitmux->reference_ctx->sinkpad, ev);
}

914 915 916 917 918 919
static GstPadProbeReturn
handle_mq_output (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
{
  GstSplitMuxSink *splitmux = ctx->splitmux;
  MqStreamBuf *buf_info = NULL;

920
  GST_LOG_OBJECT (pad, "Fired probe type 0x%x", info->type);
921 922 923 924 925 926

  /* FIXME: Handle buffer lists, until then make it clear they won't work */
  if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
    g_warning ("Buffer list handling not implemented");
    return GST_PAD_PROBE_DROP;
  }
927 928
  if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM ||
      info->type & GST_PAD_PROBE_TYPE_EVENT_FLUSH) {
929
    GstEvent *event = gst_pad_probe_info_get_event (info);
930
    gboolean locked = FALSE;
931 932 933 934 935 936 937 938 939

    GST_LOG_OBJECT (pad, "Event %" GST_PTR_FORMAT, event);

    switch (GST_EVENT_TYPE (event)) {
      case GST_EVENT_SEGMENT:
        gst_event_copy_segment (event, &ctx->out_segment);
        break;
      case GST_EVENT_FLUSH_STOP:
        GST_SPLITMUX_LOCK (splitmux);
940
        locked = TRUE;
941 942 943 944 945 946 947
        gst_segment_init (&ctx->out_segment, GST_FORMAT_UNDEFINED);
        g_queue_foreach (&ctx->queued_bufs, (GFunc) mq_stream_buf_free, NULL);
        g_queue_clear (&ctx->queued_bufs);
        ctx->flushing = FALSE;
        break;
      case GST_EVENT_FLUSH_START:
        GST_SPLITMUX_LOCK (splitmux);
948
        locked = TRUE;
949 950
        GST_LOG_OBJECT (pad, "Flush start");
        ctx->flushing = TRUE;
951
        GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
952 953 954
        break;
      case GST_EVENT_EOS:
        GST_SPLITMUX_LOCK (splitmux);
955 956
        locked = TRUE;
        if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
957 958 959 960 961
          goto beach;
        ctx->out_eos = TRUE;
        break;
      case GST_EVENT_GAP:{
        GstClockTime gap_ts;
962
        GstClockTimeDiff rtime;
963 964 965 966 967 968

        gst_event_parse_gap (event, &gap_ts, NULL);
        if (gap_ts == GST_CLOCK_TIME_NONE)
          break;

        GST_SPLITMUX_LOCK (splitmux);
969
        locked = TRUE;
970

971
        if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
972
          goto beach;
973

974 975 976 977 978 979
        /* When we get a gap event on the
         * reference stream and we're trying to open a
         * new file, we need to store it until we get
         * the buffer afterwards
         */
        if (ctx->is_reference &&
980
            (splitmux->output_state != SPLITMUX_OUTPUT_STATE_OUTPUT_GOP)) {
981 982 983 984 985 986
          GST_DEBUG_OBJECT (pad, "Storing GAP event until buffer arrives");
          gst_event_replace (&ctx->pending_gap, event);
          GST_SPLITMUX_UNLOCK (splitmux);
          return GST_PAD_PROBE_HANDLED;
        }

987 988 989 990 991
        rtime = my_segment_to_running_time (&ctx->out_segment, gap_ts);

        GST_LOG_OBJECT (pad, "Have GAP w/ ts %" GST_STIME_FORMAT,
            GST_STIME_ARGS (rtime));

992 993 994 995
        if (rtime != GST_CLOCK_STIME_NONE) {
          ctx->out_running_time = rtime;
          complete_or_wait_on_out (splitmux, ctx);
        }
996 997
        break;
      }
998 999
      case GST_EVENT_CUSTOM_DOWNSTREAM:{
        const GstStructure *s;
1000
        GstClockTimeDiff ts = 0;
1001 1002 1003 1004 1005

        s = gst_event_get_structure (event);
        if (!gst_structure_has_name (s, "splitmuxsink-unblock"))
          break;

1006
        gst_structure_get_int64 (s, "timestamp", &ts);
1007 1008

        GST_SPLITMUX_LOCK (splitmux);
1009
        locked = TRUE;
1010

1011
        if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_STOPPED)
1012 1013
          goto beach;
        ctx->out_running_time = ts;
1014 1015
        if (!ctx->is_reference)
          complete_or_wait_on_out (splitmux, ctx);
1016 1017 1018
        GST_SPLITMUX_UNLOCK (splitmux);
        return GST_PAD_PROBE_DROP;
      }
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
      case GST_EVENT_CAPS:{
        GstPad *peer;

        if (!ctx->is_reference)
          break;

        peer = gst_pad_get_peer (pad);
        if (peer) {
          gboolean ok = gst_pad_send_event (peer, gst_event_ref (event));

          gst_object_unref (peer);

          if (ok)
            break;
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042
        } else {
          break;
        }
        /* This is in the case the muxer doesn't allow this change of caps */
        GST_SPLITMUX_LOCK (splitmux);
        locked = TRUE;
        ctx->caps_change = TRUE;

        if (splitmux->output_state != SPLITMUX_OUTPUT_STATE_START_NEXT_FILE) {
1043 1044
          GST_DEBUG_OBJECT (splitmux,
              "New caps were not accepted. Switching output file");
1045
          if (ctx->out_eos == FALSE) {
1046 1047
            splitmux->output_state = SPLITMUX_OUTPUT_STATE_ENDING_FILE;
            GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1048 1049 1050 1051 1052 1053 1054 1055
          }
        }

        /* Lets it fall through, if it fails again, then the muxer just can't
         * support this format, but at least we have a closed file.
         */
        break;
      }
1056 1057 1058
      default:
        break;
    }
1059 1060 1061 1062 1063 1064 1065 1066 1067

    /* We need to make sure events aren't passed
     * until the muxer / sink are ready for it */
    if (!locked)
      GST_SPLITMUX_LOCK (splitmux);
    if (!ctx->is_reference)
      complete_or_wait_on_out (splitmux, ctx);
    GST_SPLITMUX_UNLOCK (splitmux);

1068 1069 1070 1071
    /* Don't try to forward sticky events before the next buffer is there
     * because it would cause a new file to be created without the first
     * buffer being available.
     */
1072 1073 1074 1075
    if (ctx->caps_change && GST_EVENT_IS_STICKY (event)) {
      gst_event_unref (event);
      return GST_PAD_PROBE_HANDLED;
    } else
1076
      return GST_PAD_PROBE_PASS;
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  }

  /* Allow everything through until the configured next stopping point */
  GST_SPLITMUX_LOCK (splitmux);

  buf_info = g_queue_pop_tail (&ctx->queued_bufs);
  if (buf_info == NULL)
    /* Can only happen due to a poorly timed flush */
    goto beach;

  /* If we have popped a keyframe, decrement the queued_gop count */
1088 1089
  if (buf_info->keyframe && splitmux->queued_keyframes > 0)
    splitmux->queued_keyframes--;
1090 1091

  ctx->out_running_time = buf_info->run_ts;
1092
  ctx->cur_out_buffer = gst_pad_probe_info_get_buffer (info);
1093 1094

  GST_LOG_OBJECT (splitmux,
1095
      "Pad %" GST_PTR_FORMAT " buffer with run TS %" GST_STIME_FORMAT
1096
      " size %" G_GUINT64_FORMAT,
1097
      pad, GST_STIME_ARGS (ctx->out_running_time), buf_info->buf_size);
1098

1099 1100
  ctx->caps_change = FALSE;

1101 1102 1103 1104 1105 1106 1107 1108
  complete_or_wait_on_out (splitmux, ctx);

  splitmux->muxed_out_bytes += buf_info->buf_size;

#ifndef GST_DISABLE_GST_DEBUG
  {
    GstBuffer *buf = gst_pad_probe_info_get_buffer (info);
    GST_LOG_OBJECT (pad, "Returning to pass buffer %" GST_PTR_FORMAT
1109 1110
        " run ts %" GST_STIME_FORMAT, buf,
        GST_STIME_ARGS (ctx->out_running_time));
1111 1112 1113
  }
#endif

1114
  ctx->cur_out_buffer = NULL;
1115 1116
  GST_SPLITMUX_UNLOCK (splitmux);

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  /* pending_gap is protected by the STREAM lock */
  if (ctx->pending_gap) {
    /* If we previously stored a gap event, send it now */
    GstPad *peer = gst_pad_get_peer (ctx->srcpad);

    GST_DEBUG_OBJECT (splitmux,
        "Pad %" GST_PTR_FORMAT " sending pending GAP event", ctx->srcpad);

    gst_pad_send_event (peer, ctx->pending_gap);
    ctx->pending_gap = NULL;

    gst_object_unref (peer);
  }

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  mq_stream_buf_free (buf_info);

  return GST_PAD_PROBE_PASS;

beach:
  GST_SPLITMUX_UNLOCK (splitmux);
  return GST_PAD_PROBE_DROP;
}

static gboolean
resend_sticky (GstPad * pad, GstEvent ** event, GstPad * peer)
{
  return gst_pad_send_event (peer, gst_event_ref (*event));
}

static void
restart_context (MqStreamCtx * ctx, GstSplitMuxSink * splitmux)
{
  GstPad *peer = gst_pad_get_peer (ctx->srcpad);

  gst_pad_sticky_events_foreach (ctx->srcpad,
      (GstPadStickyEventsForeachFunction) (resend_sticky), peer);

1154 1155
  /* Clear EOS flag if not actually EOS */
  ctx->out_eos = GST_PAD_IS_EOS (ctx->srcpad);
1156 1157

  gst_object_unref (peer);
1158 1159 1160 1161 1162 1163 1164
}

/* Called with lock held when a fragment
 * reaches EOS and it is time to restart
 * a new fragment
 */
static void
1165
start_next_fragment (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
1166
{
1167 1168
  GstElement *muxer, *sink;

1169
  /* 1 change to new file */
1170 1171
  splitmux->switching_fragment = TRUE;

1172 1173 1174 1175 1176 1177 1178
  /* We need to drop the splitmux lock to acquire the state lock
   * here and ensure there's no racy state change going on elsewhere */
  muxer = gst_object_ref (splitmux->muxer);
  sink = gst_object_ref (splitmux->active_sink);

  GST_SPLITMUX_UNLOCK (splitmux);
  GST_STATE_LOCK (splitmux);
1179

1180 1181 1182 1183 1184 1185
  gst_element_set_locked_state (muxer, TRUE);
  gst_element_set_locked_state (sink, TRUE);
  gst_element_set_state (muxer, GST_STATE_NULL);
  gst_element_set_state (sink, GST_STATE_NULL);

  GST_SPLITMUX_LOCK (splitmux);
1186 1187 1188
  if (splitmux->muxed_out_bytes > 0 || splitmux->fragment_id == 0)
    set_next_filename (splitmux, ctx);
  splitmux->muxed_out_bytes = 0;
1189
  GST_SPLITMUX_UNLOCK (splitmux);
1190

1191 1192 1193 1194
  gst_element_set_state (sink, GST_STATE_TARGET (splitmux));
  gst_element_set_state (muxer, GST_STATE_TARGET (splitmux));
  gst_element_set_locked_state (muxer, FALSE);
  gst_element_set_locked_state (sink, FALSE);
1195

1196 1197 1198 1199 1200
  gst_object_unref (sink);
  gst_object_unref (muxer);

  GST_SPLITMUX_LOCK (splitmux);
  GST_STATE_UNLOCK (splitmux);
1201
  splitmux->switching_fragment = FALSE;
1202
  do_async_done (splitmux);
1203

1204
  splitmux->ready_for_output = TRUE;
1205

1206
  g_list_foreach (splitmux->contexts, (GFunc) restart_context, splitmux);
1207

1208 1209
  send_fragment_opened_closed_msg (splitmux, TRUE);

1210 1211 1212
  /* FIXME: Is this always the correct next state? */
  splitmux->output_state = SPLITMUX_OUTPUT_STATE_AWAITING_COMMAND;
  GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
}

static void
bus_handler (GstBin * bin, GstMessage * message)
{
  GstSplitMuxSink *splitmux = GST_SPLITMUX_SINK (bin);

  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_EOS:
      /* If the state is draining out the current file, drop this EOS */
      GST_SPLITMUX_LOCK (splitmux);
1224 1225 1226

      send_fragment_opened_closed_msg (splitmux, FALSE);

1227
      if (splitmux->output_state == SPLITMUX_OUTPUT_STATE_ENDING_FILE) {
1228
        GST_DEBUG_OBJECT (splitmux, "Caught EOS at end of fragment, dropping");
1229 1230
        splitmux->output_state = SPLITMUX_OUTPUT_STATE_START_NEXT_FILE;
        GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1231 1232 1233 1234

        gst_message_unref (message);
        GST_SPLITMUX_UNLOCK (splitmux);
        return;
1235 1236 1237 1238 1239
      } else {
        GST_DEBUG_OBJECT (splitmux,
            "Passing EOS message. Output state %d max_out_running_time %"
            GST_STIME_FORMAT, splitmux->output_state,
            GST_STIME_ARGS (splitmux->max_out_running_time));
1240 1241 1242
      }
      GST_SPLITMUX_UNLOCK (splitmux);
      break;
1243 1244 1245 1246
    case GST_MESSAGE_ASYNC_START:
    case GST_MESSAGE_ASYNC_DONE:
      /* Ignore state changes from our children while switching */
      if (splitmux->switching_fragment) {
1247 1248
        if (GST_MESSAGE_SRC (message) == (GstObject *) splitmux->active_sink
            || GST_MESSAGE_SRC (message) == (GstObject *) splitmux->muxer) {
1249 1250 1251 1252 1253 1254 1255 1256
          GST_LOG_OBJECT (splitmux,
              "Ignoring state change from child %" GST_PTR_FORMAT
              " while switching", GST_MESSAGE_SRC (message));
          gst_message_unref (message);
          return;
        }
      }
      break;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    case GST_MESSAGE_WARNING:
    {
      GError *gerror = NULL;

      gst_message_parse_warning (message, &gerror, NULL);

      if (g_error_matches (gerror, GST_STREAM_ERROR, GST_STREAM_ERROR_FORMAT)) {
        GList *item;
        gboolean caps_change = FALSE;

        GST_SPLITMUX_LOCK (splitmux);

        for (item = splitmux->contexts; item; item = item->next) {
          MqStreamCtx *ctx = item->data;

          if (ctx->caps_change) {
            caps_change = TRUE;
            break;
          }
        }

        GST_SPLITMUX_UNLOCK (splitmux);

        if (caps_change) {
          GST_LOG_OBJECT (splitmux,
              "Ignoring warning change from child %" GST_PTR_FORMAT
              " while switching caps", GST_MESSAGE_SRC (message));
          gst_message_unref (message);
          return;
        }
      }
      break;
    }
1290 1291 1292 1293 1294 1295 1296
    default:
      break;
  }

  GST_BIN_CLASS (parent_class)->handle_message (bin, message);
}

1297 1298 1299 1300 1301 1302
static void
ctx_set_unblock (MqStreamCtx * ctx)
{
  ctx->need_unblock = TRUE;
}

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
static gboolean
need_new_fragment (GstSplitMuxSink * splitmux,
    GstClockTime queued_time, GstClockTime queued_gop_time,
    guint64 queued_bytes)
{
  guint64 thresh_bytes;
  GstClockTime thresh_time;
  gboolean check_robust_muxing;

  GST_OBJECT_LOCK (splitmux);
  thresh_bytes = splitmux->threshold_bytes;
  thresh_time = splitmux->threshold_time;
  check_robust_muxing = splitmux->use_robust_muxing
      && splitmux->muxer_has_reserved_props;
  GST_OBJECT_UNLOCK (splitmux);

  /* Have we muxed anything into the new file at all? */
  if (splitmux->fragment_total_bytes <= 0)
    return FALSE;

1323 1324 1325 1326
  /* User told us to split now */
  if (g_atomic_int_get (&(splitmux->split_now)) == TRUE)
    return TRUE;

1327
  if (thresh_bytes > 0 && queued_bytes > thresh_bytes)
1328 1329
    return TRUE;                /* Would overrun byte limit */

1330
  if (thresh_time > 0 && queued_time > thresh_time)
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    return TRUE;                /* Would overrun byte limit */

  /* Timecode-based threshold accounts for possible rounding errors:
   * 5us should be bigger than all possible rounding errors but nowhere near
   * big enough to skip to another frame */
  if (splitmux->next_max_tc_time != GST_CLOCK_TIME_NONE &&
      splitmux->reference_ctx->in_running_time >
      splitmux->next_max_tc_time + 5 * GST_USECOND)
    return TRUE;                /* Timecode threshold */

  if (check_robust_muxing) {
    GstClockTime mux_reserved_remain;

    g_object_get (splitmux->muxer,
        "reserved-duration-remaining", &mux_reserved_remain, NULL);

    GST_LOG_OBJECT (splitmux,
        "Muxer robust muxing report - %" G_GUINT64_FORMAT
        " remaining. New GOP would enqueue %" G_GUINT64_FORMAT,
        mux_reserved_remain, queued_gop_time);

    if (queued_gop_time >= mux_reserved_remain) {
      GST_INFO_OBJECT (splitmux,
          "File is about to run out of header room - %" G_GUINT64_FORMAT
          " remaining. New GOP would enqueue %" G_GUINT64_FORMAT
          ". Switching to new file", mux_reserved_remain, queued_gop_time);
      return TRUE;
    }
  }

  /* Continue and mux this GOP */
  return FALSE;
}

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
/* Called with splitmux lock held */
/* Called when entering ProcessingCompleteGop state
 * Assess if mq contents overflowed the current file
 *   -> If yes, need to switch to new file
 *   -> if no, set max_out_running_time to let this GOP in and
 *      go to COLLECTING_GOP_START state
 */
static void
handle_gathered_gop (GstSplitMuxSink * splitmux)
{
1375
  guint64 queued_bytes;
1376
  GstClockTimeDiff queued_time = 0;
1377
  GstClockTimeDiff queued_gop_time = 0;
1378 1379
  GstClockTimeDiff new_out_ts = splitmux->reference_ctx->in_running_time;
  SplitMuxOutputCommand *cmd;
1380 1381

  /* Assess if the multiqueue contents overflowed the current file */
1382 1383 1384 1385 1386 1387 1388
  /* When considering if a newly gathered GOP overflows
   * the time limit for the file, only consider the running time of the
   * reference stream. Other streams might have run ahead a little bit,
   * but extra pieces won't be released to the muxer beyond the reference
   * stream cut-off anyway - so it forms the limit. */
  queued_bytes = splitmux->fragment_total_bytes + splitmux->gop_total_bytes;
  queued_time = splitmux->reference_ctx->in_running_time;
1389 1390 1391 1392 1393 1394 1395 1396 1397
  /* queued_gop_time tracks how much unwritten data there is waiting to
   * be written to this fragment including this GOP */
  if (splitmux->reference_ctx->out_running_time != GST_CLOCK_STIME_NONE)
    queued_gop_time =
        splitmux->reference_ctx->in_running_time -
        splitmux->reference_ctx->out_running_time;
  else
    queued_gop_time =
        splitmux->reference_ctx->in_running_time - splitmux->gop_start_time;
1398 1399

  GST_LOG_OBJECT (splitmux, " queued_bytes %" G_GUINT64_FORMAT, queued_bytes);
1400

1401
  g_assert (queued_gop_time >= 0);
1402
  g_assert (queued_time >= splitmux->fragment_start_time);
1403

1404
  queued_time -= splitmux->fragment_start_time;
1405 1406
  if (queued_time < queued_gop_time)
    queued_gop_time = queued_time;
1407 1408 1409 1410

  /* Expand queued bytes estimate by muxer overhead */
  queued_bytes += (queued_bytes * splitmux->mux_overhead);

1411
  GST_LOG_OBJECT (splitmux, "mq at TS %" GST_STIME_FORMAT
1412
      " bytes %" G_GUINT64_FORMAT, GST_STIME_ARGS (queued_time), queued_bytes);
1413 1414 1415 1416 1417 1418
  if (splitmux->next_max_tc_time != GST_CLOCK_TIME_NONE) {
    GST_LOG_OBJECT (splitmux,
        "timecode mq TS %" GST_TIME_FORMAT " vs target %" GST_TIME_FORMAT,
        GST_TIME_ARGS (splitmux->reference_ctx->in_running_time),
        GST_TIME_ARGS (splitmux->next_max_tc_time + 5 * GST_USECOND));
  }
1419 1420 1421

  /* Check for overrun - have we output at least one byte and overrun
   * either threshold? */
1422
  if (need_new_fragment (splitmux, queued_time, queued_gop_time, queued_bytes)) {
1423
    g_atomic_int_set (&(splitmux->split_now), FALSE);
1424
    /* Tell the output side to start a new fragment */
1425
    GST_INFO_OBJECT (splitmux,
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
        "This GOP (dur %" GST_STIME_FORMAT
        ") would overflow the fragment, Sending start_new_fragment cmd",
        GST_STIME_ARGS (splitmux->reference_ctx->in_running_time -
            splitmux->gop_start_time));
    cmd = out_cmd_buf_new ();
    cmd->start_new_fragment = TRUE;
    g_queue_push_head (&splitmux->out_cmd_q, cmd);
    GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);

    new_out_ts = splitmux->reference_ctx->in_running_time;
    splitmux->fragment_start_time = splitmux->gop_start_time;
    splitmux->fragment_total_bytes = 0;

1439 1440
    if (request_next_keyframe (splitmux,
            splitmux->reference_ctx->prev_in_keyframe) == FALSE) {
1441 1442 1443
      GST_WARNING_OBJECT (splitmux,
          "Could not request a keyframe. Files may not split at the exact location they should");
    }
1444
    gst_buffer_replace (&splitmux->reference_ctx->prev_in_keyframe, NULL);
1445
  }
1446

1447 1448 1449 1450
  /* And set up to collect the next GOP */
  if (!splitmux->reference_ctx->in_eos) {
    splitmux->input_state = SPLITMUX_INPUT_STATE_COLLECTING_GOP_START;
    splitmux->gop_start_time = new_out_ts;
1451
  } else {
1452 1453 1454 1455
    /* This is probably already the current state, but just in case: */
    splitmux->input_state = SPLITMUX_INPUT_STATE_FINISHING_UP;
    new_out_ts = GST_CLOCK_STIME_NONE;  /* EOS runs until forever */
  }
1456

1457 1458 1459
  /* And wake all input contexts to send a wake-up event */
  g_list_foreach (splitmux->contexts, (GFunc) ctx_set_unblock, NULL);
  GST_SPLITMUX_BROADCAST_INPUT (splitmux);
1460

1461 1462
  /* Now either way - either there was no overflow, or we requested a new fragment: release this GOP */
  splitmux->fragment_total_bytes += splitmux->gop_total_bytes;
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
  if (splitmux->gop_total_bytes > 0) {
    GST_LOG_OBJECT (splitmux,
        "Releasing GOP to output. Bytes in fragment now %" G_GUINT64_FORMAT
        " time %" GST_STIME_FORMAT,
        splitmux->fragment_total_bytes, GST_STIME_ARGS (queued_time));

    /* Send this GOP to the output command queue */
    cmd = out_cmd_buf_new ();
    cmd->start_new_fragment = FALSE;
    cmd->max_output_ts = new_out_ts;
    GST_LOG_OBJECT (splitmux, "Sending GOP cmd to output for TS %"
        GST_STIME_FORMAT, GST_STIME_ARGS (new_out_ts));
    g_queue_push_head (&splitmux->out_cmd_q, cmd);

    GST_SPLITMUX_BROADCAST_OUTPUT (splitmux);
1479 1480
  }

1481
  splitmux->gop_total_bytes = 0;
1482 1483 1484 1485
}

/* Called with splitmux lock held */
/* Called from each input pad when it is has all the pieces
1486
 * for a GOP or EOS, starting with the reference pad which has set the
1487 1488 1489 1490 1491 1492
 * splitmux->max_in_running_time
 */
static void
check_completed_gop (GstSplitMuxSink * splitmux, MqStreamCtx * ctx)
{
  GList *cur;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
  GstEvent *event;

  /* On ENDING_FILE, the reference stream sends a command to start a new
   * fragment, then releases the GOP for output in the new fragment.
   *  If somes streams received no buffer during the last GOP that overran,
   * because its next buffer has a timestamp bigger than
   * ctx->max_in_running_time, its queue is empty. In that case the only
   * way to wakeup the output thread is by injecting an event in the
   * queue. This usually happen with subtitle streams.
   * See https://bugzilla.gnome.org/show_bug.cgi?id=763711. */
  if (ctx->need_unblock) {
    GST_LOG_OBJECT (ctx->sinkpad, "Sending splitmuxsink-unblock event");
    event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM |
        GST_EVENT_TYPE_SERIALIZED,
        gst_structure_new ("splitmuxsink-unblock", "timestamp",
            G_TYPE_INT64, splitmux->max_in_running_time, NULL));

    GST_SPLITMUX_UNLOCK (splitmux);
    gst_pad_send_event (ctx->sinkpad, event);
    GST_SPLITMUX_LOCK (splitmux);

    ctx->need_unblock = FALSE;
    GST_SPLITMUX_BROADCAST_INPUT (splitmux);
    /* state may have changed while we were unlocked. Loop again if so */
    if (splitmux->input_state != SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT)
      return;
  }

  if (splitmux->input_state == SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT) {
    gboolean ready = TRUE;
1523 1524

    /* Iterate each pad, and check that the input running time is at least
1525
     * up to the reference running time, and if so handle the collected GOP */
1526
    GST_LOG_OBJECT (splitmux, "Checking GOP collected, Max in running time %"
1527 1528
        GST_STIME_FORMAT " ctx %p",
        GST_STIME_ARGS (splitmux->max_in_running_time), ctx);
1529 1530
    for (cur = g_list_first (splitmux->contexts); cur != NULL;
        cur = g_list_next (cur)) {
1531 1532 1533
      MqStreamCtx *tmpctx = (MqStreamCtx *) (cur->data);

      GST_LOG_OBJECT (splitmux,
1534
          "Context %p (src pad %" GST_PTR_FORMAT ") TS %" GST_STIME_FORMAT
1535
          " EOS %d", tmpctx, tmpctx->srcpad,
1536
          GST_STIME_ARGS (tmpctx->in_running_time), tmpctx->in_eos);
1537

1538
      if (splitmux->max_in_running_time != GST_CLOCK_STIME_NONE &&
1539
          tmpctx->in_running_time < splitmux->max_in_running_time &&
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
          !tmpctx->in_eos) {
        GST_LOG_OBJECT (splitmux,
            "Context %p (src pad %" GST_PTR_FORMAT ") not ready. We'll sleep",
            tmpctx, tmpctx->srcpad);
        ready = FALSE;
        break;
      }
    }
    if (ready) {
      GST_DEBUG_OBJECT (splitmux,
          "Collected GOP is complete. Processing (ctx %p)", ctx);
      /* All pads have a complete GOP, release it into the multiqueue */
      handle_gathered_gop (splitmux);
    }
  }

1556 1557 1558 1559 1560
  /* If upstream reached EOS we are not expecting more data, no need to wait
   * here. */
  if (ctx->in_eos)
    return;

1561 1562
  /* Some pad is not yet ready, or GOP is being pushed
   * either way, sleep and wait to get woken */
1563
  while (splitmux->input_state == SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT &&
1564
      !ctx->flushing &&
1565 1566
      (ctx->in_running_time >= splitmux->max_in_running_time) &&
      (splitmux->max_in_running_time != GST_CLOCK_STIME_NONE)) {
1567

1568 1569
    GST_LOG_OBJECT (splitmux, "Sleeping for GOP collection (ctx %p)", ctx);
    GST_SPLITMUX_WAIT_INPUT (splitmux);
1570 1571 1572 1573 1574 1575 1576 1577 1578
    GST_LOG_OBJECT (splitmux, "Done waiting for complete GOP (ctx %p)", ctx);
  }
}

static GstPadProbeReturn
handle_mq_input (GstPad * pad, GstPadProbeInfo * info, MqStreamCtx * ctx)
{
  GstSplitMuxSink *splitmux = ctx->splitmux;
  GstBuffer *buf;
1579
  MqStreamBuf *buf_info = NULL;
1580 1581 1582 1583
  GstClockTime ts;
  gboolean loop_again;
  gboolean keyframe = FALSE;

1584
  GST_LOG_OBJECT (pad, "Fired probe type 0x%x", info->type);
1585 1586 1587 1588 1589 1590

  /* FIXME: Handle buffer lists, until then make it clear they won't work */
  if (info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST) {
    g_warning ("Buffer list handling not implemented");
    return GST_PAD_PROBE_DROP;
  }
1591 1592
  if (info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM ||
      info->type & GST_PAD_PROBE_TYPE_EVENT_FLUSH) {
1593
    GstEvent *event = gst_pad_probe_info_get_event (info);
1594 1595 1596

    GST_LOG_OBJECT (pad, "Event %" GST_PTR_FORMAT, event);

1597 1598 1599 1600 1601 1602 1603 1604
    switch (GST_EVENT_TYPE (event)) {
      case GST_EVENT_SEGMENT:
        gst_event_copy_segment (event, &ctx->in_segment);
        break;
      case GST_EVENT_FLUSH_STOP:
        GST_SPLITMUX_LOCK (splitmux);
        gst_segment_init (&ctx->in_segment, GST_FORMAT_UNDEFINED);
        ctx->in_eos = FALSE;
1605
        ctx->in_running_time = GST_CLOCK_STIME_NONE;
1606 1607 1608 1609 1610 1611
        GST_SPLITMUX_UNLOCK (splitmux);
        break;
      case GST_EVENT_EOS:
        GST_SPLITMUX_LOCK (splitmux);
        ctx->in_eos = TRUE;

1612
        if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED)
1613 1614
          goto beach;

1615 1616
        if (ctx->is_reference) {
          GST_INFO_OBJECT (splitmux, "Got Reference EOS. Finishing up");
1617 1618
          /* check_completed_gop will act as if this is a new keyframe with infinite timestamp */
          splitmux->input_state = SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT;
1619
          /* Wake up other input pads to collect this GOP */
1620
          GST_SPLITMUX_BROADCAST_INPUT (splitmux);
1621
          check_completed_gop (splitmux, ctx);
1622 1623
        } else if (splitmux->input_state ==
            SPLITMUX_INPUT_STATE_WAITING_GOP_COLLECT) {
1624 1625 1626 1627 1628 1629 1630 1631
          /* If we are waiting for a GOP to be completed (ie, for aux
           * pads to catch up), then this pad is complete, so check
           * if the whole GOP is.
           */
          check_completed_gop (splitmux, ctx);
        }
        GST_SPLITMUX_UNLOCK (splitmux);
        break;
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
      case GST_EVENT_GAP:{
        GstClockTime gap_ts;
        GstClockTimeDiff rtime;

        gst_event_parse_gap (event, &gap_ts, NULL);
        if (gap_ts == GST_CLOCK_TIME_NONE)
          break;

        GST_SPLITMUX_LOCK (splitmux);

        if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED)
          goto beach;
        rtime = my_segment_to_running_time (&ctx->in_segment, gap_ts);

        GST_LOG_OBJECT (pad, "Have GAP w/ ts %" GST_STIME_FORMAT,
            GST_STIME_ARGS (rtime));

        if (ctx->is_reference
            && splitmux->fragment_start_time == GST_CLOCK_STIME_NONE) {
          splitmux->gop_start_time = splitmux->fragment_start_time = rtime;
          GST_LOG_OBJECT (splitmux, "Mux start time now %" GST_STIME_FORMAT,
              GST_STIME_ARGS (splitmux->fragment_start_time));
          /* Also take this as the first start time when starting up,
           * so that we start counting overflow from the first frame */
          if (!GST_CLOCK_STIME_IS_VALID (splitmux->max_in_running_time))
            splitmux->max_in_running_time = splitmux->fragment_start_time;
        }

        GST_SPLITMUX_UNLOCK (splitmux);
        break;
      }
1663 1664 1665 1666
      default:
        break;
    }
    return GST_PAD_PROBE_PASS;
1667 1668 1669 1670 1671 1672 1673
  } else if (info->type & GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM) {
    switch (GST_QUERY_TYPE (GST_QUERY (info->data))) {
      case GST_QUERY_ALLOCATION:
        return GST_PAD_PROBE_DROP;
      default:
        return GST_PAD_PROBE_PASS;
    }
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
  }

  buf = gst_pad_probe_info_get_buffer (info);
  buf_info = mq_stream_buf_new ();

  if (GST_BUFFER_PTS_IS_VALID (buf))
    ts = GST_BUFFER_PTS (buf);
  else
    ts = GST_BUFFER_DTS (buf);

1684
  GST_LOG_OBJECT (pad, "Buffer TS is %" GST_TIME_FORMAT, GST_TIME_ARGS (ts));
1685

1686 1687
  GST_SPLITMUX_LOCK (splitmux);

1688
  if (splitmux->input_state == SPLITMUX_INPUT_STATE_STOPPED)
1689 1690 1691 1692 1693
    goto beach;

  /* If this buffer has a timestamp, advance the input timestamp of the
   * stream */
  if (GST_CLOCK_TIME_IS_VALID (ts)) {
1694
    GstClockTimeDiff running_time =
1695
        my_segment_to_running_time (&ctx->in_segment, ts);
1696

1697 1698 1699 1700 1701
    GST_LOG_OBJECT (pad, "Buffer running TS is %" GST_STIME_FORMAT,
        GST_STIME_ARGS (running_time));

    if (GST_CLOCK_STIME_IS_VALID (running_time)
        && running_time > ctx->in_running_time)
1702 1703 1704 1705
      ctx->in_running_time = running_time;
  }

  /* Try to make sure we have a valid running time */
1706
  if (!GST_CLOCK_STIME_IS_VALID (ctx->in_running_time)) {
1707
    ctx->in_running_time =
1708
        my_segment_to_running_time (&ctx->in_segment, ctx->in_segment.start);
1709 1710
  }

1711 1712 1713
  GST_LOG_OBJECT (pad, "in running time now %" GST_STIME_FORMAT,
      GST_STIME_ARGS (ctx->in_running_time));

1714 1715
  buf_info->run_ts = ctx->in_running_time;
  buf_info->buf_size = gst_buffer_get_size (buf);
1716
  buf_info->duration = GST_BUFFER_DURATION (buf);
1717