gstmultifilesink.c 34.2 KB
Newer Older
David Schleef's avatar
David Schleef committed
1
2
3
4
5
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2000 Wim Taymans <wtay@chello.be>
 *                    2006 Wim Taymans <wim@fluendo.com>
 *                    2006 David A. Schleef <ds@schleef.org>
6
 *                    2011 Collabora Ltd. <tim.muller@collabora.co.uk>
7
 *                    2015 Tim-Philipp Müller <tim@centricular.com>
David Schleef's avatar
David Schleef committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * gstmultifilesink.c:
 *
 * 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
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
23
24
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
David Schleef's avatar
David Schleef committed
25
26
27
28
29
 */
/**
 * SECTION:element-multifilesink
 * @see_also: #GstFileSrc
 *
30
 * Write incoming data to a series of sequentially-named files.
31
 *
32
33
34
35
36
37
38
39
 * This element is usually used with data where each buffer is an
 * independent unit of data in its own right (e.g. raw video buffers or
 * encoded JPEG or PNG images) or with streamable container formats such
 * as MPEG-TS or MPEG-PS.
 *
 * It is not possible to use this element to create independently playable
 * mp4 files, use the splitmuxsink element for that instead.
 *
Stefan Kost's avatar
Stefan Kost committed
40
 * The filename property should contain a string with a \%d placeholder that will
41
42
 * be substituted with the index for each filename.
 *
43
 * If the #GstMultiFileSink:post-messages property is #TRUE, it sends an application
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
 * message named
 * <classname>&quot;GstMultiFileSink&quot;</classname> after writing each
 * buffer.
 *
 * The message's structure contains these fields:
 * <itemizedlist>
 * <listitem>
 *   <para>
 *   #gchar *
 *   <classname>&quot;filename&quot;</classname>:
 *   the filename where the buffer was written.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #gint
 *   <classname>&quot;index&quot;</classname>:
 *   the index of the buffer.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #GstClockTime
 *   <classname>&quot;timestamp&quot;</classname>:
 *   the timestamp of the buffer.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #GstClockTime
 *   <classname>&quot;stream-time&quot;</classname>:
 *   the stream time of the buffer.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #GstClockTime
 *   <classname>&quot;running-time&quot;</classname>:
 *   the running_time of the buffer.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #GstClockTime
 *   <classname>&quot;duration&quot;</classname>:
 *   the duration of the buffer.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #guint64
 *   <classname>&quot;offset&quot;</classname>:
 *   the offset of the buffer that triggered the message.
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
 *   #guint64
 *   <classname>&quot;offset-end&quot;</classname>:
 *   the offset-end of the buffer that triggered the message.
 *   </para>
 * </listitem>
 * </itemizedlist>
 *
 * <refsect2>
Stefan Kost's avatar
Stefan Kost committed
109
 * <title>Example launch line</title>
110
 * |[
111
112
 * gst-launch-1.0 audiotestsrc ! multifilesink
 * gst-launch-1.0 videotestsrc ! multifilesink post-messages=true filename="frame%d"
113
114
 * ]|
 * </refsect2>
David Schleef's avatar
David Schleef committed
115
116
117
118
119
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
120
#include <gst/base/gstbasetransform.h>
121
#include <gst/video/video.h>
122
#include <glib/gstdio.h>
123
#include "gstmultifilesink.h"
David Schleef's avatar
David Schleef committed
124
125
126
127
128
129
130
131
132

static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

GST_DEBUG_CATEGORY_STATIC (gst_multi_file_sink_debug);
#define GST_CAT_DEFAULT gst_multi_file_sink_debug

133
134
#define DEFAULT_LOCATION "%05d"
#define DEFAULT_INDEX 0
135
#define DEFAULT_POST_MESSAGES FALSE
136
#define DEFAULT_NEXT_FILE GST_MULTI_FILE_SINK_NEXT_BUFFER
137
#define DEFAULT_MAX_FILES 0
138
#define DEFAULT_MAX_FILE_SIZE G_GUINT64_CONSTANT(2*1024*1024*1024)
139
#define DEFAULT_MAX_FILE_DURATION GST_CLOCK_TIME_NONE
140
#define DEFAULT_AGGREGATE_GOPS FALSE
141

David Schleef's avatar
David Schleef committed
142
143
enum
{
144
145
146
  PROP_0,
  PROP_LOCATION,
  PROP_INDEX,
147
  PROP_POST_MESSAGES,
148
  PROP_NEXT_FILE,
149
  PROP_MAX_FILES,
150
  PROP_MAX_FILE_SIZE,
151
  PROP_MAX_FILE_DURATION,
152
  PROP_AGGREGATE_GOPS
David Schleef's avatar
David Schleef committed
153
154
};

155
static void gst_multi_file_sink_finalize (GObject * object);
David Schleef's avatar
David Schleef committed
156
157
158
159
160
161

static void gst_multi_file_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_multi_file_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

162
static gboolean gst_multi_file_sink_start (GstBaseSink * bsink);
163
static gboolean gst_multi_file_sink_stop (GstBaseSink * sink);
David Schleef's avatar
David Schleef committed
164
165
static GstFlowReturn gst_multi_file_sink_render (GstBaseSink * sink,
    GstBuffer * buffer);
166
167
static GstFlowReturn gst_multi_file_sink_render_list (GstBaseSink * sink,
    GstBufferList * buffer_list);
168
169
static gboolean gst_multi_file_sink_set_caps (GstBaseSink * sink,
    GstCaps * caps);
170
171
172
173
static gboolean gst_multi_file_sink_open_next_file (GstMultiFileSink *
    multifilesink);
static void gst_multi_file_sink_close_file (GstMultiFileSink * multifilesink,
    GstBuffer * buffer);
174
175
static void gst_multi_file_sink_ensure_max_files (GstMultiFileSink *
    multifilesink);
176
177
static gboolean gst_multi_file_sink_event (GstBaseSink * sink,
    GstEvent * event);
David Schleef's avatar
David Schleef committed
178

179
180
181
182
#define GST_TYPE_MULTI_FILE_SINK_NEXT (gst_multi_file_sink_next_get_type ())
static GType
gst_multi_file_sink_next_get_type (void)
{
183
  static GType multi_file_sink_next_type = 0;
184
185
186
187
  static const GEnumValue next_types[] = {
    {GST_MULTI_FILE_SINK_NEXT_BUFFER, "New file for each buffer", "buffer"},
    {GST_MULTI_FILE_SINK_NEXT_DISCONT, "New file after each discontinuity",
        "discont"},
188
189
    {GST_MULTI_FILE_SINK_NEXT_KEY_FRAME, "New file at each key frame "
          "(Useful for MPEG-TS segmenting)", "key-frame"},
190
191
    {GST_MULTI_FILE_SINK_NEXT_KEY_UNIT_EVENT,
        "New file after a force key unit event", "key-unit-event"},
192
193
194
    {GST_MULTI_FILE_SINK_NEXT_MAX_SIZE, "New file when the configured maximum "
          "file size would be exceeded with the next buffer or buffer list",
        "max-size"},
195
196
197
198
    {GST_MULTI_FILE_SINK_NEXT_MAX_DURATION,
          "New file when the configured maximum "
          "file duration would be exceeded with the next buffer or buffer list",
        "max-duration"},
199
200
201
    {0, NULL, NULL}
  };

202
203
  if (!multi_file_sink_next_type) {
    multi_file_sink_next_type =
204
205
206
        g_enum_register_static ("GstMultiFileSinkNext", next_types);
  }

207
  return multi_file_sink_next_type;
208
209
}

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
210
211
#define gst_multi_file_sink_parent_class parent_class
G_DEFINE_TYPE (GstMultiFileSink, gst_multi_file_sink, GST_TYPE_BASE_SINK);
David Schleef's avatar
David Schleef committed
212
213
214
215
216

static void
gst_multi_file_sink_class_init (GstMultiFileSinkClass * klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
217
  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
David Schleef's avatar
David Schleef committed
218
219
220
221
222
  GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);

  gobject_class->set_property = gst_multi_file_sink_set_property;
  gobject_class->get_property = gst_multi_file_sink_get_property;

223
  g_object_class_install_property (gobject_class, PROP_LOCATION,
David Schleef's avatar
David Schleef committed
224
      g_param_spec_string ("location", "File Location",
225
226
          "Location of the file to write", NULL,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
227
228

  g_object_class_install_property (gobject_class, PROP_INDEX,
229
230
      g_param_spec_int ("index", "Index",
          "Index to use with location property to create file names.  The "
231
          "index is incremented by one for each buffer written.",
232
233
          0, G_MAXINT, DEFAULT_INDEX,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
234
  /**
235
   * GstMultiFileSink:post-messages:
236
237
238
   *
   * Post a message on the GstBus for each file.
   */
239
240
241
  g_object_class_install_property (gobject_class, PROP_POST_MESSAGES,
      g_param_spec_boolean ("post-messages", "Post Messages",
          "Post a message for each file with information of the buffer",
242
          DEFAULT_POST_MESSAGES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
243
  /**
244
   * GstMultiFileSink:next-file:
245
246
247
248
249
250
251
   *
   * When to start a new file.
   */
  g_object_class_install_property (gobject_class, PROP_NEXT_FILE,
      g_param_spec_enum ("next-file", "Next File",
          "When to start a new file",
          GST_TYPE_MULTI_FILE_SINK_NEXT, DEFAULT_NEXT_FILE,
252
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
253

254
255

  /**
256
   * GstMultiFileSink:max-files:
257
258
259
260
261
262
263
264
265
266
267
   *
   * Maximum number of files to keep on disk. Once the maximum is reached, old
   * files start to be deleted to make room for new ones.
   */
  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,"
          "old files start to be deleted to make room for new ones.",
          0, G_MAXUINT, DEFAULT_MAX_FILES,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

268
  /**
269
   * GstMultiFileSink:max-file-size:
270
271
272
273
274
275
276
277
278
   *
   * Maximum file size before starting a new file in max-size mode.
   */
  g_object_class_install_property (gobject_class, PROP_MAX_FILE_SIZE,
      g_param_spec_uint64 ("max-file-size", "Maximum File Size",
          "Maximum file size before starting a new file in max-size mode",
          0, G_MAXUINT64, DEFAULT_MAX_FILE_SIZE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

279
280
281
282
283
284
285
286
287
288
289
  /**
   * GstMultiFileSink:max-file-duration:
   *
   * Maximum file size before starting a new file in max-size mode.
   */
  g_object_class_install_property (gobject_class, PROP_MAX_FILE_DURATION,
      g_param_spec_uint64 ("max-file-duration", "Maximum File Duration",
          "Maximum file duration before starting a new file in max-size mode",
          0, G_MAXUINT64, DEFAULT_MAX_FILE_DURATION,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
  /**
   * GstMultiFileSink:aggregate-gops:
   *
   * Whether to aggregate complete GOPs before doing any processing. Set this
   * to TRUE to make sure each new file starts with a keyframe. This requires
   * the upstream element to flag buffers containing key units and delta
   * units correctly. At least the MPEG-PS and MPEG-TS muxers should be doing
   * this.
   *
   * Since: 1.6
   */
  g_object_class_install_property (gobject_class, PROP_AGGREGATE_GOPS,
      g_param_spec_boolean ("aggregate-gops", "Aggregate GOPs",
          "Whether to aggregate GOPs and process them as a whole without "
          "splitting", DEFAULT_AGGREGATE_GOPS,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

307
  gobject_class->finalize = gst_multi_file_sink_finalize;
David Schleef's avatar
David Schleef committed
308

309
  gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_multi_file_sink_start);
310
  gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_multi_file_sink_stop);
David Schleef's avatar
David Schleef committed
311
  gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_multi_file_sink_render);
312
313
  gstbasesink_class->render_list =
      GST_DEBUG_FUNCPTR (gst_multi_file_sink_render_list);
314
315
  gstbasesink_class->set_caps =
      GST_DEBUG_FUNCPTR (gst_multi_file_sink_set_caps);
316
  gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_multi_file_sink_event);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
317
318
319
320
321
322

  GST_DEBUG_CATEGORY_INIT (gst_multi_file_sink_debug, "multifilesink", 0,
      "multifilesink element");

  gst_element_class_add_pad_template (gstelement_class,
      gst_static_pad_template_get (&sinktemplate));
323
  gst_element_class_set_static_metadata (gstelement_class, "Multi-File Sink",
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
324
325
326
      "Sink/File",
      "Write buffers to a sequentially named set of files",
      "David Schleef <ds@schleef.org>");
David Schleef's avatar
David Schleef committed
327
328
329
}

static void
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
330
gst_multi_file_sink_init (GstMultiFileSink * multifilesink)
David Schleef's avatar
David Schleef committed
331
{
332
333
  multifilesink->filename = g_strdup (DEFAULT_LOCATION);
  multifilesink->index = DEFAULT_INDEX;
334
  multifilesink->post_messages = DEFAULT_POST_MESSAGES;
335
  multifilesink->max_files = DEFAULT_MAX_FILES;
336
  multifilesink->max_file_size = DEFAULT_MAX_FILE_SIZE;
337
  multifilesink->max_file_duration = DEFAULT_MAX_FILE_DURATION;
338
339
  multifilesink->files = NULL;
  multifilesink->n_files = 0;
David Schleef's avatar
David Schleef committed
340

341
342
343
  multifilesink->aggregate_gops = DEFAULT_AGGREGATE_GOPS;
  multifilesink->gop_adapter = NULL;

344
  gst_base_sink_set_sync (GST_BASE_SINK (multifilesink), FALSE);
345
346

  multifilesink->next_segment = GST_CLOCK_TIME_NONE;
347
  multifilesink->force_key_unit_count = -1;
David Schleef's avatar
David Schleef committed
348
349
350
}

static void
351
gst_multi_file_sink_finalize (GObject * object)
David Schleef's avatar
David Schleef committed
352
353
354
355
{
  GstMultiFileSink *sink = GST_MULTI_FILE_SINK (object);

  g_free (sink->filename);
356
357
  g_slist_foreach (sink->files, (GFunc) g_free, NULL);
  g_slist_free (sink->files);
358

359
  G_OBJECT_CLASS (parent_class)->finalize (object);
David Schleef's avatar
David Schleef committed
360
361
362
363
364
365
366
}

static gboolean
gst_multi_file_sink_set_location (GstMultiFileSink * sink,
    const gchar * location)
{
  g_free (sink->filename);
367
368
  /* FIXME: validate location to have just one %d */
  sink->filename = g_strdup (location);
David Schleef's avatar
David Schleef committed
369
370
371

  return TRUE;
}
372

David Schleef's avatar
David Schleef committed
373
374
375
376
377
378
379
static void
gst_multi_file_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstMultiFileSink *sink = GST_MULTI_FILE_SINK (object);

  switch (prop_id) {
380
    case PROP_LOCATION:
David Schleef's avatar
David Schleef committed
381
382
      gst_multi_file_sink_set_location (sink, g_value_get_string (value));
      break;
383
    case PROP_INDEX:
384
385
      sink->index = g_value_get_int (value);
      break;
386
387
    case PROP_POST_MESSAGES:
      sink->post_messages = g_value_get_boolean (value);
388
      break;
389
390
391
    case PROP_NEXT_FILE:
      sink->next_file = g_value_get_enum (value);
      break;
392
393
394
    case PROP_MAX_FILES:
      sink->max_files = g_value_get_uint (value);
      break;
395
396
397
    case PROP_MAX_FILE_SIZE:
      sink->max_file_size = g_value_get_uint64 (value);
      break;
398
399
400
    case PROP_MAX_FILE_DURATION:
      sink->max_file_duration = g_value_get_uint64 (value);
      break;
401
402
403
    case PROP_AGGREGATE_GOPS:
      sink->aggregate_gops = g_value_get_boolean (value);
      break;
David Schleef's avatar
David Schleef committed
404
405
406
407
408
409
410
411
412
413
414
415
416
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_multi_file_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstMultiFileSink *sink = GST_MULTI_FILE_SINK (object);

  switch (prop_id) {
417
    case PROP_LOCATION:
David Schleef's avatar
David Schleef committed
418
419
      g_value_set_string (value, sink->filename);
      break;
420
    case PROP_INDEX:
421
422
      g_value_set_int (value, sink->index);
      break;
423
424
    case PROP_POST_MESSAGES:
      g_value_set_boolean (value, sink->post_messages);
425
      break;
426
427
428
    case PROP_NEXT_FILE:
      g_value_set_enum (value, sink->next_file);
      break;
429
430
431
    case PROP_MAX_FILES:
      g_value_set_uint (value, sink->max_files);
      break;
432
433
434
    case PROP_MAX_FILE_SIZE:
      g_value_set_uint64 (value, sink->max_file_size);
      break;
435
436
437
    case PROP_MAX_FILE_DURATION:
      g_value_set_uint64 (value, sink->max_file_duration);
      break;
438
439
440
    case PROP_AGGREGATE_GOPS:
      g_value_set_boolean (value, sink->aggregate_gops);
      break;
David Schleef's avatar
David Schleef committed
441
442
443
444
445
446
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

447
448
449
450
451
452
453
454
static gboolean
gst_multi_file_sink_start (GstBaseSink * bsink)
{
  GstMultiFileSink *sink = GST_MULTI_FILE_SINK (bsink);

  if (sink->aggregate_gops)
    sink->gop_adapter = gst_adapter_new ();
  sink->potential_next_gop = NULL;
455
  sink->file_pts = GST_CLOCK_TIME_NONE;
456
457
458
459

  return TRUE;
}

460
461
static gboolean
gst_multi_file_sink_stop (GstBaseSink * sink)
David Schleef's avatar
David Schleef committed
462
{
463
  GstMultiFileSink *multifilesink;
464
  int i;
David Schleef's avatar
David Schleef committed
465

466
  multifilesink = GST_MULTI_FILE_SINK (sink);
David Schleef's avatar
David Schleef committed
467

468
469
470
471
  if (multifilesink->file != NULL) {
    fclose (multifilesink->file);
    multifilesink->file = NULL;
  }
472

473
474
475
476
477
  if (multifilesink->streamheaders) {
    for (i = 0; i < multifilesink->n_streamheaders; i++) {
      gst_buffer_unref (multifilesink->streamheaders[i]);
    }
    g_free (multifilesink->streamheaders);
478
    multifilesink->streamheaders = NULL;
479
480
  }

481
482
483
484
485
486
487
488
489
490
491
  if (multifilesink->gop_adapter != NULL) {
    g_object_unref (multifilesink->gop_adapter);
    multifilesink->gop_adapter = NULL;
  }

  if (multifilesink->potential_next_gop != NULL) {
    g_list_free_full (multifilesink->potential_next_gop,
        (GDestroyNotify) gst_buffer_unref);
    multifilesink->potential_next_gop = NULL;
  }

492
493
  multifilesink->force_key_unit_count = -1;

494
495
  return TRUE;
}
496

497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
static void
gst_multi_file_sink_post_message_full (GstMultiFileSink * multifilesink,
    GstClockTime timestamp, GstClockTime duration, GstClockTime offset,
    GstClockTime offset_end, GstClockTime running_time,
    GstClockTime stream_time, const char *filename)
{
  GstStructure *s;

  if (!multifilesink->post_messages)
    return;

  s = gst_structure_new ("GstMultiFileSink",
      "filename", G_TYPE_STRING, filename,
      "index", G_TYPE_INT, multifilesink->index,
      "timestamp", G_TYPE_UINT64, timestamp,
      "stream-time", G_TYPE_UINT64, stream_time,
      "running-time", G_TYPE_UINT64, running_time,
      "duration", G_TYPE_UINT64, duration,
      "offset", G_TYPE_UINT64, offset,
      "offset-end", G_TYPE_UINT64, offset_end, NULL);

  gst_element_post_message (GST_ELEMENT_CAST (multifilesink),
      gst_message_new_element (GST_OBJECT_CAST (multifilesink), s));
}

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
static void
gst_multi_file_sink_post_message_from_time (GstMultiFileSink * multifilesink,
    GstClockTime timestamp, GstClockTime duration, const char *filename)
{
  GstClockTime running_time, stream_time;
  guint64 offset, offset_end;
  GstSegment *segment;
  GstFormat format;

  if (!multifilesink->post_messages)
    return;

  segment = &GST_BASE_SINK (multifilesink)->segment;
  format = segment->format;

  offset = -1;
  offset_end = -1;

  running_time = gst_segment_to_running_time (segment, format, timestamp);
  stream_time = gst_segment_to_stream_time (segment, format, timestamp);

  gst_multi_file_sink_post_message_full (multifilesink, timestamp, duration,
      offset, offset_end, running_time, stream_time, filename);
}
547

548
549
550
551
static void
gst_multi_file_sink_post_message (GstMultiFileSink * multifilesink,
    GstBuffer * buffer, const char *filename)
{
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
  GstClockTime duration, timestamp;
  GstClockTime running_time, stream_time;
  guint64 offset, offset_end;
  GstSegment *segment;
  GstFormat format;

  if (!multifilesink->post_messages)
    return;

  segment = &GST_BASE_SINK (multifilesink)->segment;
  format = segment->format;

  timestamp = GST_BUFFER_TIMESTAMP (buffer);
  duration = GST_BUFFER_DURATION (buffer);
  offset = GST_BUFFER_OFFSET (buffer);
  offset_end = GST_BUFFER_OFFSET_END (buffer);

  running_time = gst_segment_to_running_time (segment, format, timestamp);
  stream_time = gst_segment_to_stream_time (segment, format, timestamp);

  gst_multi_file_sink_post_message_full (multifilesink, timestamp, duration,
      offset, offset_end, running_time, stream_time, filename);
574
}
David Schleef's avatar
David Schleef committed
575

576
577
578
579
580
581
582
583
static gboolean
gst_multi_file_sink_write_stream_headers (GstMultiFileSink * sink)
{
  int i;

  if (sink->streamheaders == NULL)
    return TRUE;

584
585
  GST_DEBUG_OBJECT (sink, "Writing stream headers");

586
587
588
589
590
  /* we want to write these at the beginning */
  g_assert (sink->cur_file_size == 0);

  for (i = 0; i < sink->n_streamheaders; i++) {
    GstBuffer *hdr;
Wim Taymans's avatar
Wim Taymans committed
591
    GstMapInfo map;
592
593
594
    int ret;

    hdr = sink->streamheaders[i];
Wim Taymans's avatar
Wim Taymans committed
595
596
597
    gst_buffer_map (hdr, &map, GST_MAP_READ);
    ret = fwrite (map.data, map.size, 1, sink->file);
    gst_buffer_unmap (hdr, &map);
598
599
600
601

    if (ret != 1)
      return FALSE;

Wim Taymans's avatar
Wim Taymans committed
602
    sink->cur_file_size += map.size;
David Schleef's avatar
David Schleef committed
603
  }
604
605

  return TRUE;
606
}
David Schleef's avatar
David Schleef committed
607

608
static GstFlowReturn
609
610
gst_multi_file_sink_write_buffer (GstMultiFileSink * multifilesink,
    GstBuffer * buffer)
611
{
Wim Taymans's avatar
Wim Taymans committed
612
  GstMapInfo map;
613
  gboolean ret;
614
  gboolean first_file = TRUE;
615

Wim Taymans's avatar
Wim Taymans committed
616
  gst_buffer_map (buffer, &map, GST_MAP_READ);
617
618
619

  switch (multifilesink->next_file) {
    case GST_MULTI_FILE_SINK_NEXT_BUFFER:
620
621
622
623
624
625
626
627
628
629
      if (multifilesink->files != NULL)
        first_file = FALSE;
      if (!gst_multi_file_sink_open_next_file (multifilesink))
        goto stdio_write_error;
      if (first_file == FALSE)
        gst_multi_file_sink_write_stream_headers (multifilesink);
      GST_DEBUG_OBJECT (multifilesink,
          "Writing buffer data (%" G_GSIZE_FORMAT " bytes) to new file",
          map.size);
      ret = fwrite (map.data, map.size, 1, multifilesink->file);
630
631
      if (ret != 1) {
        gst_multi_file_sink_close_file (multifilesink, NULL);
632
        goto stdio_write_error;
633
      }
634

635
      gst_multi_file_sink_close_file (multifilesink, buffer);
636
637
638
      break;
    case GST_MULTI_FILE_SINK_NEXT_DISCONT:
      if (GST_BUFFER_IS_DISCONT (buffer)) {
639
640
        if (multifilesink->file)
          gst_multi_file_sink_close_file (multifilesink, buffer);
641
642
643
      }

      if (multifilesink->file == NULL) {
644
        if (!gst_multi_file_sink_open_next_file (multifilesink))
645
646
647
          goto stdio_write_error;
      }

Wim Taymans's avatar
Wim Taymans committed
648
      ret = fwrite (map.data, map.size, 1, multifilesink->file);
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
      if (ret != 1)
        goto stdio_write_error;

      break;
    case GST_MULTI_FILE_SINK_NEXT_KEY_FRAME:
      if (multifilesink->next_segment == GST_CLOCK_TIME_NONE) {
        if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
          multifilesink->next_segment = GST_BUFFER_TIMESTAMP (buffer) +
              10 * GST_SECOND;
        }
      }

      if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
          GST_BUFFER_TIMESTAMP (buffer) >= multifilesink->next_segment &&
          !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
664
665
        if (multifilesink->file) {
          first_file = FALSE;
666
          gst_multi_file_sink_close_file (multifilesink, buffer);
667
        }
668
669
670
671
        multifilesink->next_segment += 10 * GST_SECOND;
      }

      if (multifilesink->file == NULL) {
672
        if (!gst_multi_file_sink_open_next_file (multifilesink))
673
          goto stdio_write_error;
674

675
676
        if (!first_file)
          gst_multi_file_sink_write_stream_headers (multifilesink);
677
678
      }

Wim Taymans's avatar
Wim Taymans committed
679
      ret = fwrite (map.data, map.size, 1, multifilesink->file);
680
681
682
683
684
685
      if (ret != 1)
        goto stdio_write_error;

      break;
    case GST_MULTI_FILE_SINK_NEXT_KEY_UNIT_EVENT:
      if (multifilesink->file == NULL) {
686
        if (!gst_multi_file_sink_open_next_file (multifilesink))
687
          goto stdio_write_error;
688

689
690
691
692
693
        /* we don't need to write stream headers here, they will be inserted in
         * the stream by upstream elements if key unit events have
         * all_headers=true set
         */
      }
694

Wim Taymans's avatar
Wim Taymans committed
695
      ret = fwrite (map.data, map.size, 1, multifilesink->file);
696

697
698
699
700
      if (ret != 1)
        goto stdio_write_error;

      break;
701
702
703
    case GST_MULTI_FILE_SINK_NEXT_MAX_SIZE:{
      guint64 new_size;

Wim Taymans's avatar
Wim Taymans committed
704
      new_size = multifilesink->cur_file_size + map.size;
705
706
707
708
709
710
711
      if (new_size > multifilesink->max_file_size) {

        GST_INFO_OBJECT (multifilesink, "current size: %" G_GUINT64_FORMAT
            ", new_size: %" G_GUINT64_FORMAT ", max. size %" G_GUINT64_FORMAT,
            multifilesink->cur_file_size, new_size,
            multifilesink->max_file_size);

712
713
        if (multifilesink->file != NULL) {
          first_file = FALSE;
714
          gst_multi_file_sink_close_file (multifilesink, buffer);
715
        }
716
717
718
719
720
721
      }

      if (multifilesink->file == NULL) {
        if (!gst_multi_file_sink_open_next_file (multifilesink))
          goto stdio_write_error;

722
723
        if (!first_file)
          gst_multi_file_sink_write_stream_headers (multifilesink);
724
725
      }

Wim Taymans's avatar
Wim Taymans committed
726
      ret = fwrite (map.data, map.size, 1, multifilesink->file);
727

728
729
730
      if (ret != 1)
        goto stdio_write_error;

Wim Taymans's avatar
Wim Taymans committed
731
      multifilesink->cur_file_size += map.size;
732
      break;
733
    }
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
    case GST_MULTI_FILE_SINK_NEXT_MAX_DURATION:{
      GstClockTime new_duration = 0;

      if (GST_BUFFER_PTS_IS_VALID (buffer)
          && GST_CLOCK_TIME_IS_VALID (multifilesink->file_pts)) {
        /* The new duration will extend to this new buffer pts ... */
        new_duration = GST_BUFFER_PTS (buffer) - multifilesink->file_pts;
        /* ... and duration (if it has one) */
        if (GST_BUFFER_DURATION_IS_VALID (buffer))
          new_duration += GST_BUFFER_DURATION (buffer);
      }

      if (new_duration > multifilesink->max_file_duration) {

        GST_INFO_OBJECT (multifilesink,
            "new_duration: %" G_GUINT64_FORMAT ", max. duration %"
            G_GUINT64_FORMAT, new_duration, multifilesink->max_file_duration);

        if (multifilesink->file != NULL) {
          first_file = FALSE;
          gst_multi_file_sink_close_file (multifilesink, buffer);
        }
      }

      if (multifilesink->file == NULL) {
        if (!gst_multi_file_sink_open_next_file (multifilesink))
          goto stdio_write_error;

        multifilesink->file_pts = GST_BUFFER_PTS (buffer);
        if (!first_file)
          gst_multi_file_sink_write_stream_headers (multifilesink);
      }

      ret = fwrite (map.data, map.size, 1, multifilesink->file);

      if (ret != 1)
        goto stdio_write_error;

      break;
    }
774
775
776
    default:
      g_assert_not_reached ();
  }
777

Wim Taymans's avatar
Wim Taymans committed
778
  gst_buffer_unmap (buffer, &map);
779
780
781
  return GST_FLOW_OK;

  /* ERRORS */
782
stdio_write_error:
783
784
785
786
787
788
789
790
  switch (errno) {
    case ENOSPC:
      GST_ELEMENT_ERROR (multifilesink, RESOURCE, NO_SPACE_LEFT,
          ("Error while writing to file."), ("%s", g_strerror (errno)));
      break;
    default:
      GST_ELEMENT_ERROR (multifilesink, RESOURCE, WRITE,
          ("Error while writing to file."), ("%s", g_strerror (errno)));
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
791
  }
Wim Taymans's avatar
Wim Taymans committed
792
  gst_buffer_unmap (buffer, &map);
793
  return GST_FLOW_ERROR;
David Schleef's avatar
David Schleef committed
794
}
795

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
static GstFlowReturn
gst_multi_file_sink_render (GstBaseSink * bsink, GstBuffer * buffer)
{
  GstMultiFileSink *sink = GST_MULTI_FILE_SINK (bsink);
  GstFlowReturn flow = GST_FLOW_OK;
  gboolean key_unit, header;

  header = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_HEADER);
  key_unit = !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);

  if (sink->aggregate_gops) {
    GstBuffer *gop_buffer = NULL;
    guint avail;

    avail = gst_adapter_available (sink->gop_adapter);

    GST_LOG_OBJECT (sink, "aggregate GOP: received %s%s unit buffer: "
        "%" GST_PTR_FORMAT,
        (key_unit) ? "key" : "delta", (header) ? " header" : "", buffer);

    /* If it's a header buffer, it might potentially be for the next GOP */
    if (header) {
      GST_LOG_OBJECT (sink, "Accumulating buffer to potential next GOP");
      sink->potential_next_gop =
          g_list_append (sink->potential_next_gop, gst_buffer_ref (buffer));
    } else {
      if (key_unit && avail > 0) {
823
        GstClockTime pts, dts;
824
        GST_LOG_OBJECT (sink, "Grabbing pending completed GOP");
825
826
        pts = gst_adapter_prev_pts_at_offset (sink->gop_adapter, 0, NULL);
        dts = gst_adapter_prev_dts_at_offset (sink->gop_adapter, 0, NULL);
827
        gop_buffer = gst_adapter_take_buffer (sink->gop_adapter, avail);
828
829
        GST_BUFFER_PTS (gop_buffer) = pts;
        GST_BUFFER_DTS (gop_buffer) = dts;
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
      }

      /* just accumulate the buffer */
      if (sink->potential_next_gop) {
        GList *tmp;
        GST_LOG_OBJECT (sink,
            "Carrying over pending next GOP data into adapter");
        /* If we have pending data, put that first in the adapter */
        for (tmp = sink->potential_next_gop; tmp; tmp = tmp->next) {
          GstBuffer *tmpb = (GstBuffer *) tmp->data;
          gst_adapter_push (sink->gop_adapter, tmpb);
        }
        g_list_free (sink->potential_next_gop);
        sink->potential_next_gop = NULL;
      }
      GST_LOG_OBJECT (sink, "storing buffer in adapter");
      gst_adapter_push (sink->gop_adapter, gst_buffer_ref (buffer));

      if (gop_buffer != NULL) {
        GST_DEBUG_OBJECT (sink, "writing out pending GOP, %u bytes", avail);
850
851
852
853
854
855
        GST_DEBUG_OBJECT (sink,
            "gop buffer pts:%" GST_TIME_FORMAT " dts:%" GST_TIME_FORMAT
            " duration:%" GST_TIME_FORMAT,
            GST_TIME_ARGS (GST_BUFFER_PTS (gop_buffer)),
            GST_TIME_ARGS (GST_BUFFER_DTS (gop_buffer)),
            GST_TIME_ARGS (GST_BUFFER_DURATION (gop_buffer)));
856
857
858
859
860
861
862
863
864
865
        flow = gst_multi_file_sink_write_buffer (sink, gop_buffer);
        gst_buffer_unref (gop_buffer);
      }
    }
  } else {
    flow = gst_multi_file_sink_write_buffer (sink, buffer);
  }
  return flow;
}

866
867
static gboolean
buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
868
869
{
  guint *p_size = data;
870
  gsize buf_size;
871

872
873
  buf_size = gst_buffer_get_size (*buf);
  GST_TRACE ("buffer %u has size %" G_GSIZE_FORMAT, idx, buf_size);
874
875
  *p_size += buf_size;

876
  return TRUE;
877
878
}

879
880
static gboolean
buffer_list_copy_data (GstBuffer ** buf, guint idx, gpointer data)
881
882
{
  GstBuffer *dest = data;
883
884
885
886
  guint num, i;

  if (idx == 0)
    gst_buffer_copy_into (dest, *buf, GST_BUFFER_COPY_METADATA, 0, -1);
887

888
889
890
  num = gst_buffer_n_memory (*buf);
  for (i = 0; i < num; ++i) {
    GstMemory *mem;
891

Wim Taymans's avatar
Wim Taymans committed
892
    mem = gst_buffer_get_memory (*buf, i);
Wim Taymans's avatar
Wim Taymans committed
893
    gst_buffer_append_memory (dest, mem);
894
  }
895

896
  return TRUE;
897
898
899
900
901
902
903
904
905
}

/* Our assumption for now is that the buffers in a buffer list should always
 * end up in the same file. If someone wants different behaviour, they'll just
 * have to add a property for that. */
static GstFlowReturn
gst_multi_file_sink_render_list (GstBaseSink * sink, GstBufferList * list)
{
  GstBuffer *buf;
906
  guint size = 0;
907
908
909
910
911
912

  gst_buffer_list_foreach (list, buffer_list_calc_size, &size);
  GST_LOG_OBJECT (sink, "total size of buffer list %p: %u", list, size);

  /* copy all buffers in the list into one single buffer, so we can use
   * the normal render function (FIXME: optimise to avoid the memcpy) */
913
  buf = gst_buffer_new ();
914
  gst_buffer_list_foreach (list, buffer_list_copy_data, buf);
915
  g_assert (gst_buffer_get_size (buf) == size);
916
917
918
919
920
921
922

  gst_multi_file_sink_render (sink, buf);
  gst_buffer_unref (buf);

  return GST_FLOW_OK;
}

923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
static gboolean
gst_multi_file_sink_set_caps (GstBaseSink * sink, GstCaps * caps)
{
  GstMultiFileSink *multifilesink;
  GstStructure *structure;

  multifilesink = GST_MULTI_FILE_SINK (sink);

  structure = gst_caps_get_structure (caps, 0);
  if (structure) {
    const GValue *value;

    value = gst_structure_get_value (structure, "streamheader");

    if (GST_VALUE_HOLDS_ARRAY (value)) {
      int i;

      if (multifilesink->streamheaders) {
        for (i = 0; i < multifilesink->n_streamheaders; i++) {
          gst_buffer_unref (multifilesink->streamheaders[i]);
        }
        g_free (multifilesink->streamheaders);
      }

      multifilesink->n_streamheaders = gst_value_array_get_size (value);
      multifilesink->streamheaders =
          g_malloc (sizeof (GstBuffer *) * multifilesink->n_streamheaders);

      for (i = 0; i < multifilesink->n_streamheaders; i++) {
        multifilesink->streamheaders[i] =
            gst_buffer_ref (gst_value_get_buffer (gst_value_array_get_value
                (value, i)));
      }
    }
  }

  return TRUE;
}
961

962
963
964
965
966
967
968
969
970
static void
gst_multi_file_sink_ensure_max_files (GstMultiFileSink * multifilesink)
{
  char *filename;

  while (multifilesink->max_files &&
      multifilesink->n_files >= multifilesink->max_files) {
    filename = multifilesink->files->data;
    g_remove (filename);
971
    g_free (filename);
972
973
974
975
976
977
    multifilesink->files = g_slist_delete_link (multifilesink->files,
        multifilesink->files);
    multifilesink->n_files -= 1;
  }
}

978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
static gboolean
gst_multi_file_sink_event (GstBaseSink * sink, GstEvent * event)
{
  GstMultiFileSink *multifilesink;
  gchar *filename;

  multifilesink = GST_MULTI_FILE_SINK (sink);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_CUSTOM_DOWNSTREAM:
    {
      GstClockTime timestamp, duration;
      GstClockTime running_time, stream_time;
      guint64 offset, offset_end;
      gboolean all_headers;
      guint count;

      if (multifilesink->next_file != GST_MULTI_FILE_SINK_NEXT_KEY_UNIT_EVENT ||
          !gst_video_event_is_force_key_unit (event))
        goto out;

      gst_video_event_parse_downstream_force_key_unit (event, &timestamp,
          &stream_time, &running_time, &all_headers, &count);

      if (multifilesink->force_key_unit_count != -1 &&
          multifilesink->force_key_unit_count == count)
        goto out;

      multifilesink->force_key_unit_count = count;

      if (multifilesink->file) {
        duration = GST_CLOCK_TIME_NONE;
        offset = offset_end = -1;
        filename = g_strdup_printf (multifilesink->filename,
            multifilesink->index);

        gst_multi_file_sink_close_file (multifilesink, NULL);

1016
1017
1018
        gst_multi_file_sink_post_message_full (multifilesink, timestamp,
            duration, offset, offset_end, running_time, stream_time, filename);
        g_free (filename);
1019
1020
1021
1022
1023
1024
1025
1026
1027
      }

      if (multifilesink->file == NULL) {
        if (!gst_multi_file_sink_open_next_file (multifilesink))
          goto stdio_write_error;
      }

      break;
    }
1028
    case GST_EVENT_EOS:
1029
1030
1031
1032
1033
1034
1035
1036
1037
      if (multifilesink->aggregate_gops) {
        GstBuffer *buf = gst_buffer_new ();

        /* push key unit buffer to force writing out the pending GOP data */
        GST_INFO_OBJECT (sink, "EOS, write pending GOP data");
        GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
        gst_multi_file_sink_render (sink, buf);
        gst_buffer_unref (buf);
      }
1038
1039
1040
1041
1042
      if (multifilesink->file) {
        gchar *filename;

        filename = g_strdup_printf (multifilesink->filename,
            multifilesink->index);
1043
1044
1045

        gst_multi_file_sink_close_file (multifilesink, NULL);

1046
1047
1048
1049
1050
        gst_multi_file_sink_post_message_from_time (multifilesink,
            GST_BASE_SINK (multifilesink)->segment.position, -1, filename);
        g_free (filename);
      }
      break;
1051
1052
1053
1054
1055
    default:
      break;
  }

out:
1056
  return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
1057

1058
  /* ERRORS */
1059
stdio_write_error:
1060
1061
1062
1063
1064
1065
  {
    GST_ELEMENT_ERROR (multifilesink, RESOURCE, WRITE,
        ("Error while writing to file."), (NULL));
    gst_event_unref (event);
    return FALSE;
  }
1066
1067
}

1068
1069
1070
1071
1072
1073
1074
static gboolean
gst_multi_file_sink_open_next_file (GstMultiFileSink * multifilesink)
{
  char *filename;

  g_return_val_if_fail (multifilesink->file == NULL, FALSE);

1075
  gst_multi_file_sink_ensure_max_files (multifilesink);
1076
1077
  filename = g_strdup_printf (multifilesink->filename, multifilesink->index);
  multifilesink->file = g_fopen (filename, "wb");
1078
1079
  if (multifilesink->file == NULL) {
    g_free (filename);
1080
    return FALSE;
1081
1082
  }

1083
  GST_INFO_OBJECT (multifilesink, "opening file %s", filename);
1084
1085
  multifilesink->files = g_slist_append (multifilesink->files, filename);
  multifilesink->n_files += 1;
1086

1087
  multifilesink->cur_file_size = 0;
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
  return TRUE;
}

static void
gst_multi_file_sink_close_file (GstMultiFileSink * multifilesink,
    GstBuffer * buffer)
{
  char *filename;

  fclose (multifilesink->file);
  multifilesink->file = NULL;

  if (buffer) {
    filename = g_strdup_printf (multifilesink->filename, multifilesink->index);
    gst_multi_file_sink_post_message (multifilesink, buffer, filename);
    g_free (filename);
  }

  multifilesink->index++;
}