cf8148d513fbf7c8e3be0ae210f9ae5f818bf856
[platform/upstream/gst-plugins-good.git] / gst / isomp4 / gstqtmux.c
1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4  * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5  * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6  * Contact: Stefan Kost <stefan.kost@nokia.com>
7
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /*
24  * Unless otherwise indicated, Source Code is licensed under MIT license.
25  * See further explanation attached in License Statement (distributed in the file
26  * LICENSE).
27  *
28  * Permission is hereby granted, free of charge, to any person obtaining a copy of
29  * this software and associated documentation files (the "Software"), to deal in
30  * the Software without restriction, including without limitation the rights to
31  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32  * of the Software, and to permit persons to whom the Software is furnished to do
33  * so, subject to the following conditions:
34  *
35  * The above copyright notice and this permission notice shall be included in all
36  * copies or substantial portions of the Software.
37  *
38  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44  * SOFTWARE.
45  */
46
47
48 /**
49  * SECTION:element-qtmux
50  * @short_description: Muxer for quicktime(.mov) files
51  *
52  * This element merges streams (audio and video) into QuickTime(.mov) files.
53  *
54  * The following background intends to explain why various similar muxers
55  * are present in this plugin.
56  *
57  * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58  * QuickTime file format specification</ulink> served as basis for the MP4 file
59  * format specification (mp4mux), and as such the QuickTime file structure is
60  * nearly identical to the so-called ISO Base Media file format defined in
61  * ISO 14496-12 (except for some media specific parts).
62  * In turn, the latter ISO Base Media format was further specialized as a
63  * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64  * and in various 3GPP(2) specs (gppmux).
65  * The fragmented file features defined (only) in ISO Base Media are used by
66  * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
67  *
68  * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale,
69  * #GstQTMuxPad:trak-timescale) allow adjusting some technical parameters,
70  * which might be useful in (rare) cases to resolve compatibility issues in
71  * some situations.
72  *
73  * Some other properties influence the result more fundamentally.
74  * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
75  * file, somewhat contrary to this usually being called "the header".
76  * However, a #GstQTMux:faststart file will (with some effort) arrange this to
77  * be located near start of the file, which then allows it e.g. to be played
78  * while downloading. Alternatively, rather than having one chunk of metadata at
79  * start (or end), there can be some metadata at start and most of the other
80  * data can be spread out into fragments of #GstQTMux:fragment-duration.
81  * If such fragmented layout is intended for streaming purposes, then
82  * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
83  * file).
84  *
85  * When the maximum duration to be recorded can be known in advance, #GstQTMux
86  * also supports a 'Robust Muxing' mode. In robust muxing mode,  space for the
87  * headers are reserved at the start of muxing, and rewritten at a configurable
88  * interval, so that the output file is always playable, even if the recording
89  * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
90  * output, such as filesink, because it needs to rewrite the start of the file.
91  *
92  * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
93  * and #GstQTMux::reserved-max-duration property. Also present is the
94  * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
95  * for some reason the default is not large enough and the initial reserved
96  * space for headers is too small. Applications can monitor the
97  * #GstQTMux::reserved-duration-remaining property to see how close to full
98  * the reserved space is becoming.
99  *
100  * Applications that wish to be able to use/edit a file while it is being
101  * written to by live content, can use the "Robust Prefill Muxing" mode. That
102  * mode is a variant of the "Robust Muxing" mode in that it will pre-allocate a
103  * completely valid header from the start for all tracks (i.e. it appears as
104  * though the file is "reserved-max-duration" long with all samples
105  * present). This mode can be enabled by setting the
106  * #GstQTMux::reserved-moov-update-period and #GstQTMux::reserved-prefill
107  * properties. Note that this mode is only possible with input streams that have
108  * a fixed sample size (such as raw audio and Prores Video) and that don't
109  * have reordered samples.
110  *
111  * <refsect2>
112  * <title>Example pipelines</title>
113  * |[
114  * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
115  * ]|
116  * Records a video stream captured from a v4l2 device and muxes it into a qt file.
117  * </refsect2>
118  */
119
120 /*
121  * Based on avimux
122  */
123
124 #ifdef HAVE_CONFIG_H
125 #include "config.h"
126 #endif
127
128 #include <glib/gstdio.h>
129
130 #include <gst/gst.h>
131 #include <gst/base/gstcollectpads.h>
132 #include <gst/base/gstbytereader.h>
133 #include <gst/base/gstbitreader.h>
134 #include <gst/audio/audio.h>
135 #include <gst/video/video.h>
136 #include <gst/tag/tag.h>
137 #include <gst/pbutils/pbutils.h>
138
139 #include <sys/types.h>
140 #ifdef G_OS_WIN32
141 #include <io.h>                 /* lseek, open, close, read */
142 #undef lseek
143 #define lseek _lseeki64
144 #undef off_t
145 #define off_t guint64
146 #endif
147
148 #ifdef _MSC_VER
149 #define ftruncate g_win32_ftruncate
150 #endif
151
152 #ifdef HAVE_UNISTD_H
153 #  include <unistd.h>
154 #endif
155
156 #include "gstqtmux.h"
157
158 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
159 #define GST_CAT_DEFAULT gst_qt_mux_debug
160
161 #ifndef ABSDIFF
162 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
163 #endif
164
165 /* Hacker notes.
166  *
167  * The basic building blocks of MP4 files are:
168  *  - an 'ftyp' box at the very start
169  *  - an 'mdat' box which contains the raw audio/video/subtitle data;
170  *    this is just a bunch of bytes, completely unframed and possibly
171  *    unordered with no additional meta-information
172  *  - a 'moov' box that contains information about the different streams
173  *    and what they contain, as well as sample tables for each stream
174  *    that tell the demuxer where in the mdat box each buffer/sample is
175  *    and what its duration/timestamp etc. is, and whether it's a
176  *    keyframe etc.
177  * Additionally, fragmented MP4 works by writing chunks of data in
178  * pairs of 'moof' and 'mdat' boxes:
179  *  - 'moof' boxes, header preceding each mdat fragment describing the
180  *    contents, like a moov but only for that fragment.
181  *  - a 'mfra' box for Fragmented MP4, which is written at the end and
182  *    contains a summary of all fragments and seek tables.
183  *
184  * Currently mp4mux can work in 4 different modes / generate 4 types
185  * of output files/streams:
186  *
187  * - Normal mp4: mp4mux will write a little ftyp identifier at the
188  *   beginning, then start an mdat box into which it will write all the
189  *   sample data. At EOS it will then write the moov header with track
190  *   headers and sample tables at the end of the file, and rewrite the
191  *   start of the file to fix up the mdat box size at the beginning.
192  *   It has to wait for EOS to write the moov (which includes the
193  *   sample tables) because it doesn't know how much space those
194  *   tables will be. The output downstream must be seekable to rewrite
195  *   the mdat box at EOS.
196  *
197  * - Fragmented mp4: moov header with track headers at start
198  *   but no sample table, followed by N fragments, each containing
199  *   track headers with sample tables followed by some data. Downstream
200  *   does not need to be seekable if the 'streamable' flag is TRUE,
201  *   as the final mfra and total duration will be omitted.
202  *
203  * - Fast-start mp4: the goal here is to create a file where the moov
204  *   headers are at the beginning; what mp4mux will do is write all
205  *   sample data into a temp file and build moov header plus sample
206  *   tables in memory and then when EOS comes, it will push out the
207  *   moov header plus sample tables at the beginning, followed by the
208  *   mdat sample data at the end which is read in from the temp file
209  *   Files created in this mode are better for streaming over the
210  *   network, since the client doesn't have to seek to the end of the
211  *   file to get the headers, but it requires copying all sample data
212  *   out of the temp file at EOS, which can be expensive. Downstream does
213  *   not need to be seekable, because of the use of the temp file.
214  *
215  * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
216  *   and reserved-moov-update-period properties to reserve free space
217  *   at the start of the file and periodically write the MOOV atom out
218  *   to it. That means that killing the muxing at any point still
219  *   results in a playable file, at the cost of wasting some amount of
220  *   free space at the start of file. The approximate recording duration
221  *   has to be known in advance to estimate how much free space to reserve
222  *   for the moov, and the downstream must be seekable.
223  *   If the moov header grows larger than the reserved space, an error
224  *   is generated - so it's better to over-estimate the amount of space
225  *   to reserve. To ensure the file is playable at any point, the moov
226  *   is updated using a 'ping-pong' strategy, so the output is never in
227  *   an invalid state.
228  */
229
230 #ifndef GST_REMOVE_DEPRECATED
231 enum
232 {
233   DTS_METHOD_DD,
234   DTS_METHOD_REORDER,
235   DTS_METHOD_ASC
236 };
237
238 static GType
239 gst_qt_mux_dts_method_get_type (void)
240 {
241   static GType gst_qt_mux_dts_method = 0;
242
243   if (!gst_qt_mux_dts_method) {
244     static const GEnumValue dts_methods[] = {
245       {DTS_METHOD_DD, "delta/duration", "dd"},
246       {DTS_METHOD_REORDER, "reorder", "reorder"},
247       {DTS_METHOD_ASC, "ascending", "asc"},
248       {0, NULL, NULL},
249     };
250
251     gst_qt_mux_dts_method =
252         g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
253   }
254
255   return gst_qt_mux_dts_method;
256 }
257
258 #define GST_TYPE_QT_MUX_DTS_METHOD \
259   (gst_qt_mux_dts_method_get_type ())
260 #endif
261
262 enum
263 {
264   PROP_PAD_0,
265   PROP_PAD_TRAK_TIMESCALE,
266 };
267
268 #define DEFAULT_PAD_TRAK_TIMESCALE          0
269
270 GType gst_qt_mux_pad_get_type (void);
271
272 #define GST_TYPE_QT_MUX_PAD \
273   (gst_qt_mux_pad_get_type())
274 #define GST_QT_MUX_PAD(obj) \
275   (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_QT_MUX_PAD, GstQTMuxPad))
276 #define GST_QT_MUX_PAD_CLASS(klass) \
277   (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_QT_MUX_PAD, GstQTMuxPadClass))
278 #define GST_IS_QT_MUX_PAD(obj) \
279   (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_QT_MUX_PAD))
280 #define GST_IS_QT_MUX_PAD_CLASS(klass) \
281   (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_QT_MUX_PAD))
282 #define GST_QT_MUX_PAD_CAST(obj) \
283   ((GstQTMuxPad *)(obj))
284
285 typedef struct _GstQTMuxPad GstQTMuxPad;
286 typedef struct _GstQTMuxPadClass GstQTMuxPadClass;
287
288 struct _GstQTMuxPad
289 {
290   GstPad parent;
291
292   guint32 trak_timescale;
293 };
294
295 struct _GstQTMuxPadClass
296 {
297   GstPadClass parent;
298 };
299
300 G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_PAD);
301
302 static void
303 gst_qt_mux_pad_set_property (GObject * object,
304     guint prop_id, const GValue * value, GParamSpec * pspec)
305 {
306   GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
307
308   GST_OBJECT_LOCK (pad);
309   switch (prop_id) {
310     case PROP_PAD_TRAK_TIMESCALE:
311       pad->trak_timescale = g_value_get_uint (value);
312       break;
313     default:
314       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
315       break;
316   }
317   GST_OBJECT_UNLOCK (pad);
318 }
319
320 static void
321 gst_qt_mux_pad_get_property (GObject * object,
322     guint prop_id, GValue * value, GParamSpec * pspec)
323 {
324   GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
325
326   GST_OBJECT_LOCK (pad);
327   switch (prop_id) {
328     case PROP_PAD_TRAK_TIMESCALE:
329       g_value_set_uint (value, pad->trak_timescale);
330       break;
331     default:
332       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
333       break;
334   }
335   GST_OBJECT_UNLOCK (pad);
336 }
337
338 static void
339 gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
340 {
341   GObjectClass *gobject_class = (GObjectClass *) klass;
342
343   gobject_class->get_property = gst_qt_mux_pad_get_property;
344   gobject_class->set_property = gst_qt_mux_pad_set_property;
345
346   g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
347       g_param_spec_uint ("trak-timescale", "Track timescale",
348           "Timescale to use for this pad's trak (units per second, 0 is automatic)",
349           0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
350           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
351 }
352
353 static void
354 gst_qt_mux_pad_init (GstQTMuxPad * pad)
355 {
356   pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
357 }
358
359 static guint32
360 gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
361 {
362   guint32 timescale;
363
364   GST_OBJECT_LOCK (pad);
365   timescale = pad->trak_timescale;
366   GST_OBJECT_UNLOCK (pad);
367
368   return timescale;
369 }
370
371 /* QTMux signals and args */
372 enum
373 {
374   /* FILL ME */
375   LAST_SIGNAL
376 };
377
378 enum
379 {
380   PROP_0,
381   PROP_MOVIE_TIMESCALE,
382   PROP_TRAK_TIMESCALE,
383   PROP_FAST_START,
384   PROP_FAST_START_TEMP_FILE,
385   PROP_MOOV_RECOV_FILE,
386   PROP_FRAGMENT_DURATION,
387   PROP_STREAMABLE,
388   PROP_RESERVED_MAX_DURATION,
389   PROP_RESERVED_DURATION_REMAINING,
390   PROP_RESERVED_MOOV_UPDATE_PERIOD,
391   PROP_RESERVED_BYTES_PER_SEC,
392   PROP_RESERVED_PREFILL,
393 #ifndef GST_REMOVE_DEPRECATED
394   PROP_DTS_METHOD,
395 #endif
396   PROP_DO_CTTS,
397   PROP_INTERLEAVE_BYTES,
398   PROP_INTERLEAVE_TIME,
399   PROP_MAX_RAW_AUDIO_DRIFT,
400 };
401
402 /* some spare for header size as well */
403 #define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)
404
405 #define DEFAULT_MOVIE_TIMESCALE         0
406 #define DEFAULT_TRAK_TIMESCALE          0
407 #define DEFAULT_DO_CTTS                 TRUE
408 #define DEFAULT_FAST_START              FALSE
409 #define DEFAULT_FAST_START_TEMP_FILE    NULL
410 #define DEFAULT_MOOV_RECOV_FILE         NULL
411 #define DEFAULT_FRAGMENT_DURATION       0
412 #define DEFAULT_STREAMABLE              TRUE
413 #ifndef GST_REMOVE_DEPRECATED
414 #define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
415 #endif
416 #define DEFAULT_RESERVED_MAX_DURATION   GST_CLOCK_TIME_NONE
417 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD   GST_CLOCK_TIME_NONE
418 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
419 #define DEFAULT_RESERVED_PREFILL FALSE
420 #define DEFAULT_INTERLEAVE_BYTES 0
421 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
422 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
423
424 static void gst_qt_mux_finalize (GObject * object);
425
426 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
427     GstStateChange transition);
428
429 /* property functions */
430 static void gst_qt_mux_set_property (GObject * object,
431     guint prop_id, const GValue * value, GParamSpec * pspec);
432 static void gst_qt_mux_get_property (GObject * object,
433     guint prop_id, GValue * value, GParamSpec * pspec);
434
435 /* pad functions */
436 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
437     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
438 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
439
440 /* event */
441 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
442     GstCollectData * data, GstEvent * event, gpointer user_data);
443
444 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
445     gpointer user_data);
446 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
447     GstBuffer * buf);
448
449 static GstFlowReturn
450 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
451
452 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
453 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
454
455 static GstElementClass *parent_class = NULL;
456
457 static void
458 gst_qt_mux_base_init (gpointer g_class)
459 {
460   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
461   GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
462   GstQTMuxClassParams *params;
463   GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
464       *captionsinktempl;
465   GstPadTemplate *srctempl;
466   gchar *longname, *description;
467
468   params =
469       (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
470       GST_QT_MUX_PARAMS_QDATA);
471   g_assert (params != NULL);
472
473   /* construct the element details struct */
474   longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
475   description = g_strdup_printf ("Multiplex audio and video into a %s file",
476       params->prop->long_name);
477   gst_element_class_set_static_metadata (element_class, longname,
478       "Codec/Muxer", description,
479       "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
480   g_free (longname);
481   g_free (description);
482
483   /* pad templates */
484   srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
485       GST_PAD_ALWAYS, params->src_caps);
486   gst_element_class_add_pad_template (element_class, srctempl);
487
488   if (params->audio_sink_caps) {
489     audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
490         GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
491         GST_TYPE_QT_MUX_PAD);
492     gst_element_class_add_pad_template (element_class, audiosinktempl);
493   }
494
495   if (params->video_sink_caps) {
496     videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
497         GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
498         GST_TYPE_QT_MUX_PAD);
499     gst_element_class_add_pad_template (element_class, videosinktempl);
500   }
501
502   if (params->subtitle_sink_caps) {
503     subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
504         GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
505         GST_TYPE_QT_MUX_PAD);
506     gst_element_class_add_pad_template (element_class, subtitlesinktempl);
507   }
508
509   if (params->caption_sink_caps) {
510     captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
511         GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
512         GST_TYPE_QT_MUX_PAD);
513     gst_element_class_add_pad_template (element_class, captionsinktempl);
514   }
515
516   klass->format = params->prop->format;
517 }
518
519 static void
520 gst_qt_mux_class_init (GstQTMuxClass * klass)
521 {
522   GObjectClass *gobject_class;
523   GstElementClass *gstelement_class;
524   GParamFlags streamable_flags;
525   const gchar *streamable_desc;
526   gboolean streamable;
527 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
528   "be streamed and hence no indexes written or duration written."
529
530   gobject_class = (GObjectClass *) klass;
531   gstelement_class = (GstElementClass *) klass;
532
533   parent_class = g_type_class_peek_parent (klass);
534
535   gobject_class->finalize = gst_qt_mux_finalize;
536   gobject_class->get_property = gst_qt_mux_get_property;
537   gobject_class->set_property = gst_qt_mux_set_property;
538
539   streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
540   if (klass->format == GST_QT_MUX_FORMAT_ISML) {
541     streamable_desc = STREAMABLE_DESC;
542     streamable = DEFAULT_STREAMABLE;
543   } else {
544     streamable_desc =
545         STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
546     streamable_flags |= G_PARAM_DEPRECATED;
547     streamable = FALSE;
548   }
549
550   g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
551       g_param_spec_uint ("movie-timescale", "Movie timescale",
552           "Timescale to use in the movie (units per second, 0 == default)",
553           0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
554           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
555   g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
556       g_param_spec_uint ("trak-timescale", "Track timescale",
557           "Timescale to use for the tracks (units per second, 0 is automatic)",
558           0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
559           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
560   g_object_class_install_property (gobject_class, PROP_DO_CTTS,
561       g_param_spec_boolean ("presentation-time",
562           "Include presentation-time info",
563           "Calculate and include presentation/composition time "
564           "(in addition to decoding time)", DEFAULT_DO_CTTS,
565           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
566 #ifndef GST_REMOVE_DEPRECATED
567   g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
568       g_param_spec_enum ("dts-method", "dts-method",
569           "Method to determine DTS time (DEPRECATED)",
570           GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
571           G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
572           G_PARAM_STATIC_STRINGS));
573 #endif
574   g_object_class_install_property (gobject_class, PROP_FAST_START,
575       g_param_spec_boolean ("faststart", "Format file to faststart",
576           "If the file should be formatted for faststart (headers first)",
577           DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
578   g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
579       g_param_spec_string ("faststart-file", "File to use for storing buffers",
580           "File that will be used temporarily to store data from the stream "
581           "when creating a faststart file. If null a filepath will be "
582           "created automatically", DEFAULT_FAST_START_TEMP_FILE,
583           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
584   g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
585       g_param_spec_string ("moov-recovery-file",
586           "File to store data for posterior moov atom recovery",
587           "File to be used to store "
588           "data for moov atom making movie file recovery possible in case "
589           "of a crash during muxing. Null for disabled. (Experimental)",
590           DEFAULT_MOOV_RECOV_FILE,
591           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
592   g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
593       g_param_spec_uint ("fragment-duration", "Fragment duration",
594           "Fragment durations in ms (produce a fragmented file if > 0)",
595           0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
596           2000 : DEFAULT_FRAGMENT_DURATION,
597           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
598   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
599       g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
600           streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
601   g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
602       g_param_spec_uint64 ("reserved-max-duration",
603           "Reserved maximum file duration (ns)",
604           "When set to a value > 0, reserves space for index tables at the "
605           "beginning of the file.",
606           0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
607           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
608   g_object_class_install_property (gobject_class,
609       PROP_RESERVED_DURATION_REMAINING,
610       g_param_spec_uint64 ("reserved-duration-remaining",
611           "Report the approximate amount of remaining recording space (ns)",
612           "Reports the approximate amount of remaining moov header space "
613           "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
614           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
615   g_object_class_install_property (gobject_class,
616       PROP_RESERVED_MOOV_UPDATE_PERIOD,
617       g_param_spec_uint64 ("reserved-moov-update-period",
618           "Interval at which to update index tables (ns)",
619           "When used with reserved-max-duration, periodically updates the "
620           "index tables with information muxed so far.", 0, G_MAXUINT64,
621           DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
622           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
623   g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
624       g_param_spec_uint ("reserved-bytes-per-sec",
625           "Reserved MOOV bytes per second, per track",
626           "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
627           0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
628           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
629   g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
630       g_param_spec_boolean ("reserved-prefill",
631           "Reserved Prefill Samples Table",
632           "Prefill samples table of reserved duration",
633           DEFAULT_RESERVED_PREFILL,
634           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
635   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
636       g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
637           "Interleave between streams in bytes",
638           0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
639           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
640   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
641       g_param_spec_uint64 ("interleave-time", "Interleave (time)",
642           "Interleave between streams in nanoseconds",
643           0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
644           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
645   g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
646       g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
647           "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
648           0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
649           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
650
651   gstelement_class->request_new_pad =
652       GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
653   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
654   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
655 }
656
657 static void
658 gst_qt_mux_pad_reset (GstQTPad * qtpad)
659 {
660   qtpad->fourcc = 0;
661   qtpad->is_out_of_order = FALSE;
662   qtpad->sample_size = 0;
663   qtpad->sync = FALSE;
664   qtpad->last_dts = 0;
665   qtpad->sample_offset = 0;
666   qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
667   qtpad->first_ts = GST_CLOCK_TIME_NONE;
668   qtpad->first_dts = GST_CLOCK_TIME_NONE;
669   qtpad->prepare_buf_func = NULL;
670   qtpad->create_empty_buffer = NULL;
671   qtpad->avg_bitrate = 0;
672   qtpad->max_bitrate = 0;
673   qtpad->total_duration = 0;
674   qtpad->total_bytes = 0;
675   qtpad->sparse = FALSE;
676
677   gst_buffer_replace (&qtpad->last_buf, NULL);
678
679   if (qtpad->tags) {
680     gst_tag_list_unref (qtpad->tags);
681     qtpad->tags = NULL;
682   }
683
684   /* reference owned elsewhere */
685   qtpad->trak = NULL;
686   qtpad->tc_trak = NULL;
687
688   if (qtpad->traf) {
689     atom_traf_free (qtpad->traf);
690     qtpad->traf = NULL;
691   }
692   atom_array_clear (&qtpad->fragment_buffers);
693   if (qtpad->samples)
694     g_array_unref (qtpad->samples);
695   qtpad->samples = NULL;
696
697   /* reference owned elsewhere */
698   qtpad->tfra = NULL;
699
700   qtpad->first_pts = GST_CLOCK_TIME_NONE;
701   qtpad->tc_pos = -1;
702   if (qtpad->first_tc)
703     gst_video_time_code_free (qtpad->first_tc);
704   qtpad->first_tc = NULL;
705
706   if (qtpad->raw_audio_adapter)
707     gst_object_unref (qtpad->raw_audio_adapter);
708   qtpad->raw_audio_adapter = NULL;
709 }
710
711 /*
712  * Takes GstQTMux back to its initial state
713  */
714 static void
715 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
716 {
717   GSList *walk;
718
719   qtmux->state = GST_QT_MUX_STATE_NONE;
720   qtmux->header_size = 0;
721   qtmux->mdat_size = 0;
722   qtmux->moov_pos = 0;
723   qtmux->mdat_pos = 0;
724   qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
725   qtmux->fragment_sequence = 0;
726
727   if (qtmux->ftyp) {
728     atom_ftyp_free (qtmux->ftyp);
729     qtmux->ftyp = NULL;
730   }
731   if (qtmux->moov) {
732     atom_moov_free (qtmux->moov);
733     qtmux->moov = NULL;
734   }
735   if (qtmux->mfra) {
736     atom_mfra_free (qtmux->mfra);
737     qtmux->mfra = NULL;
738   }
739   if (qtmux->fast_start_file) {
740     fclose (qtmux->fast_start_file);
741     g_remove (qtmux->fast_start_file_path);
742     qtmux->fast_start_file = NULL;
743   }
744   if (qtmux->moov_recov_file) {
745     fclose (qtmux->moov_recov_file);
746     qtmux->moov_recov_file = NULL;
747   }
748   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
749     AtomInfo *ainfo = (AtomInfo *) walk->data;
750     ainfo->free_func (ainfo->atom);
751     g_free (ainfo);
752   }
753   g_slist_free (qtmux->extra_atoms);
754   qtmux->extra_atoms = NULL;
755
756   GST_OBJECT_LOCK (qtmux);
757   gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
758   GST_OBJECT_UNLOCK (qtmux);
759
760   /* reset pad data */
761   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
762     GstQTPad *qtpad = (GstQTPad *) walk->data;
763     gst_qt_mux_pad_reset (qtpad);
764
765     /* hm, moov_free above yanked the traks away from us,
766      * so do not free, but do clear */
767     qtpad->trak = NULL;
768   }
769
770   if (alloc) {
771     qtmux->moov = atom_moov_new (qtmux->context);
772     /* ensure all is as nice and fresh as request_new_pad would provide it */
773     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
774       GstQTPad *qtpad = (GstQTPad *) walk->data;
775
776       qtpad->trak = atom_trak_new (qtmux->context);
777       atom_moov_add_trak (qtmux->moov, qtpad->trak);
778     }
779   }
780
781   qtmux->current_pad = NULL;
782   qtmux->current_chunk_size = 0;
783   qtmux->current_chunk_duration = 0;
784   qtmux->current_chunk_offset = -1;
785
786   qtmux->reserved_moov_size = 0;
787   qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
788   qtmux->muxed_since_last_update = 0;
789   qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
790 }
791
792 static void
793 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
794 {
795   GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
796   GstPadTemplate *templ;
797
798   templ = gst_element_class_get_pad_template (klass, "src");
799   qtmux->srcpad = gst_pad_new_from_template (templ, "src");
800   gst_pad_use_fixed_caps (qtmux->srcpad);
801   gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
802
803   qtmux->sinkpads = NULL;
804   qtmux->collect = gst_collect_pads_new ();
805   gst_collect_pads_set_event_function (qtmux->collect,
806       GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
807   gst_collect_pads_set_clip_function (qtmux->collect,
808       GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
809   gst_collect_pads_set_function (qtmux->collect,
810       GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
811
812   /* properties set to default upon construction */
813
814   qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
815   qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
816   qtmux->reserved_bytes_per_sec_per_trak =
817       DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
818   qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
819   qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
820   qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
821
822   /* always need this */
823   qtmux->context =
824       atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
825
826   /* internals to initial state */
827   gst_qt_mux_reset (qtmux, TRUE);
828 }
829
830
831 static void
832 gst_qt_mux_finalize (GObject * object)
833 {
834   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
835
836   gst_qt_mux_reset (qtmux, FALSE);
837
838   g_free (qtmux->fast_start_file_path);
839   g_free (qtmux->moov_recov_file_path);
840
841   atoms_context_free (qtmux->context);
842   gst_object_unref (qtmux->collect);
843
844   g_slist_free (qtmux->sinkpads);
845
846   G_OBJECT_CLASS (parent_class)->finalize (object);
847 }
848
849 static GstBuffer *
850 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
851     GstQTMux * qtmux)
852 {
853   GstBuffer *newbuf;
854   GstMapInfo map;
855   gsize size;
856
857   GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
858
859   if (buf == NULL)
860     return NULL;
861
862   size = gst_buffer_get_size (buf);
863   newbuf = gst_buffer_new_and_alloc (size + 8);
864   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
865
866   gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
867   GST_WRITE_UINT32_BE (map.data, map.size);
868   GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
869
870   gst_buffer_unmap (buf, &map);
871   gst_buffer_unref (buf);
872
873   return newbuf;
874 }
875
876 static gsize
877 extract_608_field_from_cc_data (const guint8 * ccdata, gsize ccdata_size,
878     guint field, guint8 ** res)
879 {
880   guint8 *storage;
881   gsize storage_size = 128;
882   gsize i, res_size = 0;
883
884   storage = g_malloc0 (storage_size);
885
886   /* Iterate over the ccdata and put the corresponding tuples for the given field
887    * in the storage */
888   for (i = 0; i < ccdata_size; i += 3) {
889     if ((field == 1 && ccdata[i * 3] == 0xfc) ||
890         (field == 2 && ccdata[i * 3] == 0xfd)) {
891       GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
892           ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
893       if (res_size >= storage_size) {
894         storage_size += 128;
895         storage = g_realloc (storage, storage_size);
896       }
897       storage[res_size] = ccdata[i * 3 + 1];
898       storage[res_size + 1] = ccdata[i * 3 + 2];
899       res_size += 2;
900     }
901   }
902
903   if (res_size == 0) {
904     g_free (storage);
905     *res = NULL;
906     return 0;
907   }
908
909   *res = storage;
910   return res_size;
911 }
912
913
914 static GstBuffer *
915 gst_qt_mux_prepare_caption_buffer (GstQTPad * qtpad, GstBuffer * buf,
916     GstQTMux * qtmux)
917 {
918   GstBuffer *newbuf = NULL;
919   GstMapInfo map, inmap;
920   gsize size;
921   gboolean in_prefill;
922
923   if (buf == NULL)
924     return NULL;
925
926   in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
927
928   size = gst_buffer_get_size (buf);
929   gst_buffer_map (buf, &inmap, GST_MAP_READ);
930
931   GST_LOG_OBJECT (qtmux,
932       "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
933       GST_FOURCC_ARGS (qtpad->fourcc), size);
934
935   switch (qtpad->fourcc) {
936     case FOURCC_c608:
937     {
938       guint8 *cdat, *cdt2;
939       gsize cdat_size, cdt2_size, total_size = 0;
940       gsize write_offs = 0;
941
942       cdat_size =
943           extract_608_field_from_cc_data (inmap.data, inmap.size, 1, &cdat);
944       cdt2_size =
945           extract_608_field_from_cc_data (inmap.data, inmap.size, 2, &cdt2);
946
947       if (cdat_size)
948         total_size += cdat_size + 8;
949       if (cdt2_size)
950         total_size += cdt2_size + 8;
951       if (total_size == 0) {
952         GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
953         /* FIXME : We might want to *always* store something, even if
954          * it's "empty" CC (i.e. 0x80 0x80) */
955         break;
956       }
957
958       newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
959       /* Let's copy over all metadata and not the memory */
960       gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
961
962       gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
963       if (cdat_size || in_prefill) {
964         GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
965         GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
966         if (cdat_size)
967           memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
968         else {
969           /* Write 'empty' CC */
970           map.data[8] = 0x80;
971           map.data[9] = 0x80;
972         }
973         write_offs = in_prefill ? 10 : cdat_size + 8;
974         if (cdat_size)
975           g_free (cdat);
976       }
977
978       if (cdt2_size || in_prefill) {
979         GST_WRITE_UINT32_BE (map.data + write_offs,
980             in_prefill ? 10 : cdt2_size + 8);
981         GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
982         if (cdt2_size)
983           memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
984         else {
985           /* Write 'empty' CC */
986           map.data[write_offs + 8] = 0x80;
987           map.data[write_offs + 9] = 0x80;
988         }
989         if (cdt2_size)
990           g_free (cdt2);
991       }
992       gst_buffer_unmap (newbuf, &map);
993       break;
994     }
995       break;
996     case FOURCC_c708:
997     {
998       /* Take the whole CDP */
999       if (in_prefill && size > 256) {
1000         GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1001         break;
1002       }
1003       newbuf = gst_buffer_new_and_alloc (in_prefill ? 256 + 8 : size + 8);
1004
1005       /* Let's copy over all metadata and not the memory */
1006       gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1007
1008       gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1009
1010       GST_WRITE_UINT32_BE (map.data, size + 8);
1011       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1012       memcpy (map.data + 8, inmap.data, inmap.size);
1013
1014       gst_buffer_unmap (newbuf, &map);
1015       break;
1016     }
1017     default:
1018       /* theoretically this should never happen, but let's keep this here in case */
1019       GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1020       break;
1021   }
1022
1023   gst_buffer_unmap (buf, &inmap);
1024   gst_buffer_unref (buf);
1025
1026   return newbuf;
1027 }
1028
1029 static GstBuffer *
1030 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1031     GstQTMux * qtmux)
1032 {
1033   GstBuffer *newbuf;
1034   GstMapInfo frommap;
1035   GstMapInfo tomap;
1036   gsize size;
1037   const guint8 *dataend;
1038
1039   GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1040
1041   if (buf == NULL)
1042     return NULL;
1043
1044   gst_buffer_map (buf, &frommap, GST_MAP_READ);
1045
1046   dataend = memchr (frommap.data, 0, frommap.size);
1047   size = dataend ? dataend - frommap.data : frommap.size;
1048   newbuf = gst_buffer_new_and_alloc (size + 2);
1049
1050   gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1051
1052   GST_WRITE_UINT16_BE (tomap.data, size);
1053   memcpy (tomap.data + 2, frommap.data, size);
1054
1055   gst_buffer_unmap (newbuf, &tomap);
1056   gst_buffer_unmap (buf, &frommap);
1057
1058   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1059
1060   /* gst_buffer_copy_into is trying to be too clever and
1061    * won't copy duration when size is different */
1062   GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1063
1064   gst_buffer_unref (buf);
1065
1066   return newbuf;
1067 }
1068
1069 static void
1070 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1071     guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1072     guint8 lfe_on)
1073 {
1074   AtomInfo *ext;
1075
1076   g_return_if_fail (qtpad->trak_ste);
1077
1078   ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1);        /* bitrate_code is inside frmsizcod */
1079
1080   sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1081 }
1082
1083 static GstBuffer *
1084 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1085     GstQTMux * qtmux)
1086 {
1087   GstMapInfo map;
1088   GstByteReader reader;
1089   guint off;
1090
1091   if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1092     GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1093     return buf;
1094   }
1095
1096   if (G_UNLIKELY (map.size < 8))
1097     goto done;
1098
1099   gst_byte_reader_init (&reader, map.data, map.size);
1100   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1101       0, map.size);
1102
1103   if (off != -1) {
1104     GstBitReader bits;
1105     guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1106
1107     GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1108         off);
1109
1110     gst_bit_reader_init (&bits, map.data, map.size);
1111
1112     /* off + sync + crc */
1113     gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1114
1115     fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1116     frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1117     bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1118     bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1119     acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1120
1121     if ((acmod & 0x1) && (acmod != 0x1))        /* 3 front channels */
1122       gst_bit_reader_skip_unchecked (&bits, 2);
1123     if ((acmod & 0x4))          /* if a surround channel exists */
1124       gst_bit_reader_skip_unchecked (&bits, 2);
1125     if (acmod == 0x2)           /* if in 2/0 mode */
1126       gst_bit_reader_skip_unchecked (&bits, 2);
1127
1128     lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1129
1130     gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1131         bsmod, acmod, lfe_on);
1132
1133     /* AC-3 spec says that those values should be constant for the
1134      * whole stream when muxed in mp4. We trust the input follows it */
1135     GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1136         "prepare buffer function");
1137     qtpad->prepare_buf_func = NULL;
1138   }
1139
1140 done:
1141   gst_buffer_unmap (buf, &map);
1142   return buf;
1143 }
1144
1145 static GstBuffer *
1146 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1147 {
1148   guint8 *data;
1149
1150   data = g_malloc (2);
1151   GST_WRITE_UINT16_BE (data, 0);
1152
1153   return gst_buffer_new_wrapped (data, 2);
1154 }
1155
1156 static void
1157 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1158     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1159 {
1160   switch (gst_tag_get_type (tag)) {
1161       /* strings */
1162     case G_TYPE_STRING:
1163     {
1164       gchar *str = NULL;
1165
1166       if (!gst_tag_list_get_string (list, tag, &str) || !str)
1167         break;
1168       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1169           GST_FOURCC_ARGS (fourcc), str);
1170       atom_udta_add_str_tag (udta, fourcc, str);
1171       g_free (str);
1172       break;
1173     }
1174       /* double */
1175     case G_TYPE_DOUBLE:
1176     {
1177       gdouble value;
1178
1179       if (!gst_tag_list_get_double (list, tag, &value))
1180         break;
1181       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1182           GST_FOURCC_ARGS (fourcc), (gint) value);
1183       atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1184       break;
1185     }
1186     case G_TYPE_UINT:
1187     {
1188       guint value = 0;
1189       if (tag2) {
1190         /* paired unsigned integers */
1191         guint count = 0;
1192         gboolean got_tag;
1193
1194         got_tag = gst_tag_list_get_uint (list, tag, &value);
1195         got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1196         if (!got_tag)
1197           break;
1198         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1199             GST_FOURCC_ARGS (fourcc), value, count);
1200         atom_udta_add_uint_tag (udta, fourcc, 0,
1201             value << 16 | (count & 0xFFFF));
1202       } else {
1203         /* unpaired unsigned integers */
1204         if (!gst_tag_list_get_uint (list, tag, &value))
1205           break;
1206         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1207             GST_FOURCC_ARGS (fourcc), value);
1208         atom_udta_add_uint_tag (udta, fourcc, 1, value);
1209       }
1210       break;
1211     }
1212     default:
1213       g_assert_not_reached ();
1214       break;
1215   }
1216 }
1217
1218 static void
1219 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1220     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1221 {
1222   GDate *date = NULL;
1223   GDateYear year;
1224   GDateMonth month;
1225   GDateDay day;
1226   gchar *str;
1227
1228   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1229
1230   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1231     return;
1232
1233   year = g_date_get_year (date);
1234   month = g_date_get_month (date);
1235   day = g_date_get_day (date);
1236
1237   g_date_free (date);
1238
1239   if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1240       day == G_DATE_BAD_DAY) {
1241     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1242     return;
1243   }
1244
1245   str = g_strdup_printf ("%u-%u-%u", year, month, day);
1246   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1247       GST_FOURCC_ARGS (fourcc), str);
1248   atom_udta_add_str_tag (udta, fourcc, str);
1249   g_free (str);
1250 }
1251
1252 static void
1253 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1254     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1255 {
1256   GValue value = { 0, };
1257   GstBuffer *buf;
1258   GstSample *sample;
1259   GstCaps *caps;
1260   GstStructure *structure;
1261   gint flags = 0;
1262   GstMapInfo map;
1263
1264   g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1265
1266   if (!gst_tag_list_copy_value (&value, list, tag))
1267     return;
1268
1269   sample = gst_value_get_sample (&value);
1270
1271   if (!sample)
1272     goto done;
1273
1274   buf = gst_sample_get_buffer (sample);
1275   if (!buf)
1276     goto done;
1277
1278   caps = gst_sample_get_caps (sample);
1279   if (!caps) {
1280     GST_WARNING_OBJECT (qtmux, "preview image without caps");
1281     goto done;
1282   }
1283
1284   GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1285
1286   structure = gst_caps_get_structure (caps, 0);
1287   if (gst_structure_has_name (structure, "image/jpeg"))
1288     flags = 13;
1289   else if (gst_structure_has_name (structure, "image/png"))
1290     flags = 14;
1291
1292   if (!flags) {
1293     GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1294     goto done;
1295   }
1296
1297   gst_buffer_map (buf, &map, GST_MAP_READ);
1298   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1299       " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1300   atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1301   gst_buffer_unmap (buf, &map);
1302 done:
1303   g_value_unset (&value);
1304 }
1305
1306 static void
1307 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1308     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1309 {
1310   gchar *str = NULL;
1311   guint number;
1312
1313   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1314   g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1315
1316   if (!gst_tag_list_get_string (list, tag, &str) || !str)
1317     return;
1318
1319   if (tag2)
1320     if (!gst_tag_list_get_uint (list, tag2, &number))
1321       tag2 = NULL;
1322
1323   if (!tag2) {
1324     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1325         GST_FOURCC_ARGS (fourcc), str);
1326     atom_udta_add_3gp_str_tag (udta, fourcc, str);
1327   } else {
1328     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1329         GST_FOURCC_ARGS (fourcc), str, number);
1330     atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1331   }
1332
1333   g_free (str);
1334 }
1335
1336 static void
1337 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1338     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1339 {
1340   GDate *date = NULL;
1341   GDateYear year;
1342
1343   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1344
1345   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1346     return;
1347
1348   year = g_date_get_year (date);
1349   g_date_free (date);
1350
1351   if (year == G_DATE_BAD_YEAR) {
1352     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1353     return;
1354   }
1355
1356   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1357       GST_FOURCC_ARGS (fourcc), year);
1358   atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1359 }
1360
1361 static void
1362 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1363     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1364 {
1365   gdouble latitude = -360, longitude = -360, altitude = 0;
1366   gchar *location = NULL;
1367   guint8 *data, *ddata;
1368   gint size = 0, len = 0;
1369   gboolean ret = FALSE;
1370
1371   g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1372
1373   ret = gst_tag_list_get_string (list, tag, &location);
1374   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1375       &longitude);
1376   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1377       &latitude);
1378   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1379       &altitude);
1380
1381   if (!ret)
1382     return;
1383
1384   if (location)
1385     len = strlen (location);
1386   size += len + 1 + 2;
1387
1388   /* role + (long, lat, alt) + body + notes */
1389   size += 1 + 3 * 4 + 1 + 1;
1390
1391   data = ddata = g_malloc (size);
1392
1393   /* language tag */
1394   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1395   /* location */
1396   if (location)
1397     memcpy (data + 2, location, len);
1398   GST_WRITE_UINT8 (data + 2 + len, 0);
1399   data += len + 1 + 2;
1400   /* role */
1401   GST_WRITE_UINT8 (data, 0);
1402   /* long, lat, alt */
1403 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1404   QT_WRITE_SFP32 (data + 1, longitude);
1405   QT_WRITE_SFP32 (data + 5, latitude);
1406   QT_WRITE_SFP32 (data + 9, altitude);
1407   /* neither astronomical body nor notes */
1408   GST_WRITE_UINT16_BE (data + 13, 0);
1409
1410   GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1411   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1412   g_free (ddata);
1413 }
1414
1415 static void
1416 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1417     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1418 {
1419   gchar *keywords = NULL;
1420   guint8 *data, *ddata;
1421   gint size = 0, i;
1422   gchar **kwds;
1423
1424   g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1425
1426   if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1427     return;
1428
1429   kwds = g_strsplit (keywords, ",", 0);
1430   g_free (keywords);
1431
1432   size = 0;
1433   for (i = 0; kwds[i]; i++) {
1434     /* size byte + null-terminator */
1435     size += strlen (kwds[i]) + 1 + 1;
1436   }
1437
1438   /* language tag + count + keywords */
1439   size += 2 + 1;
1440
1441   data = ddata = g_malloc (size);
1442
1443   /* language tag */
1444   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1445   /* count */
1446   GST_WRITE_UINT8 (data + 2, i);
1447   data += 3;
1448   /* keywords */
1449   for (i = 0; kwds[i]; ++i) {
1450     gint len = strlen (kwds[i]);
1451
1452     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1453         GST_FOURCC_ARGS (fourcc), kwds[i]);
1454     /* size */
1455     GST_WRITE_UINT8 (data, len + 1);
1456     memcpy (data + 1, kwds[i], len + 1);
1457     data += len + 2;
1458   }
1459
1460   g_strfreev (kwds);
1461
1462   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1463   g_free (ddata);
1464 }
1465
1466 static gboolean
1467 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1468     guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1469 {
1470   guint32 fourcc;
1471   gint table;
1472   gint size;
1473   const gchar *data;
1474
1475   data = input;
1476   size = strlen (input);
1477
1478   if (size < 4 + 3 + 1 + 1 + 1) {
1479     /* at least the minimum xxxx://y/z */
1480     GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1481         "ignoring", input);
1482     return FALSE;
1483   }
1484
1485   /* read the fourcc */
1486   memcpy (&fourcc, data, 4);
1487   size -= 4;
1488   data += 4;
1489
1490   if (strncmp (data, "://", 3) != 0) {
1491     goto mismatch;
1492   }
1493   data += 3;
1494   size -= 3;
1495
1496   /* read the table number */
1497   if (sscanf (data, "%d", &table) != 1) {
1498     goto mismatch;
1499   }
1500   if (table < 0) {
1501     GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1502         ", table numbers should be positive, ignoring tag", table);
1503     return FALSE;
1504   }
1505
1506   /* find the next / */
1507   while (size > 0 && data[0] != '/') {
1508     data += 1;
1509     size -= 1;
1510   }
1511   if (size == 0) {
1512     goto mismatch;
1513   }
1514   g_assert (data[0] == '/');
1515
1516   /* skip the '/' */
1517   data += 1;
1518   size -= 1;
1519   if (size == 0) {
1520     goto mismatch;
1521   }
1522
1523   /* read up the rest of the string */
1524   *p_content = g_strdup (data);
1525   *p_table = (guint16) table;
1526   *p_fourcc = fourcc;
1527   return TRUE;
1528
1529 mismatch:
1530   {
1531     GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1532         "input (%s) didn't match the expected entitycode://table/content",
1533         input);
1534     return FALSE;
1535   }
1536 }
1537
1538 static void
1539 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1540     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1541 {
1542   gchar *clsf_data = NULL;
1543   gint size = 0;
1544   guint32 entity = 0;
1545   guint16 table = 0;
1546   gchar *content = NULL;
1547   guint8 *data;
1548
1549   g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1550
1551   if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1552     return;
1553
1554   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1555       GST_FOURCC_ARGS (fourcc), clsf_data);
1556
1557   /* parse the string, format is:
1558    * entityfourcc://table/content
1559    */
1560   gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1561       &content);
1562   g_free (clsf_data);
1563   /* +1 for the \0 */
1564   size = strlen (content) + 1;
1565
1566   /* now we have everything, build the atom
1567    * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1568   data = g_malloc (4 + 2 + 2 + size);
1569   GST_WRITE_UINT32_LE (data, entity);
1570   GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1571   GST_WRITE_UINT16_BE (data + 6, 0);
1572   memcpy (data + 8, content, size);
1573   g_free (content);
1574
1575   atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1576   g_free (data);
1577 }
1578
1579 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1580     const GstTagList * list, AtomUDTA * udta, const char *tag,
1581     const char *tag2, guint32 fourcc);
1582
1583 /*
1584  * Struct to record mappings from gstreamer tags to fourcc codes
1585  */
1586 typedef struct _GstTagToFourcc
1587 {
1588   guint32 fourcc;
1589   const gchar *gsttag;
1590   const gchar *gsttag2;
1591   const GstQTMuxAddUdtaTagFunc func;
1592 } GstTagToFourcc;
1593
1594 /* tag list tags to fourcc matching */
1595 static const GstTagToFourcc tag_matches_mp4[] = {
1596   {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1597   {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1598   {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1599   {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1600   {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1601   {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1602   {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1603   {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1604   {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1605   {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1606   {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1607   {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1608   {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1609   {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1610   {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1611   {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1612   {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1613   {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1614   {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1615   {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1616   {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1617   {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1618   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1619   {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1620   {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1621   {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1622   {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1623       gst_qt_mux_add_mp4_tag},
1624   {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1625       gst_qt_mux_add_mp4_tag},
1626   {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1627   {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1628   {0, NULL,}
1629 };
1630
1631 static const GstTagToFourcc tag_matches_3gp[] = {
1632   {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1633   {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1634   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1635   {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1636   {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1637   {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1638   {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1639   {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1640   {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1641   {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1642   {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1643       gst_qt_mux_add_3gp_classification},
1644   {0, NULL,}
1645 };
1646
1647 /* qtdemux produces these for atoms it cannot parse */
1648 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1649
1650 static void
1651 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1652 {
1653   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1654   GstBuffer *xmp = NULL;
1655
1656   /* adobe specs only have 'quicktime' and 'mp4',
1657    * but I guess we can extrapolate to gpp.
1658    * Keep mj2 out for now as we don't add any tags for it yet.
1659    * If you have further info about xmp on these formats, please share */
1660   if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1661     return;
1662
1663   GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1664
1665   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1666     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1667         list, TRUE);
1668     if (xmp)
1669       atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1670   } else {
1671     AtomInfo *ainfo;
1672     /* for isom/mp4, it is a top level uuid atom */
1673     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1674         list, TRUE);
1675     if (xmp) {
1676       ainfo = build_uuid_xmp_atom (xmp);
1677       if (ainfo) {
1678         qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1679       }
1680     }
1681   }
1682   if (xmp)
1683     gst_buffer_unref (xmp);
1684 }
1685
1686 static void
1687 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1688     AtomUDTA * udta)
1689 {
1690   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1691   guint32 fourcc;
1692   gint i;
1693   const gchar *tag, *tag2;
1694   const GstTagToFourcc *tag_matches;
1695
1696   switch (qtmux_klass->format) {
1697     case GST_QT_MUX_FORMAT_3GP:
1698       tag_matches = tag_matches_3gp;
1699       break;
1700     case GST_QT_MUX_FORMAT_MJ2:
1701       tag_matches = NULL;
1702       break;
1703     default:
1704       /* sort of iTunes style for mp4 and QT (?) */
1705       tag_matches = tag_matches_mp4;
1706       break;
1707   }
1708
1709   if (!tag_matches)
1710     return;
1711
1712   /* Clear existing tags so we don't add them over and over */
1713   atom_udta_clear_tags (udta);
1714
1715   for (i = 0; tag_matches[i].fourcc; i++) {
1716     fourcc = tag_matches[i].fourcc;
1717     tag = tag_matches[i].gsttag;
1718     tag2 = tag_matches[i].gsttag2;
1719
1720     g_assert (tag_matches[i].func);
1721     tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1722   }
1723
1724   /* add unparsed blobs if present */
1725   if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1726     guint num_tags;
1727
1728     num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1729     for (i = 0; i < num_tags; ++i) {
1730       GstSample *sample = NULL;
1731       GstBuffer *buf;
1732       const GstStructure *s;
1733
1734       if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1735               &sample))
1736         continue;
1737       buf = gst_sample_get_buffer (sample);
1738
1739       if (buf && (s = gst_sample_get_info (sample))) {
1740         const gchar *style = NULL;
1741         GstMapInfo map;
1742
1743         gst_buffer_map (buf, &map, GST_MAP_READ);
1744         GST_DEBUG_OBJECT (qtmux,
1745             "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1746             GST_PTR_FORMAT, i, num_tags, map.size, s);
1747         if (s && (style = gst_structure_get_string (s, "style"))) {
1748           /* try to prevent some style tag ending up into another variant
1749            * (todo: make into a list if more cases) */
1750           if ((strcmp (style, "itunes") == 0 &&
1751                   qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1752               (strcmp (style, "iso") == 0 &&
1753                   qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1754             GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1755             atom_udta_add_blob_tag (udta, map.data, map.size);
1756           }
1757         }
1758         gst_buffer_unmap (buf, &map);
1759       }
1760       gst_sample_unref (sample);
1761     }
1762   }
1763
1764   return;
1765 }
1766
1767 /*
1768  * Gets the tagsetter iface taglist and puts the known tags
1769  * into the output stream
1770  */
1771 static void
1772 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1773 {
1774   const GstTagList *tags = NULL;
1775   GSList *walk;
1776
1777   GST_OBJECT_LOCK (qtmux);
1778   if (qtmux->tags_changed) {
1779     tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1780     qtmux->tags_changed = FALSE;
1781   }
1782   GST_OBJECT_UNLOCK (qtmux);
1783
1784   GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1785
1786   if (tags && !gst_tag_list_is_empty (tags)) {
1787     GstTagList *copy = gst_tag_list_copy (tags);
1788
1789     GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1790     gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1791     gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1792     gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1793
1794     GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1795     gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1796     gst_qt_mux_add_xmp_tags (qtmux, copy);
1797     gst_tag_list_unref (copy);
1798   } else {
1799     GST_DEBUG_OBJECT (qtmux, "No new tags received");
1800   }
1801
1802   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1803     GstCollectData *cdata = (GstCollectData *) walk->data;
1804     GstQTPad *qpad = (GstQTPad *) cdata;
1805     GstPad *pad = qpad->collect.pad;
1806
1807     if (qpad->tags_changed && qpad->tags) {
1808       GST_DEBUG_OBJECT (pad, "Adding tags");
1809       gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1810       gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1811       qpad->tags_changed = FALSE;
1812       GST_DEBUG_OBJECT (pad, "Tags added");
1813     } else {
1814       GST_DEBUG_OBJECT (pad, "No new tags received");
1815     }
1816   }
1817 }
1818
1819 static inline GstBuffer *
1820 _gst_buffer_new_take_data (guint8 * data, guint size)
1821 {
1822   GstBuffer *buf;
1823
1824   buf = gst_buffer_new ();
1825   gst_buffer_append_memory (buf,
1826       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1827
1828   return buf;
1829 }
1830
1831 static GstFlowReturn
1832 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1833     gboolean mind_fast)
1834 {
1835   GstFlowReturn res;
1836   gsize size;
1837
1838   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1839
1840   size = gst_buffer_get_size (buf);
1841   GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1842
1843   if (mind_fast && qtmux->fast_start_file) {
1844     GstMapInfo map;
1845     gint ret;
1846
1847     GST_LOG_OBJECT (qtmux, "to temporary file");
1848     gst_buffer_map (buf, &map, GST_MAP_READ);
1849     ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1850     gst_buffer_unmap (buf, &map);
1851     gst_buffer_unref (buf);
1852     if (ret != size)
1853       goto write_error;
1854     else
1855       res = GST_FLOW_OK;
1856   } else {
1857     GST_LOG_OBJECT (qtmux, "downstream");
1858     res = gst_pad_push (qtmux->srcpad, buf);
1859   }
1860
1861   if (G_LIKELY (offset))
1862     *offset += size;
1863
1864   return res;
1865
1866   /* ERRORS */
1867 write_error:
1868   {
1869     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1870         ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1871     return GST_FLOW_ERROR;
1872   }
1873 }
1874
1875 static gboolean
1876 gst_qt_mux_seek_to_beginning (FILE * f)
1877 {
1878 #ifdef HAVE_FSEEKO
1879   if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1880     return FALSE;
1881 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1882   if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1883     return FALSE;
1884 #else
1885   if (fseek (f, (long) 0, SEEK_SET) != 0)
1886     return FALSE;
1887 #endif
1888   return TRUE;
1889 }
1890
1891 static GstFlowReturn
1892 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1893 {
1894   GstFlowReturn ret = GST_FLOW_OK;
1895   GstBuffer *buf = NULL;
1896
1897   if (fflush (qtmux->fast_start_file))
1898     goto flush_failed;
1899
1900   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1901     goto seek_failed;
1902
1903   /* hm, this could all take a really really long time,
1904    * but there may not be another way to get moov atom first
1905    * (somehow optimize copy?) */
1906   GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1907   while (ret == GST_FLOW_OK) {
1908     const int bufsize = 4096;
1909     GstMapInfo map;
1910     gsize size;
1911
1912     buf = gst_buffer_new_and_alloc (bufsize);
1913     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1914     size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1915     if (size == 0) {
1916       gst_buffer_unmap (buf, &map);
1917       break;
1918     }
1919     GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1920     gst_buffer_unmap (buf, &map);
1921     if (size != bufsize)
1922       gst_buffer_set_size (buf, size);
1923     ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1924     buf = NULL;
1925   }
1926   if (buf)
1927     gst_buffer_unref (buf);
1928
1929   if (ftruncate (fileno (qtmux->fast_start_file), 0))
1930     goto seek_failed;
1931   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1932     goto seek_failed;
1933
1934   return ret;
1935
1936   /* ERRORS */
1937 flush_failed:
1938   {
1939     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1940         ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1941     ret = GST_FLOW_ERROR;
1942     goto fail;
1943   }
1944 seek_failed:
1945   {
1946     GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1947         ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1948     ret = GST_FLOW_ERROR;
1949     goto fail;
1950   }
1951 fail:
1952   {
1953     /* clear descriptor so we don't remove temp file later on,
1954      * might be possible to recover */
1955     fclose (qtmux->fast_start_file);
1956     qtmux->fast_start_file = NULL;
1957     return ret;
1958   }
1959 }
1960
1961 /*
1962  * Sends the initial mdat atom fields (size fields and fourcc type),
1963  * the subsequent buffers are considered part of it's data.
1964  * As we can't predict the amount of data that we are going to place in mdat
1965  * we need to record the position of the size field in the stream so we can
1966  * seek back to it later and update when the streams have finished.
1967  */
1968 static GstFlowReturn
1969 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1970     gboolean extended, gboolean fsync_after)
1971 {
1972   GstBuffer *buf;
1973   GstMapInfo map;
1974
1975   GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1976       "size %" G_GUINT64_FORMAT, size);
1977
1978   /* if the qtmux state is EOS, really write the mdat, otherwise
1979    * allow size == 0 for a placeholder atom */
1980   if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1981     size += 8;
1982
1983   if (extended) {
1984     gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1985     /* Always write 16-bytes, but put a free atom first
1986      * if the size is < 4GB. */
1987     buf = gst_buffer_new_and_alloc (16);
1988     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1989
1990     if (large_file) {
1991       /* Write extended mdat header and large_size field */
1992       GST_WRITE_UINT32_BE (map.data, 1);
1993       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1994       GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1995     } else {
1996       /* Write an empty free atom, then standard 32-bit mdat */
1997       GST_WRITE_UINT32_BE (map.data, 8);
1998       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1999       GST_WRITE_UINT32_BE (map.data + 8, size);
2000       GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2001     }
2002     gst_buffer_unmap (buf, &map);
2003   } else {
2004     buf = gst_buffer_new_and_alloc (8);
2005     gst_buffer_map (buf, &map, GST_MAP_WRITE);
2006
2007     /* Vanilla 32-bit mdat */
2008     GST_WRITE_UINT32_BE (map.data, size);
2009     GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2010     gst_buffer_unmap (buf, &map);
2011   }
2012
2013   GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2014   if (fsync_after)
2015     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2016
2017   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2018
2019 }
2020
2021 /*
2022  * We get the position of the mdat size field, seek back to it
2023  * and overwrite with the real value
2024  */
2025 static GstFlowReturn
2026 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2027     guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2028 {
2029   GstSegment segment;
2030
2031   /* We must have recorded the mdat position for this to work */
2032   g_assert (mdat_pos != 0);
2033
2034   /* seek and rewrite the header */
2035   gst_segment_init (&segment, GST_FORMAT_BYTES);
2036   segment.start = mdat_pos;
2037   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2038
2039   return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2040       fsync_after);
2041 }
2042
2043 static GstFlowReturn
2044 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2045 {
2046   GstBuffer *buf;
2047   guint64 size = 0, offset = 0;
2048   guint8 *data = NULL;
2049
2050   GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2051
2052   if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2053     goto serialize_error;
2054
2055   buf = _gst_buffer_new_take_data (data, offset);
2056
2057   GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2058   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2059
2060   /* ERRORS */
2061 serialize_error:
2062   {
2063     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2064         ("Failed to serialize ftyp"));
2065     return GST_FLOW_ERROR;
2066   }
2067 }
2068
2069 static void
2070 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2071     GstBuffer ** p_prefix)
2072 {
2073   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2074   guint32 major, version;
2075   GList *comp;
2076   GstBuffer *prefix = NULL;
2077   AtomFTYP *ftyp = NULL;
2078
2079   GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2080
2081   /* init and send context and ftyp based on current property state */
2082   gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2083       &version, &comp, qtmux->moov, qtmux->longest_chunk,
2084       qtmux->fast_start_file != NULL);
2085   ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2086   if (comp)
2087     g_list_free (comp);
2088   if (prefix) {
2089     if (p_prefix)
2090       *p_prefix = prefix;
2091     else
2092       gst_buffer_unref (prefix);
2093   }
2094   *p_ftyp = ftyp;
2095 }
2096
2097 static GstFlowReturn
2098 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2099 {
2100   GstFlowReturn ret = GST_FLOW_OK;
2101   GstBuffer *prefix = NULL;
2102
2103   GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2104
2105   /* init and send context and ftyp based on current property state */
2106   if (qtmux->ftyp) {
2107     atom_ftyp_free (qtmux->ftyp);
2108     qtmux->ftyp = NULL;
2109   }
2110   gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2111   if (prefix) {
2112     ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2113     if (ret != GST_FLOW_OK)
2114       return ret;
2115   }
2116   return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2117 }
2118
2119 static void
2120 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2121 {
2122   GstStructure *structure;
2123   GValue array = { 0 };
2124   GValue value = { 0 };
2125   GstCaps *caps, *tcaps;
2126
2127   tcaps = gst_pad_get_current_caps (mux->srcpad);
2128   caps = gst_caps_copy (tcaps);
2129   gst_caps_unref (tcaps);
2130
2131   structure = gst_caps_get_structure (caps, 0);
2132
2133   g_value_init (&array, GST_TYPE_ARRAY);
2134
2135   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2136   g_value_init (&value, GST_TYPE_BUFFER);
2137   gst_value_take_buffer (&value, gst_buffer_ref (buf));
2138   gst_value_array_append_value (&array, &value);
2139   g_value_unset (&value);
2140
2141   gst_structure_set_value (structure, "streamheader", &array);
2142   g_value_unset (&array);
2143   gst_pad_set_caps (mux->srcpad, caps);
2144   gst_caps_unref (caps);
2145 }
2146
2147 /*
2148  * Write out a free space atom. The offset is adjusted by the full
2149  * size, but a smaller buffer is sent
2150  */
2151 static GstFlowReturn
2152 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2153     gboolean fsync_after)
2154 {
2155   Atom *node_header;
2156   GstBuffer *buf;
2157   guint8 *data = NULL;
2158   guint64 offset = 0, bsize = 0;
2159   GstFlowReturn ret;
2160
2161   GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2162
2163   /* We can't make a free space atom smaller than the header */
2164   if (size < 8)
2165     goto too_small;
2166
2167   node_header = g_malloc0 (sizeof (Atom));
2168   node_header->type = FOURCC_free;
2169   node_header->size = size;
2170
2171   bsize = offset = 0;
2172   if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2173     goto serialize_error;
2174
2175   buf = _gst_buffer_new_take_data (data, offset);
2176   g_free (node_header);
2177
2178   if (fsync_after)
2179     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2180
2181   GST_LOG_OBJECT (qtmux, "Pushing free atom");
2182   ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2183
2184   if (off) {
2185     GstSegment segment;
2186
2187     *off += size - 8;
2188
2189     /* Make sure downstream position ends up at the end of this free box */
2190     gst_segment_init (&segment, GST_FORMAT_BYTES);
2191     segment.start = *off;
2192     gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2193   }
2194
2195   return ret;
2196
2197   /* ERRORS */
2198 too_small:
2199   {
2200     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2201         ("Not enough free reserved space"));
2202     return GST_FLOW_ERROR;
2203   }
2204 serialize_error:
2205   {
2206     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2207         ("Failed to serialize mdat"));
2208     g_free (node_header);
2209     return GST_FLOW_ERROR;
2210   }
2211 }
2212
2213 static void
2214 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2215 {
2216   gboolean fragmented = FALSE;
2217   guint32 timescale;
2218
2219   GST_OBJECT_LOCK (qtmux);
2220   timescale = qtmux->timescale;
2221   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2222       qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2223     fragmented = TRUE;
2224   GST_OBJECT_UNLOCK (qtmux);
2225
2226   /* inform lower layers of our property wishes, and determine duration.
2227    * Let moov take care of this using its list of traks;
2228    * so that released pads are also included */
2229   GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2230       timescale);
2231   atom_moov_update_timescale (qtmux->moov, timescale);
2232   atom_moov_set_fragmented (qtmux->moov, fragmented);
2233
2234   atom_moov_update_duration (qtmux->moov);
2235 }
2236
2237 static GstFlowReturn
2238 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2239     guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2240 {
2241   guint64 offset = 0, size = 0;
2242   guint8 *data;
2243   GstBuffer *buf;
2244   GstFlowReturn ret = GST_FLOW_OK;
2245   GSList *walk;
2246   guint64 current_time = atoms_get_current_qt_time ();
2247
2248   /* update modification times */
2249   qtmux->moov->mvhd.time_info.modification_time = current_time;
2250   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2251     GstCollectData *cdata = (GstCollectData *) walk->data;
2252     GstQTPad *qtpad = (GstQTPad *) cdata;
2253
2254     qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2255     qtpad->trak->tkhd.modification_time = current_time;
2256   }
2257
2258   /* serialize moov */
2259   offset = size = 0;
2260   data = NULL;
2261   GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2262   if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2263     goto serialize_error;
2264   qtmux->last_moov_size = offset;
2265
2266   /* Check we have enough reserved space for this and a Free atom */
2267   if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2268     goto too_small_reserved;
2269   buf = _gst_buffer_new_take_data (data, offset);
2270   GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2271
2272   /* If at EOS, this is the final moov, put in the streamheader
2273    * (apparently used by a flumotion util) */
2274   if (qtmux->state == GST_QT_MUX_STATE_EOS)
2275     gst_qt_mux_set_header_on_caps (qtmux, buf);
2276
2277   if (fsync_after)
2278     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2279   ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2280
2281   /* Write out a free atom if needed */
2282   if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2283     GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2284         (guint32) (padded_moov_size - offset));
2285     ret =
2286         gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2287         fsync_after);
2288   }
2289
2290   return ret;
2291 too_small_reserved:
2292   {
2293     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2294         ("Not enough free reserved header space"),
2295         ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2296             offset, padded_moov_size));
2297     return GST_FLOW_ERROR;
2298   }
2299 serialize_error:
2300   {
2301     g_free (data);
2302     return GST_FLOW_ERROR;
2303   }
2304 }
2305
2306 /* either calculates size of extra atoms or pushes them */
2307 static GstFlowReturn
2308 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2309     gboolean mind_fast)
2310 {
2311   GSList *walk;
2312   guint64 loffset = 0, size = 0;
2313   guint8 *data;
2314   GstFlowReturn ret = GST_FLOW_OK;
2315
2316   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2317     AtomInfo *ainfo = (AtomInfo *) walk->data;
2318
2319     loffset = size = 0;
2320     data = NULL;
2321     if (!ainfo->copy_data_func (ainfo->atom,
2322             send ? &data : NULL, &size, &loffset))
2323       goto serialize_error;
2324
2325     if (send) {
2326       GstBuffer *buf;
2327
2328       GST_DEBUG_OBJECT (qtmux,
2329           "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2330           GST_FOURCC_ARGS (ainfo->atom->type));
2331       buf = _gst_buffer_new_take_data (data, loffset);
2332       ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2333       if (ret != GST_FLOW_OK)
2334         break;
2335     } else {
2336       if (offset)
2337         *offset += loffset;
2338     }
2339   }
2340
2341   return ret;
2342
2343 serialize_error:
2344   {
2345     g_free (data);
2346     return GST_FLOW_ERROR;
2347   }
2348 }
2349
2350 static gboolean
2351 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2352 {
2353   gboolean seekable = FALSE;
2354   GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2355
2356   if (gst_pad_peer_query (qtmux->srcpad, query)) {
2357     gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2358     GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2359   } else {
2360     /* have to assume seeking is not supported if query not handled downstream */
2361     GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2362     seekable = FALSE;
2363   }
2364   gst_query_unref (query);
2365
2366   return seekable;
2367 }
2368
2369 static void
2370 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2371 {
2372   GSList *walk;
2373   gboolean fail = FALSE;
2374   AtomFTYP *ftyp = NULL;
2375   GstBuffer *prefix = NULL;
2376
2377   GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2378       qtmux->moov_recov_file_path);
2379
2380   qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2381   if (qtmux->moov_recov_file == NULL) {
2382     GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2383         qtmux->moov_recov_file_path);
2384     return;
2385   }
2386
2387   gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2388
2389   if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2390           qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2391     GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2392     goto fail;
2393   }
2394
2395   atom_ftyp_free (ftyp);
2396   if (prefix)
2397     gst_buffer_unref (prefix);
2398
2399   for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2400     GstCollectData *cdata = (GstCollectData *) walk->data;
2401     GstQTPad *qpad = (GstQTPad *) cdata;
2402     /* write info for each stream */
2403     fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2404     if (fail) {
2405       GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2406           "file");
2407       break;
2408     }
2409   }
2410
2411   return;
2412
2413 fail:
2414   /* cleanup */
2415   fclose (qtmux->moov_recov_file);
2416   qtmux->moov_recov_file = NULL;
2417 }
2418
2419 static guint64
2420 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2421 {
2422   switch (qpad->fourcc) {
2423     case FOURCC_apch:
2424     case FOURCC_apcn:
2425     case FOURCC_apcs:
2426     case FOURCC_apco:
2427     case FOURCC_ap4h:
2428     case FOURCC_ap4x:
2429     case FOURCC_c608:
2430     case FOURCC_c708:
2431       return qpad->sample_offset;
2432     case FOURCC_sowt:
2433     case FOURCC_twos:
2434       return gst_util_uint64_scale_ceil (qpad->sample_offset,
2435           qpad->expected_sample_duration_n,
2436           qpad->expected_sample_duration_d *
2437           atom_trak_get_timescale (qpad->trak));
2438     default:
2439       return -1;
2440   }
2441 }
2442
2443 static guint
2444 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2445 {
2446   switch (qpad->fourcc) {
2447     case FOURCC_apch:
2448       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2449         return 300000;
2450       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2451         return 350000;
2452       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2453         return 525000;
2454       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2455         return 1050000;
2456       } else {
2457         return 4150000;
2458       }
2459       break;
2460     case FOURCC_apcn:
2461       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2462         return 200000;
2463       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2464         return 250000;
2465       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2466         return 350000;
2467       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2468         return 700000;
2469       } else {
2470         return 2800000;
2471       }
2472       break;
2473     case FOURCC_apcs:
2474       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2475         return 150000;
2476       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2477         return 200000;
2478       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2479         return 250000;
2480       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2481         return 500000;
2482       } else {
2483         return 2800000;
2484       }
2485       break;
2486     case FOURCC_apco:
2487       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2488         return 80000;
2489       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2490         return 100000;
2491       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2492         return 150000;
2493       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2494         return 250000;
2495       } else {
2496         return 900000;
2497       }
2498       break;
2499     case FOURCC_c608:
2500       /* We always write both cdat and cdt2 atom in prefill mode */
2501       return 20;
2502     case FOURCC_c708:
2503       /* We're cheating a bit by always allocating 256 bytes plus 8 bytes for the atom header
2504        * even if we use less  */
2505       return 256 + 8;
2506     case FOURCC_sowt:
2507     case FOURCC_twos:{
2508       guint64 block_idx;
2509       guint64 next_sample_offset;
2510
2511       block_idx = prefill_get_block_index (qtmux, qpad);
2512       next_sample_offset =
2513           gst_util_uint64_scale (block_idx + 1,
2514           qpad->expected_sample_duration_d *
2515           atom_trak_get_timescale (qpad->trak),
2516           qpad->expected_sample_duration_n);
2517
2518       return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2519     }
2520     case FOURCC_ap4h:
2521     case FOURCC_ap4x:
2522     default:
2523       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2524       return -1;
2525   }
2526
2527   return -1;
2528 }
2529
2530 static GstClockTime
2531 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2532 {
2533   switch (qpad->fourcc) {
2534     case FOURCC_apch:
2535     case FOURCC_apcn:
2536     case FOURCC_apcs:
2537     case FOURCC_apco:
2538     case FOURCC_ap4h:
2539     case FOURCC_ap4x:
2540     case FOURCC_c608:
2541     case FOURCC_c708:
2542       return gst_util_uint64_scale (qpad->sample_offset + 1,
2543           qpad->expected_sample_duration_d * GST_SECOND,
2544           qpad->expected_sample_duration_n);
2545     case FOURCC_sowt:
2546     case FOURCC_twos:{
2547       guint64 block_idx;
2548       guint64 next_sample_offset;
2549
2550       block_idx = prefill_get_block_index (qtmux, qpad);
2551       next_sample_offset =
2552           gst_util_uint64_scale (block_idx + 1,
2553           qpad->expected_sample_duration_d *
2554           atom_trak_get_timescale (qpad->trak),
2555           qpad->expected_sample_duration_n);
2556
2557       return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2558           atom_trak_get_timescale (qpad->trak));
2559     }
2560     default:
2561       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2562       return -1;
2563   }
2564
2565   return -1;
2566 }
2567
2568 static GstBuffer *
2569 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2570     GstQTMux * qtmux)
2571 {
2572   guint64 block_idx;
2573   guint64 nsamples;
2574   GstClockTime input_timestamp;
2575   guint64 input_timestamp_distance;
2576
2577   if (buf)
2578     gst_adapter_push (qtpad->raw_audio_adapter, buf);
2579
2580   block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2581       qtpad->expected_sample_duration_n,
2582       qtpad->expected_sample_duration_d *
2583       atom_trak_get_timescale (qtpad->trak));
2584   nsamples =
2585       gst_util_uint64_scale (block_idx + 1,
2586       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2587       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2588
2589   if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2590               GST_COLLECT_PADS_STATE_EOS)
2591           && gst_adapter_available (qtpad->raw_audio_adapter) <
2592           nsamples * qtpad->sample_size)
2593       || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2594     return NULL;
2595   }
2596
2597   input_timestamp =
2598       gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2599       &input_timestamp_distance);
2600   if (input_timestamp != GST_CLOCK_TIME_NONE)
2601     input_timestamp +=
2602         gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2603         qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2604
2605   buf =
2606       gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2607       !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2608           GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2609       qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2610   GST_BUFFER_PTS (buf) = input_timestamp;
2611   GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2612   GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2613
2614   qtpad->raw_audio_adapter_offset += nsamples;
2615
2616   /* Check if we have yet another block of raw audio in the adapter */
2617   nsamples =
2618       gst_util_uint64_scale (block_idx + 2,
2619       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2620       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2621   if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2622       nsamples * qtpad->sample_size) {
2623     input_timestamp =
2624         gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2625         &input_timestamp_distance);
2626     if (input_timestamp != GST_CLOCK_TIME_NONE)
2627       input_timestamp +=
2628           gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2629           qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2630     qtpad->raw_audio_adapter_pts = input_timestamp;
2631   } else {
2632     qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2633   }
2634
2635   return buf;
2636 }
2637
2638 static void
2639 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2640 {
2641   GSList *walk;
2642
2643   /* Find the (first) video track and assume that we have to output
2644    * in that size */
2645   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2646     GstCollectData *cdata = (GstCollectData *) walk->data;
2647     GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2648
2649     if (tmp_qpad->trak->is_video) {
2650       *dur_n = tmp_qpad->expected_sample_duration_n;
2651       *dur_d = tmp_qpad->expected_sample_duration_d;
2652       break;
2653     }
2654   }
2655
2656   if (walk == NULL) {
2657     GST_INFO_OBJECT (qtmux,
2658         "Found no video framerate, using 40ms audio buffers");
2659     *dur_n = 25;
2660     *dur_d = 1;
2661   }
2662 }
2663
2664 /* Called when all pads are prerolled to adjust and  */
2665 static gboolean
2666 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2667 {
2668   switch (qpad->fourcc) {
2669     case FOURCC_apch:
2670     case FOURCC_apcn:
2671     case FOURCC_apcs:
2672     case FOURCC_apco:
2673     case FOURCC_ap4h:
2674     case FOURCC_ap4x:
2675     {
2676       guint sample_size = prefill_get_sample_size (qtmux, qpad);
2677       atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2678       return TRUE;
2679     }
2680     case FOURCC_c608:
2681     case FOURCC_c708:
2682     {
2683       guint sample_size = prefill_get_sample_size (qtmux, qpad);
2684       /* We need a "valid" duration */
2685       find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2686           &qpad->expected_sample_duration_d);
2687       atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2688       return TRUE;
2689     }
2690     case FOURCC_sowt:
2691     case FOURCC_twos:{
2692       find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2693           &qpad->expected_sample_duration_d);
2694       /* Set a prepare_buf_func that ensures this */
2695       qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2696       qpad->raw_audio_adapter = gst_adapter_new ();
2697       qpad->raw_audio_adapter_offset = 0;
2698       qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2699
2700       return TRUE;
2701     }
2702     default:
2703       return TRUE;
2704   }
2705 }
2706
2707 /* Only called at startup when doing the "fake" iteration of all tracks in order
2708  * to prefill the sample tables in the header.  */
2709 static GstQTPad *
2710 find_best_pad_prefill_start (GstQTMux * qtmux)
2711 {
2712   GSList *walk;
2713   GstQTPad *best_pad = NULL;
2714
2715   /* If interleave limits have been specified and the current pad is within
2716    * those interleave limits, pick that one, otherwise let's try to figure out
2717    * the next best one. */
2718   if (qtmux->current_pad &&
2719       (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2720       (qtmux->interleave_bytes == 0
2721           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2722       && (qtmux->interleave_time == 0
2723           || qtmux->current_chunk_duration <= qtmux->interleave_time)
2724       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2725       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2726
2727     if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2728       best_pad = qtmux->current_pad;
2729     }
2730   } else if (qtmux->collect->data->next) {
2731     /* Attempt to try another pad if we have one. Otherwise use the only pad
2732      * present */
2733     best_pad = qtmux->current_pad = NULL;
2734   }
2735
2736   /* The next best pad is the one which has the lowest timestamp and hasn't
2737    * exceeded the reserved max duration */
2738   if (!best_pad) {
2739     GstClockTime best_time = GST_CLOCK_TIME_NONE;
2740
2741     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2742       GstCollectData *cdata = (GstCollectData *) walk->data;
2743       GstQTPad *qtpad = (GstQTPad *) cdata;
2744       GstClockTime timestamp;
2745
2746       if (qtpad->total_duration >= qtmux->reserved_max_duration)
2747         continue;
2748
2749       timestamp = qtpad->total_duration;
2750
2751       if (best_pad == NULL ||
2752           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2753         best_pad = qtpad;
2754         best_time = timestamp;
2755       }
2756     }
2757   }
2758
2759   return best_pad;
2760 }
2761
2762 /* Called when starting the file in prefill_mode to figure out all the entries
2763  * of the header based on the input stream and reserved maximum duration.
2764  *
2765  * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2766  * will be updated and written on EOS. */
2767 static gboolean
2768 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2769 {
2770   GstQTPad *qpad;
2771   GSList *walk;
2772   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2773
2774   /* Update expected sample sizes/durations as needed, this is for raw
2775    * audio where samples are actual audio samples. */
2776   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2777     GstCollectData *cdata = (GstCollectData *) walk->data;
2778     GstQTPad *qpad = (GstQTPad *) cdata;
2779
2780     if (!prefill_update_sample_size (qtmux, qpad))
2781       return FALSE;
2782   }
2783
2784   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2785     /* For the first sample check/update timecode as needed. We do that before
2786      * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2787      * initial buffer directly, not with last_buf */
2788     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2789       GstCollectData *cdata = (GstCollectData *) walk->data;
2790       GstQTPad *qpad = (GstQTPad *) cdata;
2791       GstBuffer *buffer =
2792           gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2793       GstVideoTimeCodeMeta *tc_meta;
2794
2795       if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2796         GstVideoTimeCode *tc = &tc_meta->tc;
2797
2798         qpad->tc_trak = atom_trak_new (qtmux->context);
2799         atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2800
2801         qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2802         atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2803
2804         atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2805             qpad->trak->mdia.mdhd.time_info.timescale, tc);
2806
2807         atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2808             qtmux->mdat_size, FALSE, 0);
2809
2810         qpad->tc_pos = qtmux->mdat_size;
2811         qpad->first_tc = gst_video_time_code_copy (tc);
2812         qpad->first_pts = GST_BUFFER_PTS (buffer);
2813
2814         qtmux->current_chunk_offset = -1;
2815         qtmux->current_chunk_size = 0;
2816         qtmux->current_chunk_duration = 0;
2817         qtmux->mdat_size += 4;
2818       }
2819       if (buffer)
2820         gst_buffer_unref (buffer);
2821     }
2822   }
2823
2824   while ((qpad = find_best_pad_prefill_start (qtmux))) {
2825     GstClockTime timestamp, next_timestamp, duration;
2826     guint nsamples, sample_size;
2827     guint64 chunk_offset;
2828     gint64 scaled_duration;
2829     gint64 pts_offset = 0;
2830     gboolean sync = FALSE;
2831     TrakBufferEntryInfo sample_entry;
2832
2833     sample_size = prefill_get_sample_size (qtmux, qpad);
2834
2835     if (sample_size == -1) {
2836       return FALSE;
2837     }
2838
2839     if (!qpad->samples)
2840       qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2841
2842     timestamp = qpad->total_duration;
2843     next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2844     duration = next_timestamp - timestamp;
2845
2846     if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2847       qpad->first_ts = timestamp;
2848     if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2849       qpad->first_dts = timestamp;
2850
2851     if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2852       qtmux->current_pad = qpad;
2853       if (qtmux->current_chunk_offset == -1)
2854         qtmux->current_chunk_offset = qtmux->mdat_size;
2855       else
2856         qtmux->current_chunk_offset += qtmux->current_chunk_size;
2857       qtmux->current_chunk_size = 0;
2858       qtmux->current_chunk_duration = 0;
2859     }
2860     if (qpad->sample_size)
2861       nsamples = sample_size / qpad->sample_size;
2862     else
2863       nsamples = 1;
2864     qpad->last_dts = timestamp;
2865     scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2866         atom_trak_get_timescale (qpad->trak),
2867         GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2868         atom_trak_get_timescale (qpad->trak), GST_SECOND);
2869
2870     qtmux->current_chunk_size += sample_size;
2871     qtmux->current_chunk_duration += duration;
2872     qpad->total_bytes += sample_size;
2873
2874     chunk_offset = qtmux->current_chunk_offset;
2875
2876     /* I-frame only, no frame reordering */
2877     sync = FALSE;
2878     pts_offset = 0;
2879
2880     if (qtmux->current_chunk_duration > qtmux->longest_chunk
2881         || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2882       qtmux->longest_chunk = qtmux->current_chunk_duration;
2883     }
2884
2885     sample_entry.track_id = qpad->trak->tkhd.track_ID;
2886     sample_entry.nsamples = nsamples;
2887     sample_entry.delta = scaled_duration / nsamples;
2888     sample_entry.size = sample_size / nsamples;
2889     sample_entry.chunk_offset = chunk_offset;
2890     sample_entry.pts_offset = pts_offset;
2891     sample_entry.sync = sync;
2892     sample_entry.do_pts = TRUE;
2893     g_array_append_val (qpad->samples, sample_entry);
2894     atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2895         sample_size / nsamples, chunk_offset, sync, pts_offset);
2896
2897     qpad->total_duration = next_timestamp;
2898     qtmux->mdat_size += sample_size;
2899     qpad->sample_offset += nsamples;
2900   }
2901
2902   return TRUE;
2903 }
2904
2905 static GstFlowReturn
2906 gst_qt_mux_start_file (GstQTMux * qtmux)
2907 {
2908   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2909   GstFlowReturn ret = GST_FLOW_OK;
2910   GstCaps *caps;
2911   GstSegment segment;
2912   gchar s_id[32];
2913   GstClockTime reserved_max_duration;
2914   guint reserved_bytes_per_sec_per_trak;
2915   GSList *walk;
2916
2917   GST_DEBUG_OBJECT (qtmux, "starting file");
2918
2919   GST_OBJECT_LOCK (qtmux);
2920   reserved_max_duration = qtmux->reserved_max_duration;
2921   reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2922   GST_OBJECT_UNLOCK (qtmux);
2923
2924   /* stream-start (FIXME: create id based on input ids) */
2925   g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2926   gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2927
2928   caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2929   /* qtmux has structure with and without variant, remove all but the first */
2930   while (gst_caps_get_size (caps) > 1)
2931     gst_caps_remove_structure (caps, 1);
2932   gst_pad_set_caps (qtmux->srcpad, caps);
2933   gst_caps_unref (caps);
2934
2935   /* Default is 'normal' mode */
2936   qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2937
2938   /* Require a sensible fragment duration when muxing
2939    * using the ISML muxer */
2940   if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2941       qtmux->fragment_duration == 0)
2942     goto invalid_isml;
2943
2944   if (qtmux->fragment_duration > 0) {
2945     if (qtmux->streamable)
2946       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2947     else
2948       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2949   } else if (qtmux->fast_start) {
2950     qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2951   } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2952     if (qtmux->reserved_prefill)
2953       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2954     else
2955       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2956   }
2957
2958   switch (qtmux->mux_mode) {
2959     case GST_QT_MUX_MODE_MOOV_AT_END:
2960     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2961       /* We have to be able to seek to rewrite the mdat header, or any
2962        * moov atom we write will not be visible in the file, because an
2963        * MDAT with 0 as the size covers the rest of the file. A file
2964        * with no moov is not playable, so error out now. */
2965       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2966         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2967             ("Downstream is not seekable - will not be able to create a playable file"),
2968             (NULL));
2969         return GST_FLOW_ERROR;
2970       }
2971       if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
2972         GST_WARNING_OBJECT (qtmux,
2973             "Robust muxing requires reserved-moov-update-period to be set");
2974       }
2975       break;
2976     case GST_QT_MUX_MODE_FAST_START:
2977     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2978       break;                    /* Don't need seekability, ignore */
2979     case GST_QT_MUX_MODE_FRAGMENTED:
2980       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2981         GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2982             "streamable=false. Will ignore that and create streamable output "
2983             "instead");
2984         qtmux->streamable = TRUE;
2985         g_object_notify (G_OBJECT (qtmux), "streamable");
2986       }
2987       break;
2988     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2989       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2990         GST_WARNING_OBJECT (qtmux,
2991             "downstream is not seekable, will not be able "
2992             "to trim samples table at the end if less than reserved-duration is "
2993             "recorded");
2994       }
2995       break;
2996   }
2997
2998   /* let downstream know we think in BYTES and expect to do seeking later on */
2999   gst_segment_init (&segment, GST_FORMAT_BYTES);
3000   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3001
3002   GST_OBJECT_LOCK (qtmux);
3003
3004   if (qtmux->timescale == 0) {
3005     guint32 suggested_timescale = 0;
3006     GSList *walk;
3007
3008     /* Calculate a reasonable timescale for the moov:
3009      * If there is video, it is the biggest video track timescale or an even
3010      * multiple of it if it's smaller than 1800.
3011      * Otherwise it is 1800 */
3012     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3013       GstCollectData *cdata = (GstCollectData *) walk->data;
3014       GstQTPad *qpad = (GstQTPad *) cdata;
3015
3016       if (!qpad->trak)
3017         continue;
3018
3019       /* not video */
3020       if (!qpad->trak->mdia.minf.vmhd)
3021         continue;
3022
3023       suggested_timescale =
3024           MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3025     }
3026
3027     if (suggested_timescale == 0)
3028       suggested_timescale = 1800;
3029
3030     while (suggested_timescale < 1800)
3031       suggested_timescale *= 2;
3032
3033     qtmux->timescale = suggested_timescale;
3034   }
3035
3036   /* initialize our moov recovery file */
3037   if (qtmux->moov_recov_file_path) {
3038     gst_qt_mux_prepare_moov_recovery (qtmux);
3039   }
3040
3041   /* Make sure the first time we update the moov, we'll
3042    * include any tagsetter tags */
3043   qtmux->tags_changed = TRUE;
3044
3045   GST_OBJECT_UNLOCK (qtmux);
3046
3047   /*
3048    * send mdat header if already needed, and mark position for later update.
3049    * We don't send ftyp now if we are on fast start mode, because we can
3050    * better fine tune using the information we gather to create the whole moov
3051    * atom.
3052    */
3053   switch (qtmux->mux_mode) {
3054     case GST_QT_MUX_MODE_MOOV_AT_END:
3055       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3056       if (ret != GST_FLOW_OK)
3057         break;
3058
3059       /* Store this as the mdat offset for later updating
3060        * when we write the moov */
3061       qtmux->mdat_pos = qtmux->header_size;
3062       /* extended atom in case we go over 4GB while writing and need
3063        * the full 64-bit atom */
3064       ret =
3065           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3066           FALSE);
3067       break;
3068     case GST_QT_MUX_MODE_ROBUST_RECORDING:
3069       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3070       if (ret != GST_FLOW_OK)
3071         break;
3072
3073       /* Pad ftyp out to an 8-byte boundary before starting the moov
3074        * ping pong region. It should be well less than 1 disk sector,
3075        * unless there's a bajillion compatible types listed,
3076        * but let's be sure the free atom doesn't cross a sector
3077        * boundary anyway */
3078       if (qtmux->header_size % 8) {
3079         /* Extra 8 bytes for the padding free atom header */
3080         guint padding = (guint) (16 - (qtmux->header_size % 8));
3081         GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3082         ret =
3083             gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3084             FALSE);
3085         if (ret != GST_FLOW_OK)
3086           return ret;
3087       }
3088
3089       /* Store this as the moov offset for later updating.
3090        * We record mdat position below */
3091       qtmux->moov_pos = qtmux->header_size;
3092
3093       /* Set up the initial 'ping' state of the ping-pong buffers */
3094       qtmux->reserved_moov_first_active = TRUE;
3095
3096       gst_qt_mux_configure_moov (qtmux);
3097       gst_qt_mux_setup_metadata (qtmux);
3098       /* Empty free atom to begin, starting on an 8-byte boundary */
3099       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3100       if (ret != GST_FLOW_OK)
3101         return ret;
3102       /* Moov header, not padded yet */
3103       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3104       if (ret != GST_FLOW_OK)
3105         return ret;
3106       /* The moov we just sent contains the 'base' size of the moov, before
3107        * we put in any time-dependent per-trak data. Use that to make
3108        * a good estimate of how much extra to reserve */
3109       /* Calculate how much space to reserve for our MOOV atom.
3110        * We actually reserve twice that, for ping-pong buffers */
3111       qtmux->base_moov_size = qtmux->last_moov_size;
3112       GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3113           qtmux->base_moov_size);
3114       qtmux->reserved_moov_size = qtmux->base_moov_size +
3115           gst_util_uint64_scale (reserved_max_duration,
3116           reserved_bytes_per_sec_per_trak *
3117           atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3118
3119       /* Need space for at least 4 atom headers. More really, but
3120        * this as an absolute minimum */
3121       if (qtmux->reserved_moov_size < 4 * 8)
3122         goto reserved_moov_too_small;
3123
3124       GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3125           2 * qtmux->reserved_moov_size + 16);
3126
3127       GST_OBJECT_LOCK (qtmux);
3128       qtmux->reserved_duration_remaining =
3129           gst_util_uint64_scale (qtmux->reserved_moov_size -
3130           qtmux->base_moov_size, GST_SECOND,
3131           reserved_bytes_per_sec_per_trak *
3132           atom_moov_get_trak_count (qtmux->moov));
3133       GST_OBJECT_UNLOCK (qtmux);
3134
3135       /* Now that we know how much reserved space is targetted,
3136        * output a free atom to fill the extra reserved */
3137       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3138           qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3139       if (ret != GST_FLOW_OK)
3140         return ret;
3141
3142       /* Then a free atom containing 'pong' buffer, with an
3143        * extra 8 bytes to account for the free atom header itself */
3144       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3145           qtmux->reserved_moov_size + 8, FALSE);
3146       if (ret != GST_FLOW_OK)
3147         return ret;
3148
3149       /* extra atoms go after the free/moov(s), before the mdat */
3150       ret =
3151           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3152       if (ret != GST_FLOW_OK)
3153         return ret;
3154
3155       qtmux->mdat_pos = qtmux->header_size;
3156       /* extended atom in case we go over 4GB while writing and need
3157        * the full 64-bit atom */
3158       ret =
3159           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3160           FALSE);
3161       break;
3162     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3163       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3164       if (ret != GST_FLOW_OK)
3165         break;
3166
3167       /* Store this as the moov offset for later updating.
3168        * We record mdat position below */
3169       qtmux->moov_pos = qtmux->header_size;
3170
3171       if (!gst_qt_mux_prefill_samples (qtmux)) {
3172         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3173             ("Unsupported codecs or configuration for prefill mode"), (NULL));
3174
3175         return GST_FLOW_ERROR;
3176       }
3177
3178       gst_qt_mux_update_global_statistics (qtmux);
3179       gst_qt_mux_configure_moov (qtmux);
3180       gst_qt_mux_update_edit_lists (qtmux);
3181       gst_qt_mux_setup_metadata (qtmux);
3182
3183       /* Moov header with pre-filled samples */
3184       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3185       if (ret != GST_FLOW_OK)
3186         return ret;
3187
3188       /* last_moov_size now contains the full size of the moov, moov_pos the
3189        * position. This allows us to rewrite it in the very end as needed */
3190       qtmux->reserved_moov_size =
3191           qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3192
3193       /* Send an additional free atom at the end so we definitely have space
3194        * to rewrite the moov header at the end and remove the samples that
3195        * were not actually written */
3196       ret =
3197           gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3198           12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3199       if (ret != GST_FLOW_OK)
3200         return ret;
3201
3202       /* extra atoms go after the free/moov(s), before the mdat */
3203       ret =
3204           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3205       if (ret != GST_FLOW_OK)
3206         return ret;
3207
3208       qtmux->mdat_pos = qtmux->header_size;
3209
3210       /* And now send the mdat header */
3211       ret =
3212           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3213           qtmux->mdat_size, TRUE, FALSE);
3214
3215       /* chunks position is set relative to the first byte of the
3216        * MDAT atom payload. Set the overall offset into the file */
3217       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3218
3219       {
3220         GstSegment segment;
3221
3222         gst_segment_init (&segment, GST_FORMAT_BYTES);
3223         segment.start = qtmux->moov_pos;
3224         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3225
3226         ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3227         if (ret != GST_FLOW_OK)
3228           return ret;
3229
3230         segment.start = qtmux->header_size;
3231         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3232       }
3233
3234       qtmux->current_chunk_size = 0;
3235       qtmux->current_chunk_duration = 0;
3236       qtmux->current_chunk_offset = -1;
3237       qtmux->mdat_size = 0;
3238       qtmux->current_pad = NULL;
3239       qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3240
3241       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3242         GstCollectData *cdata = (GstCollectData *) walk->data;
3243         GstQTPad *qtpad = (GstQTPad *) cdata;
3244
3245         qtpad->total_bytes = 0;
3246         qtpad->total_duration = 0;
3247         qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3248         qtpad->last_dts = GST_CLOCK_TIME_NONE;
3249         qtpad->sample_offset = 0;
3250       }
3251
3252       break;
3253     case GST_QT_MUX_MODE_FAST_START:
3254       GST_OBJECT_LOCK (qtmux);
3255       qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3256       if (!qtmux->fast_start_file)
3257         goto open_failed;
3258       GST_OBJECT_UNLOCK (qtmux);
3259       /* send a dummy buffer for preroll */
3260       ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3261       break;
3262     case GST_QT_MUX_MODE_FRAGMENTED:
3263     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3264       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3265       if (ret != GST_FLOW_OK)
3266         break;
3267       /* store the moov pos so we can update the duration later
3268        * in non-streamable mode */
3269       qtmux->moov_pos = qtmux->header_size;
3270
3271       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3272           qtmux->fragment_duration);
3273       /* also used as snapshot marker to indicate fragmented file */
3274       qtmux->fragment_sequence = 1;
3275       /* prepare moov and/or tags */
3276       gst_qt_mux_configure_moov (qtmux);
3277       gst_qt_mux_setup_metadata (qtmux);
3278       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3279       if (ret != GST_FLOW_OK)
3280         return ret;
3281       /* extra atoms */
3282       ret =
3283           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3284       if (ret != GST_FLOW_OK)
3285         break;
3286       /* prepare index if not streamable */
3287       if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3288         qtmux->mfra = atom_mfra_new (qtmux->context);
3289       break;
3290   }
3291
3292   return ret;
3293   /* ERRORS */
3294 invalid_isml:
3295   {
3296     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3297         ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3298     return GST_FLOW_ERROR;
3299   }
3300 reserved_moov_too_small:
3301   {
3302     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3303         ("Not enough reserved space for creating headers"), (NULL));
3304     return GST_FLOW_ERROR;
3305   }
3306 open_failed:
3307   {
3308     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3309         (("Could not open temporary file \"%s\""),
3310             qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3311     GST_OBJECT_UNLOCK (qtmux);
3312     return GST_FLOW_ERROR;
3313   }
3314 }
3315
3316 static GstFlowReturn
3317 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3318 {
3319   GstFlowReturn ret = GST_FLOW_OK;
3320   GSList *walk;
3321
3322   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3323     GstCollectData *cdata = (GstCollectData *) walk->data;
3324     GstQTPad *qtpad = (GstQTPad *) cdata;
3325
3326     /* avoid add_buffer complaining if not negotiated
3327      * in which case no buffers either, so skipping */
3328     if (!qtpad->fourcc) {
3329       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3330           GST_PAD_NAME (qtpad->collect.pad));
3331       continue;
3332     }
3333
3334     /* send last buffer; also flushes possibly queued buffers/ts */
3335     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3336         GST_PAD_NAME (qtpad->collect.pad));
3337     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3338     if (ret != GST_FLOW_OK) {
3339       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3340           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3341           gst_flow_get_name (ret));
3342     }
3343   }
3344
3345   return ret;
3346 }
3347
3348 static void
3349 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3350 {
3351   GSList *walk;
3352
3353   /* for setting some subtitles fields */
3354   guint max_width = 0;
3355   guint max_height = 0;
3356
3357   qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3358
3359   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3360     GstCollectData *cdata = (GstCollectData *) walk->data;
3361     GstQTPad *qtpad = (GstQTPad *) cdata;
3362
3363     if (!qtpad->fourcc) {
3364       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3365           GST_PAD_NAME (qtpad->collect.pad));
3366       continue;
3367     }
3368
3369     /* having flushed above, can check for buffers now */
3370     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3371       GstClockTime first_pts_in = qtpad->first_ts;
3372       /* it should be, since we got first_ts by adding adjustment
3373        * to a positive incoming PTS */
3374       if (qtpad->dts_adjustment <= first_pts_in)
3375         first_pts_in -= qtpad->dts_adjustment;
3376       /* determine max stream duration */
3377       if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3378           || qtpad->last_dts > qtmux->last_dts) {
3379         qtmux->last_dts = qtpad->last_dts;
3380       }
3381       if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3382           || first_pts_in < qtmux->first_ts) {
3383         /* we need the original incoming PTS here, as this first_ts
3384          * is used in update_edit_lists to construct the edit list that arrange
3385          * for sync'ed streams.  The first_ts is most likely obtained from
3386          * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3387          * so it makes no difference, though it matters in other cases */
3388         qtmux->first_ts = first_pts_in;
3389       }
3390     }
3391
3392     /* subtitles need to know the video width/height,
3393      * it is stored shifted 16 bits to the left according to the
3394      * spec */
3395     max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3396     max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3397
3398     /* update average bitrate of streams if needed */
3399     {
3400       guint32 avgbitrate = 0;
3401       guint32 maxbitrate = qtpad->max_bitrate;
3402
3403       if (qtpad->avg_bitrate)
3404         avgbitrate = qtpad->avg_bitrate;
3405       else if (qtpad->total_duration > 0)
3406         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3407             8 * GST_SECOND, qtpad->total_duration);
3408
3409       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3410     }
3411   }
3412
3413   /* need to update values on subtitle traks now that we know the
3414    * max width and height */
3415   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3416     GstCollectData *cdata = (GstCollectData *) walk->data;
3417     GstQTPad *qtpad = (GstQTPad *) cdata;
3418
3419     if (!qtpad->fourcc) {
3420       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3421           GST_PAD_NAME (qtpad->collect.pad));
3422       continue;
3423     }
3424
3425     if (qtpad->fourcc == FOURCC_tx3g) {
3426       atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3427     }
3428   }
3429 }
3430
3431 /* Called after gst_qt_mux_update_global_statistics() updates the
3432  * first_ts tracking, to create/set edit lists for delayed streams */
3433 static void
3434 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3435 {
3436   GSList *walk;
3437
3438   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3439       GST_TIME_ARGS (qtmux->first_ts));
3440   /* add/update EDTSs for late streams. configure_moov will have
3441    * set the trak durations above by summing the sample tables,
3442    * here we extend that if needing to insert an empty segment */
3443   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3444     GstCollectData *cdata = (GstCollectData *) walk->data;
3445     GstQTPad *qtpad = (GstQTPad *) cdata;
3446
3447     atom_trak_edts_clear (qtpad->trak);
3448
3449     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3450       guint32 lateness = 0;
3451       guint32 duration = qtpad->trak->tkhd.duration;
3452       gboolean has_gap;
3453
3454       has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3455
3456       if (has_gap) {
3457         GstClockTime diff;
3458
3459         diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3460         lateness = gst_util_uint64_scale_round (diff,
3461             qtmux->timescale, GST_SECOND);
3462
3463         if (lateness > 0) {
3464           GST_DEBUG_OBJECT (qtmux,
3465               "Pad %s is a late stream by %" GST_TIME_FORMAT,
3466               GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3467
3468           atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3469               (guint32) (1 * 65536.0));
3470         }
3471       }
3472
3473       /* Always write an edit list for the whole track. In general this is not
3474        * necessary except for the case of having a gap or DTS adjustment but
3475        * it allows to give the whole track's duration in the usually more
3476        * accurate media timescale
3477        */
3478       {
3479         GstClockTime ctts = 0;
3480         guint32 media_start;
3481
3482         if (qtpad->first_ts > qtpad->first_dts)
3483           ctts = qtpad->first_ts - qtpad->first_dts;
3484
3485         media_start = gst_util_uint64_scale_round (ctts,
3486             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3487
3488         /* atom_trak_set_elst_entry() has a quirk - if the edit list
3489          * is empty because there's no gap added above, this call
3490          * will not replace index 1, it will create the entry at index 0.
3491          * Luckily, that's exactly what we want here */
3492         atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3493             (guint32) (1 * 65536.0));
3494       }
3495
3496       /* need to add the empty time to the trak duration */
3497       duration += lateness;
3498       qtpad->trak->tkhd.duration = duration;
3499       if (qtpad->tc_trak) {
3500         qtpad->tc_trak->tkhd.duration = duration;
3501         qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3502       }
3503
3504       /* And possibly grow the moov duration */
3505       if (duration > qtmux->moov->mvhd.time_info.duration) {
3506         qtmux->moov->mvhd.time_info.duration = duration;
3507         qtmux->moov->mvex.mehd.fragment_duration = duration;
3508       }
3509     }
3510   }
3511 }
3512
3513 static GstFlowReturn
3514 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3515 {
3516   GstSegment segment;
3517   GstBuffer *buf;
3518   GstMapInfo map;
3519   guint64 offset = qtpad->tc_pos;
3520   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3521
3522   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3523     return GST_FLOW_OK;
3524
3525   g_assert (qtpad->tc_pos != -1);
3526
3527   gst_segment_init (&segment, GST_FORMAT_BYTES);
3528   segment.start = offset;
3529   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3530
3531   buf = gst_buffer_new_and_alloc (4);
3532   gst_buffer_map (buf, &map, GST_MAP_WRITE);
3533
3534   GST_WRITE_UINT32_BE (map.data,
3535       gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3536   gst_buffer_unmap (buf, &map);
3537
3538   /* Reset this value, so the timecode won't be re-rewritten */
3539   qtpad->tc_pos = -1;
3540
3541   return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3542 }
3543
3544 static GstFlowReturn
3545 gst_qt_mux_stop_file (GstQTMux * qtmux)
3546 {
3547   gboolean ret = GST_FLOW_OK;
3548   guint64 offset = 0, size = 0;
3549   gboolean large_file;
3550   GSList *walk;
3551
3552   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3553
3554   /* pushing last buffers for each pad */
3555   if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3556     return ret;
3557
3558   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3559     /* Streamable mode; no need to write duration or MFRA */
3560     GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3561     return GST_FLOW_OK;
3562   }
3563
3564   gst_qt_mux_update_global_statistics (qtmux);
3565   for (walk = qtmux->collect->data; walk; walk = walk->next) {
3566     GstQTPad *qtpad = (GstQTPad *) walk->data;
3567
3568     if (qtpad->tc_pos != -1) {
3569       /* File is being stopped and timecode hasn't been updated. Update it now
3570        * with whatever we have */
3571       ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3572       if (ret != GST_FLOW_OK)
3573         return ret;
3574     }
3575   }
3576
3577   switch (qtmux->mux_mode) {
3578     case GST_QT_MUX_MODE_FRAGMENTED:{
3579       GstSegment segment;
3580       guint8 *data = NULL;
3581       GstBuffer *buf;
3582
3583       size = offset = 0;
3584       GST_DEBUG_OBJECT (qtmux, "adding mfra");
3585       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3586         goto serialize_error;
3587       buf = _gst_buffer_new_take_data (data, offset);
3588       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3589       if (ret != GST_FLOW_OK)
3590         return ret;
3591
3592       /* only mvex duration is updated,
3593        * mvhd should be consistent with empty moov
3594        * (but TODO maybe some clients do not handle that well ?) */
3595       qtmux->moov->mvex.mehd.fragment_duration =
3596           gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3597       GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3598           GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3599       /* seek and rewrite the header */
3600       gst_segment_init (&segment, GST_FORMAT_BYTES);
3601       segment.start = qtmux->moov_pos;
3602       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3603       /* no need to seek back */
3604       return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3605     }
3606     case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3607       ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3608       if (G_UNLIKELY (ret != GST_FLOW_OK))
3609         return ret;
3610       /* Finalise by writing the final size into the mdat. Up until now
3611        * it's been 0, which means 'rest of the file'
3612        * No need to seek back after this, we won't write any more */
3613       return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3614           qtmux->mdat_size, NULL, TRUE);
3615     }
3616     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3617       GSList *walk;
3618       guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3619
3620       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3621         GstCollectData *cdata = (GstCollectData *) walk->data;
3622         GstQTPad *qpad = (GstQTPad *) cdata;
3623         guint64 block_idx;
3624         AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3625
3626         /* Get the block index of the last sample we wrote, not of the next
3627          * sample we would write */
3628         block_idx = prefill_get_block_index (qtmux, qpad);
3629
3630         /* stts */
3631         if (block_idx > 0) {
3632           STTSEntry *entry;
3633           guint64 nsamples = 0;
3634           gint i, n;
3635
3636           n = atom_array_get_len (&stbl->stts.entries);
3637           for (i = 0; i < n; i++) {
3638             entry = &atom_array_index (&stbl->stts.entries, i);
3639             if (nsamples + entry->sample_count >= qpad->sample_offset) {
3640               entry->sample_count = qpad->sample_offset - nsamples;
3641               stbl->stts.entries.len = i + 1;
3642               break;
3643             }
3644             nsamples += entry->sample_count;
3645           }
3646           g_assert (i < n);
3647         } else {
3648           stbl->stts.entries.len = 0;
3649         }
3650
3651         /* stsz */
3652         {
3653           g_assert (stbl->stsz.entries.len == 0);
3654           stbl->stsz.table_size = qpad->sample_offset;
3655         }
3656
3657         /* stco/stsc */
3658         {
3659           gint i, n;
3660           guint64 nsamples = 0;
3661           gint chunk_index = 0;
3662           const TrakBufferEntryInfo *sample_entry;
3663
3664           if (block_idx > 0) {
3665             sample_entry =
3666                 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3667                 block_idx - 1);
3668
3669             n = stbl->stco64.entries.len;
3670             for (i = 0; i < n; i++) {
3671               guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3672
3673               if (*entry == sample_entry->chunk_offset) {
3674                 stbl->stco64.entries.len = i + 1;
3675                 chunk_index = i + 1;
3676                 break;
3677               }
3678             }
3679             g_assert (i < n);
3680             g_assert (chunk_index > 0);
3681
3682             n = stbl->stsc.entries.len;
3683             for (i = 0; i < n; i++) {
3684               STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3685
3686               if (entry->first_chunk >= chunk_index)
3687                 break;
3688
3689               if (i > 0) {
3690                 nsamples +=
3691                     (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3692                         i -
3693                         1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3694                     i - 1).samples_per_chunk;
3695               }
3696             }
3697             g_assert (i <= n);
3698
3699             if (i > 0) {
3700               STSCEntry *prev_entry =
3701                   &atom_array_index (&stbl->stsc.entries, i - 1);
3702               nsamples +=
3703                   (chunk_index -
3704                   prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3705               if (qpad->sample_offset - nsamples > 0) {
3706                 stbl->stsc.entries.len = i;
3707                 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3708                     qpad->sample_offset - nsamples);
3709               } else {
3710                 stbl->stsc.entries.len = i;
3711                 stbl->stco64.entries.len--;
3712               }
3713             } else {
3714               /* Everything in a single chunk */
3715               stbl->stsc.entries.len = 0;
3716               atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3717                   qpad->sample_offset);
3718             }
3719           } else {
3720             stbl->stco64.entries.len = 0;
3721             stbl->stsc.entries.len = 0;
3722           }
3723         }
3724
3725         {
3726           GList *walk2;
3727
3728           for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3729             AtomTREX *trex = walk2->data;
3730
3731             if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3732               trex->track_ID = next_track_id;
3733               break;
3734             }
3735           }
3736
3737           qpad->trak->tkhd.track_ID = next_track_id++;
3738         }
3739       }
3740       qtmux->moov->mvhd.next_track_id = next_track_id;
3741
3742       gst_qt_mux_update_global_statistics (qtmux);
3743       gst_qt_mux_configure_moov (qtmux);
3744
3745       gst_qt_mux_update_edit_lists (qtmux);
3746
3747       /* Check if any gap edit lists were added. We don't have any space
3748        * reserved for this in the moov and the pre-finalized moov would have
3749        * broken A/V synchronization. Error out here now
3750        */
3751       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3752         GstCollectData *cdata = (GstCollectData *) walk->data;
3753         GstQTPad *qpad = (GstQTPad *) cdata;
3754
3755         if (qpad->trak->edts
3756             && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3757           GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3758               ("Can't support gaps in prefill mode"));
3759
3760           return GST_FLOW_ERROR;
3761         }
3762       }
3763
3764       gst_qt_mux_setup_metadata (qtmux);
3765       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3766
3767       {
3768         GstSegment segment;
3769
3770         gst_segment_init (&segment, GST_FORMAT_BYTES);
3771         segment.start = qtmux->moov_pos;
3772         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3773
3774         ret =
3775             gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3776             FALSE);
3777         if (ret != GST_FLOW_OK)
3778           return ret;
3779
3780         if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3781           ret =
3782               gst_qt_mux_send_free_atom (qtmux, NULL,
3783               qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3784         }
3785
3786         if (ret != GST_FLOW_OK)
3787           return ret;
3788       }
3789
3790       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3791           qtmux->mdat_size, NULL, FALSE);
3792       return ret;
3793     }
3794     default:
3795       break;
3796   }
3797
3798   /* Moov-at-end or fast-start mode from here down */
3799   gst_qt_mux_configure_moov (qtmux);
3800
3801   gst_qt_mux_update_edit_lists (qtmux);
3802
3803   /* tags into file metadata */
3804   gst_qt_mux_setup_metadata (qtmux);
3805
3806   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3807
3808   switch (qtmux->mux_mode) {
3809     case GST_QT_MUX_MODE_FAST_START:{
3810       /* if faststart, update the offset of the atoms in the movie with the offset
3811        * that the movie headers before mdat will cause.
3812        * Also, send the ftyp */
3813       offset = size = 0;
3814
3815       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3816       if (ret != GST_FLOW_OK) {
3817         goto ftyp_error;
3818       }
3819       /* copy into NULL to obtain size */
3820       if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3821         goto serialize_error;
3822       GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3823           offset);
3824       offset += qtmux->header_size + (large_file ? 16 : 8);
3825
3826       /* sum up with the extra atoms size */
3827       ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3828       if (ret != GST_FLOW_OK)
3829         return ret;
3830       break;
3831     }
3832     default:
3833       offset = qtmux->header_size;
3834       break;
3835   }
3836
3837   /* Now that we know the size of moov + extra atoms, we can adjust
3838    * the chunk offsets stored into the moov */
3839   atom_moov_chunks_set_offset (qtmux->moov, offset);
3840
3841   /* write out moov and extra atoms */
3842   /* note: as of this point, we no longer care about tracking written data size,
3843    * since there is no more use for it anyway */
3844   ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3845   if (ret != GST_FLOW_OK)
3846     return ret;
3847
3848   /* extra atoms */
3849   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3850   if (ret != GST_FLOW_OK)
3851     return ret;
3852
3853   switch (qtmux->mux_mode) {
3854     case GST_QT_MUX_MODE_MOOV_AT_END:
3855     {
3856       /* mdat needs update iff not using faststart */
3857       GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3858       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3859           qtmux->mdat_size, NULL, FALSE);
3860       /* note; no seeking back to the end of file is done,
3861        * since we no longer write anything anyway */
3862       break;
3863     }
3864     case GST_QT_MUX_MODE_FAST_START:
3865     {
3866       /* send mdat atom and move buffered data into it */
3867       /* mdat_size = accumulated (buffered data) */
3868       ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3869           large_file, FALSE);
3870       if (ret != GST_FLOW_OK)
3871         return ret;
3872       ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3873       if (ret != GST_FLOW_OK)
3874         return ret;
3875       break;
3876     }
3877     default:
3878       g_assert_not_reached ();
3879   }
3880
3881   return ret;
3882
3883   /* ERRORS */
3884 serialize_error:
3885   {
3886     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3887         ("Failed to serialize moov"));
3888     return GST_FLOW_ERROR;
3889   }
3890 ftyp_error:
3891   {
3892     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3893     return GST_FLOW_ERROR;
3894   }
3895 }
3896
3897 static GstFlowReturn
3898 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3899     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3900     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3901 {
3902   GstFlowReturn ret = GST_FLOW_OK;
3903
3904   /* setup if needed */
3905   if (G_UNLIKELY (!pad->traf || force))
3906     goto init;
3907
3908 flush:
3909   /* flush pad fragment if threshold reached,
3910    * or at new keyframe if we should be minding those in the first place */
3911   if (G_UNLIKELY (force || (sync && pad->sync) ||
3912           pad->fragment_duration < (gint64) delta)) {
3913     AtomMOOF *moof;
3914     guint64 size = 0, offset = 0;
3915     guint8 *data = NULL;
3916     GstBuffer *buffer;
3917     guint i, total_size;
3918
3919     /* now we know where moof ends up, update offset in tfra */
3920     if (pad->tfra)
3921       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3922
3923     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3924     /* takes ownership */
3925     atom_moof_add_traf (moof, pad->traf);
3926     pad->traf = NULL;
3927     atom_moof_copy_data (moof, &data, &size, &offset);
3928     buffer = _gst_buffer_new_take_data (data, offset);
3929     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3930         gst_buffer_get_size (buffer));
3931     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3932
3933     /* and actual data */
3934     total_size = 0;
3935     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3936       total_size +=
3937           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3938     }
3939
3940     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3941         atom_array_get_len (&pad->fragment_buffers), total_size);
3942     if (ret == GST_FLOW_OK)
3943       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3944           FALSE, FALSE);
3945     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3946       if (G_LIKELY (ret == GST_FLOW_OK))
3947         ret = gst_qt_mux_send_buffer (qtmux,
3948             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3949             FALSE);
3950       else
3951         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3952     }
3953
3954     atom_array_clear (&pad->fragment_buffers);
3955     atom_moof_free (moof);
3956     qtmux->fragment_sequence++;
3957     force = FALSE;
3958   }
3959
3960 init:
3961   if (G_UNLIKELY (!pad->traf)) {
3962     GST_LOG_OBJECT (qtmux, "setting up new fragment");
3963     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3964     atom_array_init (&pad->fragment_buffers, 512);
3965     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3966         atom_trak_get_timescale (pad->trak), 1000);
3967
3968     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3969       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3970       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3971     }
3972     atom_traf_set_base_decode_time (pad->traf, dts);
3973   }
3974
3975   /* add buffer and metadata */
3976   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3977       pad->sync && sync);
3978   atom_array_append (&pad->fragment_buffers, buf, 256);
3979   pad->fragment_duration -= delta;
3980
3981   if (pad->tfra) {
3982     guint32 sn = atom_traf_get_sample_num (pad->traf);
3983
3984     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3985       atom_tfra_add_entry (pad->tfra, dts, sn);
3986   }
3987
3988   if (G_UNLIKELY (force))
3989     goto flush;
3990
3991   return ret;
3992 }
3993
3994 /* Here's the clever bit of robust recording: Updating the moov
3995  * header is done using a ping-pong scheme inside 2 blocks of size
3996  * 'reserved_moov_size' at the start of the file, in such a way that the
3997  * file on-disk is always valid if interrupted.
3998  * Inside the reserved space, we have 2 pairs of free + moov atoms
3999  * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4000  * at offset "reserved_moov_size".
4001  *
4002  * 1. Free-A has 0 size payload, moov-A immediately after is
4003  *    active/current, and is padded with an internal Free atom to
4004  *    end at reserved_space/2. Free-B is at reserved_space/2, sized
4005  *    to cover the remaining free space (including moov-B).
4006  * 2. We write moov-B (which is invisible inside free-B), and pad it to
4007  *    end at the end of free space. Then, we update free-A to size
4008  *    reserved_space/2 + sizeof(free-B), which hides moov-A and the
4009  *    free-B header, and makes moov-B active.
4010  * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4011  *    Change the size of free-A to make moov-A active again.
4012  * 4. Rinse and repeat.
4013  *
4014  */
4015 static GstFlowReturn
4016 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4017 {
4018   GstSegment segment;
4019   GstFlowReturn ret;
4020   guint64 freeA_offset;
4021   guint32 new_freeA_size;
4022   guint64 new_moov_offset;
4023
4024   /* Update moov info, then seek and rewrite the MOOV atom */
4025   gst_qt_mux_update_global_statistics (qtmux);
4026   gst_qt_mux_configure_moov (qtmux);
4027
4028   gst_qt_mux_update_edit_lists (qtmux);
4029
4030   /* tags into file metadata */
4031   gst_qt_mux_setup_metadata (qtmux);
4032
4033   /* chunks position is set relative to the first byte of the
4034    * MDAT atom payload. Set the overall offset into the file */
4035   atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4036
4037   /* Calculate which moov to rewrite. qtmux->moov_pos points to
4038    * the start of the free-A header */
4039   freeA_offset = qtmux->moov_pos;
4040   if (qtmux->reserved_moov_first_active) {
4041     GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4042     /* After this, freeA will include itself, moovA, plus the freeB
4043      * header */
4044     new_freeA_size = qtmux->reserved_moov_size + 16;
4045   } else {
4046     GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4047     new_freeA_size = 8;
4048   }
4049   /* the moov we update is after free-A, calculate its offset */
4050   new_moov_offset = freeA_offset + new_freeA_size;
4051
4052   /* Swap ping-pong cadence marker */
4053   qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4054
4055   /* seek and rewrite the MOOV atom */
4056   gst_segment_init (&segment, GST_FORMAT_BYTES);
4057   segment.start = new_moov_offset;
4058   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4059
4060   ret =
4061       gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4062       TRUE);
4063   if (ret != GST_FLOW_OK)
4064     return ret;
4065
4066   /* Update the estimated recording space remaining, based on amount used so
4067    * far and duration muxed so far */
4068   if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4069     GstClockTime remain;
4070     GstClockTime time_muxed = qtmux->last_dts;
4071
4072     remain =
4073         gst_util_uint64_scale (qtmux->reserved_moov_size -
4074         qtmux->last_moov_size, time_muxed,
4075         qtmux->last_moov_size - qtmux->base_moov_size);
4076     /* Always under-estimate slightly, so users
4077      * have time to stop muxing before we run out */
4078     if (remain < GST_SECOND / 2)
4079       remain = 0;
4080     else
4081       remain -= GST_SECOND / 2;
4082
4083     GST_INFO_OBJECT (qtmux,
4084         "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4085         ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4086         qtmux->reserved_moov_size, qtmux->last_moov_size,
4087         GST_TIME_ARGS (qtmux->last_dts),
4088         qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4089
4090     GST_OBJECT_LOCK (qtmux);
4091     qtmux->reserved_duration_remaining = remain;
4092     qtmux->muxed_since_last_update = 0;
4093     GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4094         G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4095     GST_OBJECT_UNLOCK (qtmux);
4096   }
4097
4098
4099   /* Now update the moov-A size. Don't pass offset, since we don't need
4100    * send_free_atom() to seek for us - all our callers seek back to
4101    * where they need after this, or they don't need it */
4102   gst_segment_init (&segment, GST_FORMAT_BYTES);
4103   segment.start = freeA_offset;
4104   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4105
4106   ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4107
4108   return ret;
4109 }
4110
4111 static GstFlowReturn
4112 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4113 {
4114   GstSegment segment;
4115   GstFlowReturn flow_ret;
4116
4117   guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4118
4119   GST_OBJECT_LOCK (qtmux);
4120
4121   /* Update the offset of how much we've muxed, so the
4122    * report of remaining space keeps counting down */
4123   if (position > qtmux->last_moov_update &&
4124       position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4125     GST_LOG_OBJECT (qtmux,
4126         "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4127         qtmux->muxed_since_last_update);
4128     qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4129   }
4130
4131   /* Next, check if we're supposed to send periodic moov updates downstream */
4132   if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4133     GST_OBJECT_UNLOCK (qtmux);
4134     return GST_FLOW_OK;
4135   }
4136
4137   /* Update if position is > the threshold or there's been no update yet */
4138   if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4139       (position <= qtmux->last_moov_update ||
4140           (position - qtmux->last_moov_update) <
4141           qtmux->reserved_moov_update_period)) {
4142     GST_OBJECT_UNLOCK (qtmux);
4143     return GST_FLOW_OK;         /* No update needed yet */
4144   }
4145
4146   qtmux->last_moov_update = position;
4147   GST_OBJECT_UNLOCK (qtmux);
4148
4149   GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4150       " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4151       GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4152
4153   flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4154   if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4155     return flow_ret;
4156
4157   /* Seek back to previous position */
4158   gst_segment_init (&segment, GST_FORMAT_BYTES);
4159   segment.start = mdat_offset;
4160   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4161
4162   return flow_ret;
4163 }
4164
4165 static GstFlowReturn
4166 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4167     GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4168     gint64 last_dts, gint64 scaled_duration, guint sample_size,
4169     guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4170 {
4171   GstFlowReturn ret = GST_FLOW_OK;
4172
4173   /* note that a new chunk is started each time (not fancy but works) */
4174   if (qtmux->moov_recov_file) {
4175     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4176             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4177             do_pts, pts_offset)) {
4178       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4179           "recovery file, disabling recovery");
4180       fclose (qtmux->moov_recov_file);
4181       qtmux->moov_recov_file = NULL;
4182     }
4183   }
4184
4185   switch (qtmux->mux_mode) {
4186     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4187       const TrakBufferEntryInfo *sample_entry;
4188       guint64 block_idx = prefill_get_block_index (qtmux, pad);
4189
4190       if (block_idx >= pad->samples->len) {
4191         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4192             ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4193                 block_idx, pad->samples->len));
4194         gst_buffer_unref (buffer);
4195         return GST_FLOW_ERROR;
4196       }
4197
4198       /* Check if all values are as expected */
4199       sample_entry =
4200           &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4201
4202       /* Allow +/- 1 difference for the scaled_duration to allow
4203        * for some rounding errors
4204        */
4205       if (sample_entry->nsamples != nsamples
4206           || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4207           || sample_entry->size != sample_size
4208           || sample_entry->chunk_offset != chunk_offset
4209           || sample_entry->pts_offset != pts_offset
4210           || sample_entry->sync != sync) {
4211         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4212             ("Unexpected values in sample %" G_GUINT64_FORMAT,
4213                 pad->sample_offset + 1));
4214         GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4215             "chunk offset %" G_GUINT64_FORMAT ", "
4216             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4217             sample_entry->nsamples,
4218             sample_entry->delta,
4219             sample_entry->size,
4220             sample_entry->chunk_offset,
4221             sample_entry->pts_offset, sample_entry->sync);
4222         GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4223             "chunk offset %" G_GUINT64_FORMAT ", "
4224             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4225             nsamples,
4226             (guint) scaled_duration,
4227             sample_size, chunk_offset, pts_offset, sync);
4228
4229         gst_buffer_unref (buffer);
4230         return GST_FLOW_ERROR;
4231       }
4232
4233       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4234       break;
4235     }
4236     case GST_QT_MUX_MODE_MOOV_AT_END:
4237     case GST_QT_MUX_MODE_FAST_START:
4238     case GST_QT_MUX_MODE_ROBUST_RECORDING:
4239       atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4240           sample_size, chunk_offset, sync, pts_offset);
4241       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4242       /* Check if it's time to re-write the headers in robust-recording mode */
4243       if (ret == GST_FLOW_OK
4244           && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4245         ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4246       break;
4247     case GST_QT_MUX_MODE_FRAGMENTED:
4248     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4249       /* ensure that always sync samples are marked as such */
4250       ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4251           is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4252           sample_size, !pad->sync || sync, pts_offset);
4253       break;
4254   }
4255
4256   return ret;
4257 }
4258
4259 static void
4260 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4261     guint buffer_size, GstClockTime duration)
4262 {
4263   /* not that much happens here,
4264    * but updating any of this very likely needs to happen all in sync,
4265    * unless there is a very good reason not to */
4266
4267   /* for computing the avg bitrate */
4268   pad->total_bytes += buffer_size;
4269   pad->total_duration += duration;
4270   /* for keeping track of where we are in chunk;
4271    * ensures that data really is located as recorded in atoms */
4272   qtmux->current_chunk_size += buffer_size;
4273   qtmux->current_chunk_duration += duration;
4274 }
4275
4276 static GstFlowReturn
4277 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4278     GstBuffer * buf, GstFlowReturn ret)
4279 {
4280   GstVideoTimeCodeMeta *tc_meta;
4281   GstVideoTimeCode *tc;
4282   GstBuffer *tc_buf;
4283   gsize szret;
4284   guint32 frames_since_daily_jam;
4285   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4286
4287   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4288     return ret;
4289
4290   if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4291     return ret;
4292
4293   tc_meta = gst_buffer_get_video_time_code_meta (buf);
4294   if (!tc_meta)
4295     return ret;
4296
4297   tc = &tc_meta->tc;
4298
4299   /* This means we never got a timecode before */
4300   if (pad->first_tc == NULL) {
4301 #ifndef GST_DISABLE_GST_DEBUG
4302     gchar *tc_str = gst_video_time_code_to_string (tc);
4303     GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4304     g_free (tc_str);
4305 #endif
4306     g_assert (pad->tc_trak == NULL);
4307     pad->first_tc = gst_video_time_code_copy (tc);
4308     /* If frames are out of order, the frame we're currently getting might
4309      * not be the first one. Just write a 0 timecode for now and wait
4310      * until we receive a timecode that's lower than the current one */
4311     if (pad->is_out_of_order) {
4312       pad->first_pts = GST_BUFFER_PTS (buf);
4313       frames_since_daily_jam = 0;
4314       /* Position to rewrite */
4315       pad->tc_pos = qtmux->mdat_size;
4316     } else {
4317       frames_since_daily_jam =
4318           gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4319       frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4320     }
4321     /* Write the timecode trak now */
4322     pad->tc_trak = atom_trak_new (qtmux->context);
4323     atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4324
4325     pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4326     atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4327
4328     atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4329         pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4330
4331     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4332     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4333     g_assert (szret == 4);
4334
4335     atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4336     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4337
4338     /* Need to reset the current chunk (of the previous pad) here because
4339      * some other data was written now above, and the pad has to start a
4340      * new chunk now */
4341     qtmux->current_chunk_offset = -1;
4342     qtmux->current_chunk_size = 0;
4343     qtmux->current_chunk_duration = 0;
4344   } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4345     frames_since_daily_jam =
4346         gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4347     frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4348
4349     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4350     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4351     g_assert (szret == 4);
4352
4353     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4354     pad->tc_pos = -1;
4355
4356     qtmux->current_chunk_offset = -1;
4357     qtmux->current_chunk_size = 0;
4358     qtmux->current_chunk_duration = 0;
4359   } else if (pad->is_out_of_order) {
4360     /* Check for a lower timecode than the one stored */
4361     g_assert (pad->tc_trak != NULL);
4362     if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4363       if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4364         gst_video_time_code_free (pad->first_tc);
4365         pad->first_tc = gst_video_time_code_copy (tc);
4366       }
4367     } else {
4368       guint64 bk_size = qtmux->mdat_size;
4369       GstSegment segment;
4370       /* If this frame's DTS is after the first PTS received, it means
4371        * we've already received the first frame to be presented. Otherwise
4372        * the decoder would need to go back in time */
4373       gst_qt_mux_update_timecode (qtmux, pad);
4374
4375       /* Reset writing position */
4376       gst_segment_init (&segment, GST_FORMAT_BYTES);
4377       segment.start = bk_size;
4378       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4379     }
4380   }
4381
4382   return ret;
4383 }
4384
4385 /*
4386  * Here we push the buffer and update the tables in the track atoms
4387  */
4388 static GstFlowReturn
4389 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4390 {
4391   GstBuffer *last_buf = NULL;
4392   GstClockTime duration;
4393   guint nsamples, sample_size;
4394   guint64 chunk_offset;
4395   gint64 last_dts, scaled_duration;
4396   gint64 pts_offset = 0;
4397   gboolean sync = FALSE;
4398   GstFlowReturn ret = GST_FLOW_OK;
4399   guint buffer_size;
4400
4401   if (!pad->fourcc)
4402     goto not_negotiated;
4403
4404   /* if this pad has a prepare function, call it */
4405   if (pad->prepare_buf_func != NULL) {
4406     GstBuffer *new_buf;
4407
4408     new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4409     if (buf && !new_buf)
4410       return GST_FLOW_OK;
4411     buf = new_buf;
4412   }
4413
4414   ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4415   if (ret != GST_FLOW_OK) {
4416     if (buf)
4417       gst_buffer_unref (buf);
4418     return ret;
4419   }
4420
4421   last_buf = pad->last_buf;
4422   pad->last_buf = buf;
4423
4424   if (last_buf == NULL) {
4425 #ifndef GST_DISABLE_GST_DEBUG
4426     if (buf == NULL) {
4427       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4428           "received NULL buffer, doing nothing",
4429           GST_PAD_NAME (pad->collect.pad));
4430     } else {
4431       GST_LOG_OBJECT (qtmux,
4432           "Pad %s has no previous buffer stored, storing now",
4433           GST_PAD_NAME (pad->collect.pad));
4434     }
4435 #endif
4436     goto exit;
4437   }
4438
4439   if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4440     goto no_pts;
4441
4442   /* if this is the first buffer, store the timestamp */
4443   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4444     if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4445       pad->first_ts = GST_BUFFER_PTS (last_buf);
4446     } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4447       pad->first_ts = GST_BUFFER_DTS (last_buf);
4448     }
4449
4450     if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4451       pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4452     } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4453       pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4454     }
4455
4456     if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4457       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4458     } else {
4459       GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4460           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4461       pad->first_ts = pad->first_dts = 0;
4462     }
4463     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4464         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4465         GST_TIME_ARGS (pad->first_ts));
4466   }
4467
4468   if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4469       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4470       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4471     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4472         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4473         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4474     pad->last_buf = buf = gst_buffer_make_writable (buf);
4475     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4476   }
4477
4478   buffer_size = gst_buffer_get_size (last_buf);
4479
4480   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4481     guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4482     guint fill_size = required_buffer_size - buffer_size;
4483     GstMemory *mem;
4484     GstMapInfo map;
4485
4486     if (required_buffer_size < buffer_size) {
4487       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4488           ("Sample size %u bigger than expected maximum %u", buffer_size,
4489               required_buffer_size));
4490       goto bail;
4491     }
4492
4493     if (fill_size > 0) {
4494       GST_DEBUG_OBJECT (qtmux,
4495           "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4496           required_buffer_size);
4497       mem = gst_allocator_alloc (NULL, fill_size, NULL);
4498       gst_memory_map (mem, &map, GST_MAP_WRITE);
4499       memset (map.data, 0, map.size);
4500       gst_memory_unmap (mem, &map);
4501       last_buf = gst_buffer_make_writable (last_buf);
4502       gst_buffer_append_memory (last_buf, mem);
4503       buffer_size = required_buffer_size;
4504     }
4505   }
4506
4507   /* duration actually means time delta between samples, so we calculate
4508    * the duration based on the difference in DTS or PTS, falling back
4509    * to DURATION if the other two don't exist, such as with the last
4510    * sample before EOS. Or use 0 if nothing else is available */
4511   if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4512     duration = GST_BUFFER_DURATION (last_buf);
4513   else
4514     duration = 0;
4515   if (!pad->sparse) {
4516     if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4517         && GST_BUFFER_DTS_IS_VALID (last_buf))
4518       duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4519     else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4520         && GST_BUFFER_PTS_IS_VALID (last_buf))
4521       duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4522   }
4523
4524   if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4525     GST_DEBUG_OBJECT (qtmux,
4526         "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4527         ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4528         GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4529         qtmux->current_chunk_size,
4530         GST_TIME_ARGS (qtmux->current_chunk_duration));
4531     qtmux->current_pad = pad;
4532     if (qtmux->current_chunk_offset == -1)
4533       qtmux->current_chunk_offset = qtmux->mdat_size;
4534     else
4535       qtmux->current_chunk_offset += qtmux->current_chunk_size;
4536     qtmux->current_chunk_size = 0;
4537     qtmux->current_chunk_duration = 0;
4538   }
4539
4540   last_dts = gst_util_uint64_scale_round (pad->last_dts,
4541       atom_trak_get_timescale (pad->trak), GST_SECOND);
4542
4543   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4544   if (pad->sample_size && !qtmux->fragment_sequence) {
4545     GstClockTime expected_timestamp;
4546
4547     /* Constant size packets: usually raw audio (with many samples per
4548        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4549      */
4550     sample_size = pad->sample_size;
4551     if (buffer_size % sample_size != 0)
4552       goto fragmented_sample;
4553
4554     /* note: qt raw audio storage warps it implicitly into a timewise
4555      * perfect stream, discarding buffer times.
4556      * If the difference between the current PTS and the expected one
4557      * becomes too big, we error out: there was a gap and we have no way to
4558      * represent that, causing A/V sync to be off */
4559     expected_timestamp =
4560         gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4561         atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4562     if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4563             expected_timestamp) > qtmux->max_raw_audio_drift)
4564       goto raw_audio_timestamp_drift;
4565
4566     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4567       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4568           atom_trak_get_timescale (pad->trak), GST_SECOND);
4569       duration = GST_BUFFER_DURATION (last_buf);
4570     } else {
4571       nsamples = buffer_size / sample_size;
4572       duration =
4573           gst_util_uint64_scale_round (nsamples, GST_SECOND,
4574           atom_trak_get_timescale (pad->trak));
4575     }
4576
4577     /* timescale = samplerate */
4578     scaled_duration = 1;
4579     pad->last_dts =
4580         pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4581         nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4582   } else {
4583     nsamples = 1;
4584     sample_size = buffer_size;
4585     if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4586             || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4587       gint64 scaled_dts;
4588       if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4589         pad->last_dts = GST_BUFFER_DTS (buf);
4590       } else {
4591         pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4592       }
4593       if ((gint64) (pad->last_dts) < 0) {
4594         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4595             atom_trak_get_timescale (pad->trak), GST_SECOND);
4596       } else {
4597         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4598             atom_trak_get_timescale (pad->trak), GST_SECOND);
4599       }
4600       scaled_duration = scaled_dts - last_dts;
4601       last_dts = scaled_dts;
4602     } else {
4603       /* first convert intended timestamp (in GstClockTime resolution) to
4604        * trak timescale, then derive delta;
4605        * this ensures sums of (scale)delta add up to converted timestamp,
4606        * which only deviates at most 1/scale from timestamp itself */
4607       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4608           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4609       pad->last_dts += duration;
4610     }
4611   }
4612
4613   gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4614
4615   chunk_offset = qtmux->current_chunk_offset;
4616
4617   GST_LOG_OBJECT (qtmux,
4618       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4619       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4620   GST_LOG_OBJECT (qtmux,
4621       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4622       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4623       nsamples, scaled_duration, sample_size, chunk_offset);
4624
4625   /* might be a sync sample */
4626   if (pad->sync &&
4627       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4628     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4629         GST_PAD_NAME (pad->collect.pad));
4630     sync = TRUE;
4631   }
4632
4633   if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4634     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4635         atom_trak_get_timescale (pad->trak), GST_SECOND);
4636     pts_offset =
4637         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4638             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4639   } else {
4640     pts_offset = 0;
4641     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4642         atom_trak_get_timescale (pad->trak), GST_SECOND);
4643   }
4644   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4645       " timebase_dts: %d pts_offset: %d",
4646       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4647       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4648       (int) (last_dts), (int) (pts_offset));
4649
4650   if (GST_CLOCK_TIME_IS_VALID (duration)
4651       && (qtmux->current_chunk_duration > qtmux->longest_chunk
4652           || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4653     GST_DEBUG_OBJECT (qtmux,
4654         "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4655         GST_TIME_ARGS (qtmux->current_chunk_duration),
4656         GST_PAD_NAME (pad->collect.pad));
4657     qtmux->longest_chunk = qtmux->current_chunk_duration;
4658   }
4659
4660   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4661     const TrakBufferEntryInfo *sample_entry;
4662     guint64 block_idx = prefill_get_block_index (qtmux, pad);
4663
4664     if (block_idx >= pad->samples->len) {
4665       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4666           ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4667               block_idx, pad->samples->len));
4668       goto bail;
4669     }
4670
4671     /* Check if all values are as expected */
4672     sample_entry =
4673         &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4674
4675     if (chunk_offset < sample_entry->chunk_offset) {
4676       guint fill_size = sample_entry->chunk_offset - chunk_offset;
4677       GstBuffer *fill_buf;
4678
4679       fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4680       gst_buffer_memset (fill_buf, 0, 0, fill_size);
4681
4682       ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4683       if (ret != GST_FLOW_OK)
4684         goto bail;
4685       qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4686       qtmux->current_chunk_size = buffer_size;
4687       qtmux->current_chunk_duration = duration;
4688     } else if (chunk_offset != sample_entry->chunk_offset) {
4689       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4690           ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4691               G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4692       goto bail;
4693     }
4694   }
4695
4696   /* now we go and register this buffer/sample all over */
4697   ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4698       buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4699       chunk_offset, sync, TRUE, pts_offset);
4700   pad->sample_offset += nsamples;
4701
4702   /* if this is sparse and we have a next buffer, check if there is any gap
4703    * between them to insert an empty sample */
4704   if (pad->sparse && buf) {
4705     if (pad->create_empty_buffer) {
4706       GstBuffer *empty_buf;
4707       gint64 empty_duration =
4708           GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4709       gint64 empty_duration_scaled;
4710       guint empty_size;
4711
4712       empty_buf = pad->create_empty_buffer (pad, empty_duration);
4713
4714       pad->last_dts = GST_BUFFER_PTS (buf);
4715       empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4716           atom_trak_get_timescale (pad->trak), GST_SECOND)
4717           - (last_dts + scaled_duration);
4718       empty_size = gst_buffer_get_size (empty_buf);
4719
4720       gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4721           empty_duration);
4722
4723       ret =
4724           gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4725           last_dts + scaled_duration, empty_duration_scaled,
4726           empty_size, chunk_offset, sync, TRUE, 0);
4727     } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4728       /* This assert is kept here to make sure implementors of new
4729        * sparse input format decide whether there needs to be special
4730        * gap handling or not */
4731       g_assert_not_reached ();
4732       GST_WARNING_OBJECT (qtmux,
4733           "no empty buffer creation function found for pad %s",
4734           GST_PAD_NAME (pad->collect.pad));
4735     }
4736   }
4737
4738 exit:
4739
4740   return ret;
4741
4742   /* ERRORS */
4743 bail:
4744   {
4745     gst_buffer_unref (last_buf);
4746     return GST_FLOW_ERROR;
4747   }
4748 fragmented_sample:
4749   {
4750     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4751         ("Audio buffer contains fragmented sample."));
4752     goto bail;
4753   }
4754 raw_audio_timestamp_drift:
4755   {
4756     /* TODO: Could in theory be implemented with edit lists */
4757     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4758         ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4759             ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4760             GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4761             GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4762                     GST_SECOND,
4763                     atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4764     goto bail;
4765   }
4766 no_pts:
4767   {
4768     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4769     goto bail;
4770   }
4771 not_negotiated:
4772   {
4773     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4774         ("format wasn't negotiated before buffer flow on pad %s",
4775             GST_PAD_NAME (pad->collect.pad)));
4776     if (buf)
4777       gst_buffer_unref (buf);
4778     return GST_FLOW_NOT_NEGOTIATED;
4779   }
4780 }
4781
4782 /*
4783  * DTS running time can be negative. There is no way to represent that in
4784  * MP4 however, thus we need to offset DTS so that it starts from 0.
4785  */
4786 static void
4787 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4788     GstCollectData * cdata, GstBuffer ** buf)
4789 {
4790   GstClockTime pts;
4791   gint64 dts;
4792
4793   pts = GST_BUFFER_PTS (*buf);
4794   dts = GST_COLLECT_PADS_DTS (cdata);
4795
4796   GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4797       " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4798       GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4799
4800   if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4801     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4802       pad->dts_adjustment = -dts;
4803     else
4804       pad->dts_adjustment = 0;
4805   }
4806
4807   if (pad->dts_adjustment > 0) {
4808     *buf = gst_buffer_make_writable (*buf);
4809
4810     dts += pad->dts_adjustment;
4811
4812     if (GST_CLOCK_TIME_IS_VALID (pts))
4813       pts += pad->dts_adjustment;
4814
4815     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4816       GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4817       dts = 0;
4818     }
4819
4820     if (pts < dts) {
4821       GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4822       pts = dts;
4823     }
4824
4825     GST_BUFFER_PTS (*buf) = pts;
4826     GST_BUFFER_DTS (*buf) = dts;
4827
4828     GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4829         " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4830   }
4831 }
4832
4833 static GstQTPad *
4834 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4835 {
4836   GSList *walk;
4837   GstQTPad *best_pad = NULL;
4838
4839   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4840     guint64 smallest_offset = G_MAXUINT64;
4841     guint64 chunk_offset = 0;
4842
4843     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4844       GstCollectData *cdata = (GstCollectData *) walk->data;
4845       GstQTPad *qtpad = (GstQTPad *) cdata;
4846       const TrakBufferEntryInfo *sample_entry;
4847       guint64 block_idx, current_block_idx;
4848       guint64 chunk_offset_offset = 0;
4849       GstBuffer *tmp_buf =
4850           gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4851
4852       /* Check for EOS pads and just skip them */
4853       if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4854               || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4855         continue;
4856       if (tmp_buf)
4857         gst_buffer_unref (tmp_buf);
4858
4859       /* Find the exact offset where the next sample of this track is supposed
4860        * to be written at */
4861       block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4862       sample_entry =
4863           &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4864       while (block_idx > 0) {
4865         const TrakBufferEntryInfo *tmp =
4866             &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4867
4868         if (tmp->chunk_offset != sample_entry->chunk_offset)
4869           break;
4870         chunk_offset_offset += tmp->size * tmp->nsamples;
4871         block_idx--;
4872       }
4873
4874       /* Except for the previously selected pad being EOS we always have
4875        *  qtmux->current_chunk_offset + qtmux->current_chunk_size
4876        *    ==
4877        *  sample_entry->chunk_offset + chunk_offset_offset
4878        * for the best pad. Instead of checking that, we just return the
4879        * pad that has the smallest offset for the next to-be-written sample.
4880        */
4881       if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4882         smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4883         best_pad = qtpad;
4884         chunk_offset = sample_entry->chunk_offset;
4885       }
4886     }
4887
4888     if (chunk_offset != qtmux->current_chunk_offset) {
4889       qtmux->current_pad = NULL;
4890     }
4891
4892     return best_pad;
4893   }
4894
4895   if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4896           || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4897           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4898       && (qtmux->interleave_time == 0
4899           || qtmux->current_chunk_duration <= qtmux->interleave_time)
4900       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4901       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4902     GstBuffer *tmp_buf =
4903         gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4904
4905     if (tmp_buf || qtmux->current_pad->last_buf) {
4906       best_pad = qtmux->current_pad;
4907       if (tmp_buf)
4908         gst_buffer_unref (tmp_buf);
4909       GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4910           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4911     }
4912   } else if (qtmux->collect->data->next) {
4913     /* Only switch pads if we have more than one, otherwise
4914      * we can just put everything into a single chunk and save
4915      * a few bytes of offsets
4916      */
4917     if (qtmux->current_pad)
4918       GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4919           GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4920     best_pad = qtmux->current_pad = NULL;
4921   }
4922
4923   if (!best_pad) {
4924     GstClockTime best_time = GST_CLOCK_TIME_NONE;
4925
4926     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4927       GstCollectData *cdata = (GstCollectData *) walk->data;
4928       GstQTPad *qtpad = (GstQTPad *) cdata;
4929       GstBuffer *tmp_buf;
4930       GstClockTime timestamp;
4931
4932       tmp_buf = gst_collect_pads_peek (pads, cdata);
4933       if (!tmp_buf) {
4934         /* This one is newly EOS now, finish it for real */
4935         if (qtpad->last_buf) {
4936           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4937         } else {
4938           continue;
4939         }
4940       } else {
4941         if (qtpad->last_buf)
4942           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4943         else
4944           timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4945       }
4946
4947       if (best_pad == NULL ||
4948           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4949         best_pad = qtpad;
4950         best_time = timestamp;
4951       }
4952
4953       if (tmp_buf)
4954         gst_buffer_unref (tmp_buf);
4955     }
4956
4957     if (best_pad) {
4958       GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4959           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4960     } else {
4961       GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4962     }
4963   }
4964
4965   return best_pad;
4966 }
4967
4968 static GstFlowReturn
4969 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4970 {
4971   GstFlowReturn ret = GST_FLOW_OK;
4972   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4973   GstQTPad *best_pad = NULL;
4974
4975   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4976     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4977       return ret;
4978
4979     qtmux->state = GST_QT_MUX_STATE_DATA;
4980   }
4981
4982   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4983     return GST_FLOW_EOS;
4984
4985   best_pad = find_best_pad (qtmux, pads);
4986
4987   /* clipping already converted to running time */
4988   if (best_pad != NULL) {
4989     GstBuffer *buf = NULL;
4990
4991     if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4992         best_pad->raw_audio_adapter == NULL ||
4993         best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4994       buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4995
4996     g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4997             && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4998
4999     if (buf)
5000       gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
5001           (GstCollectData *) best_pad, &buf);
5002
5003     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5004   } else {
5005     qtmux->state = GST_QT_MUX_STATE_EOS;
5006     ret = gst_qt_mux_stop_file (qtmux);
5007     if (ret == GST_FLOW_OK) {
5008       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
5009       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5010       ret = GST_FLOW_EOS;
5011     } else {
5012       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5013           gst_flow_get_name (ret));
5014     }
5015   }
5016
5017   return ret;
5018 }
5019
5020 static gboolean
5021 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5022 {
5023   GstStructure *structure = (GstStructure *) user_data;
5024   const GValue *other = gst_structure_id_get_value (structure, field_id);
5025   if (other == NULL)
5026     return FALSE;
5027   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5028 }
5029
5030 static gboolean
5031 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5032     GstCaps * superset)
5033 {
5034   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5035   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5036
5037   return gst_structure_foreach (sub_s, check_field, sup_s);
5038 }
5039
5040 /* will unref @qtmux */
5041 static gboolean
5042 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5043 {
5044   GstCaps *current_caps;
5045
5046   /* does not go well to renegotiate stream mid-way, unless
5047    * the old caps are a subset of the new one (this means upstream
5048    * added more info to the caps, as both should be 'fixed' caps) */
5049   current_caps = gst_pad_get_current_caps (pad);
5050   g_assert (caps != NULL);
5051
5052   if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5053     gst_caps_unref (current_caps);
5054     GST_WARNING_OBJECT (qtmux,
5055         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5056         GST_PAD_NAME (pad), caps);
5057     gst_object_unref (qtmux);
5058     return FALSE;
5059   }
5060
5061   GST_DEBUG_OBJECT (qtmux,
5062       "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5063       GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5064   gst_object_unref (qtmux);
5065   gst_caps_unref (current_caps);
5066
5067   return TRUE;
5068 }
5069
5070 static gboolean
5071 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5072 {
5073   GstPad *pad = qtpad->collect.pad;
5074   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5075   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5076   GstStructure *structure;
5077   const gchar *mimetype;
5078   gint rate, channels;
5079   const GValue *value = NULL;
5080   const GstBuffer *codec_data = NULL;
5081   GstQTMuxFormat format;
5082   AudioSampleEntry entry = { 0, };
5083   AtomInfo *ext_atom = NULL;
5084   gint constant_size = 0;
5085   const gchar *stream_format;
5086   guint32 timescale;
5087
5088   if (qtpad->fourcc)
5089     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5090
5091   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5092       GST_DEBUG_PAD_NAME (pad), caps);
5093
5094   qtpad->prepare_buf_func = NULL;
5095
5096   format = qtmux_klass->format;
5097   structure = gst_caps_get_structure (caps, 0);
5098   mimetype = gst_structure_get_name (structure);
5099
5100   /* common info */
5101   if (!gst_structure_get_int (structure, "channels", &channels) ||
5102       !gst_structure_get_int (structure, "rate", &rate)) {
5103     goto refuse_caps;
5104   }
5105
5106   /* optional */
5107   value = gst_structure_get_value (structure, "codec_data");
5108   if (value != NULL)
5109     codec_data = gst_value_get_buffer (value);
5110
5111   qtpad->is_out_of_order = FALSE;
5112
5113   /* set common properties */
5114   entry.sample_rate = rate;
5115   entry.channels = channels;
5116   /* default */
5117   entry.sample_size = 16;
5118   /* this is the typical compressed case */
5119   if (format == GST_QT_MUX_FORMAT_QT) {
5120     entry.version = 1;
5121     entry.compression_id = -2;
5122   }
5123
5124   /* now map onto a fourcc, and some extra properties */
5125   if (strcmp (mimetype, "audio/mpeg") == 0) {
5126     gint mpegversion = 0, mpegaudioversion = 0;
5127     gint layer = -1;
5128
5129     gst_structure_get_int (structure, "mpegversion", &mpegversion);
5130     switch (mpegversion) {
5131       case 1:
5132         gst_structure_get_int (structure, "layer", &layer);
5133         gst_structure_get_int (structure, "mpegaudioversion",
5134             &mpegaudioversion);
5135
5136         /* mp1/2/3 */
5137         /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5138         if (format == GST_QT_MUX_FORMAT_QT)
5139           entry.fourcc = FOURCC__mp3;
5140         else {
5141           entry.fourcc = FOURCC_mp4a;
5142           ext_atom =
5143               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5144               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5145               qtpad->max_bitrate);
5146         }
5147         if (layer == 1) {
5148           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5149               || format == GST_QT_MUX_FORMAT_QT);
5150           entry.samples_per_packet = 384;
5151         } else if (layer == 2) {
5152           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5153               || format == GST_QT_MUX_FORMAT_QT);
5154           entry.samples_per_packet = 1152;
5155         } else {
5156           g_warn_if_fail (layer == 3);
5157           entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5158         }
5159         entry.bytes_per_sample = 2;
5160         break;
5161       case 4:
5162
5163         /* check stream-format */
5164         stream_format = gst_structure_get_string (structure, "stream-format");
5165         if (stream_format) {
5166           if (strcmp (stream_format, "raw") != 0) {
5167             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5168                 "please use 'raw'", stream_format);
5169             goto refuse_caps;
5170           }
5171         } else {
5172           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5173               "assuming 'raw'");
5174         }
5175
5176         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5177           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5178           goto refuse_caps;
5179         } else {
5180           guint8 profile;
5181
5182           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5183           /* warn if not Low Complexity profile */
5184           profile >>= 3;
5185           if (profile != 2)
5186             GST_WARNING_OBJECT (qtmux,
5187                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5188         }
5189
5190         /* AAC */
5191         entry.fourcc = FOURCC_mp4a;
5192
5193         if (format == GST_QT_MUX_FORMAT_QT)
5194           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5195               qtpad->avg_bitrate, qtpad->max_bitrate);
5196         else
5197           ext_atom =
5198               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5199               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5200               qtpad->max_bitrate);
5201         break;
5202       default:
5203         break;
5204     }
5205   } else if (strcmp (mimetype, "audio/AMR") == 0) {
5206     entry.fourcc = FOURCC_samr;
5207     entry.sample_size = 16;
5208     entry.samples_per_packet = 160;
5209     entry.bytes_per_sample = 2;
5210     ext_atom = build_amr_extension ();
5211   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5212     entry.fourcc = FOURCC_sawb;
5213     entry.sample_size = 16;
5214     entry.samples_per_packet = 320;
5215     entry.bytes_per_sample = 2;
5216     ext_atom = build_amr_extension ();
5217   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5218     GstAudioInfo info;
5219
5220     gst_audio_info_init (&info);
5221     if (!gst_audio_info_from_caps (&info, caps))
5222       goto refuse_caps;
5223
5224     /* spec has no place for a distinction in these */
5225     if (info.finfo->width != info.finfo->depth) {
5226       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5227       goto refuse_caps;
5228     }
5229
5230     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5231       if (info.finfo->endianness == G_LITTLE_ENDIAN)
5232         entry.fourcc = FOURCC_sowt;
5233       else if (info.finfo->endianness == G_BIG_ENDIAN)
5234         entry.fourcc = FOURCC_twos;
5235       else
5236         entry.fourcc = FOURCC_sowt;
5237       /* maximum backward compatibility; only new version for > 16 bit */
5238       if (info.finfo->depth <= 16)
5239         entry.version = 0;
5240       /* not compressed in any case */
5241       entry.compression_id = 0;
5242       /* QT spec says: max at 16 bit even if sample size were actually larger,
5243        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5244       entry.sample_size = info.finfo->depth;
5245       entry.bytes_per_sample = info.finfo->depth / 8;
5246       entry.samples_per_packet = 1;
5247       entry.bytes_per_packet = info.finfo->depth / 8;
5248       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5249     } else {
5250       if (info.finfo->width == 8 && info.finfo->depth == 8) {
5251         /* fall back to old 8-bit version */
5252         entry.fourcc = FOURCC_raw_;
5253         entry.version = 0;
5254         entry.compression_id = 0;
5255         entry.sample_size = 8;
5256       } else {
5257         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5258         goto refuse_caps;
5259       }
5260     }
5261     constant_size = (info.finfo->depth / 8) * info.channels;
5262   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5263     entry.fourcc = FOURCC_alaw;
5264     entry.samples_per_packet = 1023;
5265     entry.bytes_per_sample = 2;
5266   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5267     entry.fourcc = FOURCC_ulaw;
5268     entry.samples_per_packet = 1023;
5269     entry.bytes_per_sample = 2;
5270   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5271     gint blocksize;
5272     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5273       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5274       goto refuse_caps;
5275     }
5276     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5277        0x11 */
5278     entry.fourcc = MS_WAVE_FOURCC (0x11);
5279     /* 4 byte header per channel (including one sample). 2 samples per byte
5280        remaining. Simplifying gives the following (samples per block per
5281        channel) */
5282     entry.samples_per_packet = 2 * blocksize / channels - 7;
5283     entry.bytes_per_sample = 2;
5284
5285     entry.bytes_per_frame = blocksize;
5286     entry.bytes_per_packet = blocksize / channels;
5287     /* ADPCM has constant size packets */
5288     constant_size = 1;
5289     /* TODO: I don't really understand why this helps, but it does! Constant
5290      * size and compression_id of -2 seem to be incompatible, and other files
5291      * in the wild use this too. */
5292     entry.compression_id = -1;
5293
5294     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5295   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5296     GstBuffer *codec_config;
5297     gint len;
5298     GstMapInfo map;
5299
5300     entry.fourcc = FOURCC_alac;
5301     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5302     /* let's check if codec data already comes with 'alac' atom prefix */
5303     if (!codec_data || (len = map.size) < 28) {
5304       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5305       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5306       goto refuse_caps;
5307     }
5308     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5309       len -= 8;
5310       codec_config =
5311           gst_buffer_copy_region ((GstBuffer *) codec_data,
5312           GST_BUFFER_COPY_MEMORY, 8, len);
5313     } else {
5314       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5315     }
5316     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5317     if (len != 28) {
5318       /* does not look good, but perhaps some trailing unneeded stuff */
5319       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5320     }
5321     if (format == GST_QT_MUX_FORMAT_QT)
5322       ext_atom = build_mov_alac_extension (codec_config);
5323     else
5324       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5325     /* set some more info */
5326     gst_buffer_map (codec_config, &map, GST_MAP_READ);
5327     entry.bytes_per_sample = 2;
5328     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5329     gst_buffer_unmap (codec_config, &map);
5330     gst_buffer_unref (codec_config);
5331   } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5332     entry.fourcc = FOURCC_ac_3;
5333
5334     /* Fixed values according to TS 102 366 but it also mentions that
5335      * they should be ignored */
5336     entry.channels = 2;
5337     entry.sample_size = 16;
5338
5339     /* AC-3 needs an extension atom but its data can only be obtained from
5340      * the stream itself. Abuse the prepare_buf_func so we parse a frame
5341      * and get the needed data */
5342     qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5343   } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5344     /* Based on the specification defined in:
5345      * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5346     guint8 channels, mapping_family, stream_count, coupled_count;
5347     guint16 pre_skip;
5348     gint16 output_gain;
5349     guint32 rate;
5350     guint8 channel_mapping[256];
5351     const GValue *streamheader;
5352     const GValue *first_element;
5353     GstBuffer *header;
5354
5355     entry.fourcc = FOURCC_opus;
5356     entry.sample_size = 16;
5357
5358     streamheader = gst_structure_get_value (structure, "streamheader");
5359     if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5360         gst_value_array_get_size (streamheader) != 0) {
5361       first_element = gst_value_array_get_value (streamheader, 0);
5362       header = gst_value_get_buffer (first_element);
5363       if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5364               &mapping_family, &stream_count, &coupled_count, channel_mapping,
5365               &pre_skip, &output_gain)) {
5366         GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5367         goto refuse_caps;
5368       }
5369     } else {
5370       GST_WARNING_OBJECT (qtmux,
5371           "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5372
5373       if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5374               &mapping_family, &stream_count, &coupled_count,
5375               channel_mapping)) {
5376         GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5377         goto refuse_caps;
5378       }
5379       pre_skip = 0;
5380       output_gain = 0;
5381     }
5382
5383     entry.channels = channels;
5384     ext_atom = build_opus_extension (rate, channels, mapping_family,
5385         stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5386   }
5387
5388   if (!entry.fourcc)
5389     goto refuse_caps;
5390
5391   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5392   if (!timescale && qtmux->trak_timescale)
5393     timescale = qtmux->trak_timescale;
5394   else if (!timescale)
5395     timescale = entry.sample_rate;
5396
5397   /* ok, set the pad info accordingly */
5398   qtpad->fourcc = entry.fourcc;
5399   qtpad->sample_size = constant_size;
5400   qtpad->trak_ste =
5401       (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5402       qtmux->context, &entry, timescale, ext_atom, constant_size);
5403
5404   gst_object_unref (qtmux);
5405   return TRUE;
5406
5407   /* ERRORS */
5408 refuse_caps:
5409   {
5410     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5411         GST_PAD_NAME (pad), caps);
5412     gst_object_unref (qtmux);
5413     return FALSE;
5414   }
5415 }
5416
5417 static gboolean
5418 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5419 {
5420   GstPad *pad = qtpad->collect.pad;
5421   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5422   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5423   GstStructure *structure;
5424   const gchar *mimetype;
5425   gint width, height, depth = -1;
5426   gint framerate_num, framerate_den;
5427   guint32 rate;
5428   const GValue *value = NULL;
5429   const GstBuffer *codec_data = NULL;
5430   VisualSampleEntry entry = { 0, };
5431   GstQTMuxFormat format;
5432   AtomInfo *ext_atom = NULL;
5433   GList *ext_atom_list = NULL;
5434   gboolean sync = FALSE;
5435   int par_num, par_den;
5436   const gchar *multiview_mode;
5437
5438   if (qtpad->fourcc)
5439     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5440
5441   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5442       GST_DEBUG_PAD_NAME (pad), caps);
5443
5444   qtpad->prepare_buf_func = NULL;
5445
5446   format = qtmux_klass->format;
5447   structure = gst_caps_get_structure (caps, 0);
5448   mimetype = gst_structure_get_name (structure);
5449
5450   /* required parts */
5451   if (!gst_structure_get_int (structure, "width", &width) ||
5452       !gst_structure_get_int (structure, "height", &height))
5453     goto refuse_caps;
5454
5455   /* optional */
5456   depth = -1;
5457   /* works as a default timebase */
5458   framerate_num = 10000;
5459   framerate_den = 1;
5460   gst_structure_get_fraction (structure, "framerate", &framerate_num,
5461       &framerate_den);
5462   gst_structure_get_int (structure, "depth", &depth);
5463   value = gst_structure_get_value (structure, "codec_data");
5464   if (value != NULL)
5465     codec_data = gst_value_get_buffer (value);
5466
5467   par_num = 1;
5468   par_den = 1;
5469   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5470       &par_den);
5471
5472   qtpad->is_out_of_order = FALSE;
5473
5474   /* bring frame numerator into a range that ensures both reasonable resolution
5475    * as well as a fair duration */
5476   qtpad->expected_sample_duration_n = framerate_num;
5477   qtpad->expected_sample_duration_d = framerate_den;
5478
5479   rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5480   if (!rate && qtmux->trak_timescale)
5481     rate = qtmux->trak_timescale;
5482   else if (!rate)
5483     rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5484
5485   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5486       rate);
5487
5488   multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5489   if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5490     GstVideoMultiviewMode mode;
5491     GstVideoMultiviewFlags flags = 0;
5492
5493     mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5494     gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5495     switch (mode) {
5496       case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5497         qtpad->trak->mdia.minf.stbl.svmi =
5498             atom_svmi_new (0,
5499             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5500         break;
5501       case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5502         qtpad->trak->mdia.minf.stbl.svmi =
5503             atom_svmi_new (1,
5504             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5505         break;
5506       case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5507         qtpad->trak->mdia.minf.stbl.svmi =
5508             atom_svmi_new (2,
5509             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5510         break;
5511       default:
5512         GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5513             multiview_mode);
5514         break;
5515     }
5516   }
5517
5518   /* set common properties */
5519   entry.width = width;
5520   entry.height = height;
5521   entry.par_n = par_num;
5522   entry.par_d = par_den;
5523   /* should be OK according to qt and iso spec, override if really needed */
5524   entry.color_table_id = -1;
5525   entry.frame_count = 1;
5526   entry.depth = 24;
5527
5528   /* sync entries by default */
5529   sync = TRUE;
5530
5531   /* now map onto a fourcc, and some extra properties */
5532   if (strcmp (mimetype, "video/x-raw") == 0) {
5533     const gchar *format;
5534     GstVideoFormat fmt;
5535     const GstVideoFormatInfo *vinfo;
5536
5537     format = gst_structure_get_string (structure, "format");
5538     fmt = gst_video_format_from_string (format);
5539     vinfo = gst_video_format_get_info (fmt);
5540
5541     switch (fmt) {
5542       case GST_VIDEO_FORMAT_UYVY:
5543         if (depth == -1)
5544           depth = 24;
5545         entry.fourcc = FOURCC_2vuy;
5546         entry.depth = depth;
5547         sync = FALSE;
5548         break;
5549       case GST_VIDEO_FORMAT_v210:
5550         if (depth == -1)
5551           depth = 24;
5552         entry.fourcc = FOURCC_v210;
5553         entry.depth = depth;
5554         sync = FALSE;
5555         break;
5556       default:
5557         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5558           entry.fourcc = FOURCC_raw_;
5559           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5560           sync = FALSE;
5561         }
5562         break;
5563     }
5564   } else if (strcmp (mimetype, "video/x-h263") == 0) {
5565     ext_atom = NULL;
5566     if (format == GST_QT_MUX_FORMAT_QT)
5567       entry.fourcc = FOURCC_h263;
5568     else
5569       entry.fourcc = FOURCC_s263;
5570     ext_atom = build_h263_extension ();
5571     if (ext_atom != NULL)
5572       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5573   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5574       strcmp (mimetype, "video/mpeg") == 0) {
5575     gint version = 0;
5576
5577     if (strcmp (mimetype, "video/x-divx") == 0) {
5578       gst_structure_get_int (structure, "divxversion", &version);
5579       version = version == 5 ? 1 : 0;
5580     } else {
5581       gst_structure_get_int (structure, "mpegversion", &version);
5582       version = version == 4 ? 1 : 0;
5583     }
5584     if (version) {
5585       entry.fourcc = FOURCC_mp4v;
5586       ext_atom =
5587           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5588           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5589           qtpad->max_bitrate);
5590       if (ext_atom != NULL)
5591         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5592       if (!codec_data)
5593         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5594             "output might not play in Apple QuickTime (try global-headers?)");
5595     }
5596   } else if (strcmp (mimetype, "video/x-h264") == 0) {
5597     if (!codec_data) {
5598       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5599       goto refuse_caps;
5600     }
5601
5602     entry.fourcc = FOURCC_avc1;
5603
5604     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5605     if (ext_atom != NULL)
5606       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5607     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5608     if (ext_atom != NULL)
5609       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5610   } else if (strcmp (mimetype, "video/x-h265") == 0) {
5611     const gchar *format;
5612
5613     if (!codec_data) {
5614       GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5615       goto refuse_caps;
5616     }
5617
5618     format = gst_structure_get_string (structure, "stream-format");
5619     if (strcmp (format, "hvc1") == 0)
5620       entry.fourcc = FOURCC_hvc1;
5621     else if (strcmp (format, "hev1") == 0)
5622       entry.fourcc = FOURCC_hev1;
5623
5624     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5625     if (ext_atom != NULL)
5626       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5627
5628     ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5629     if (ext_atom != NULL)
5630       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5631
5632   } else if (strcmp (mimetype, "video/x-svq") == 0) {
5633     gint version = 0;
5634     const GstBuffer *seqh = NULL;
5635     const GValue *seqh_value;
5636     gdouble gamma = 0;
5637
5638     gst_structure_get_int (structure, "svqversion", &version);
5639     if (version == 3) {
5640       entry.fourcc = FOURCC_SVQ3;
5641       entry.version = 3;
5642       entry.depth = 32;
5643
5644       seqh_value = gst_structure_get_value (structure, "seqh");
5645       if (seqh_value) {
5646         seqh = gst_value_get_buffer (seqh_value);
5647         ext_atom = build_SMI_atom (seqh);
5648         if (ext_atom)
5649           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5650       }
5651
5652       /* we need to add the gamma anyway because quicktime might crash
5653        * when it doesn't find it */
5654       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5655         /* it seems that using 0 here makes it ignored */
5656         gamma = 0.0;
5657       }
5658       ext_atom = build_gama_atom (gamma);
5659       if (ext_atom)
5660         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5661     } else {
5662       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5663           "a bug at http://bugzilla.gnome.org", version);
5664     }
5665   } else if (strcmp (mimetype, "video/x-dv") == 0) {
5666     gint version = 0;
5667     gboolean pal = TRUE;
5668
5669     sync = FALSE;
5670     if (framerate_num != 25 || framerate_den != 1)
5671       pal = FALSE;
5672     gst_structure_get_int (structure, "dvversion", &version);
5673     /* fall back to typical one */
5674     if (!version)
5675       version = 25;
5676     switch (version) {
5677       case 25:
5678         if (pal)
5679           entry.fourcc = FOURCC_dvcp;
5680         else
5681           entry.fourcc = FOURCC_dvc_;
5682         break;
5683       case 50:
5684         if (pal)
5685           entry.fourcc = FOURCC_dv5p;
5686         else
5687           entry.fourcc = FOURCC_dv5n;
5688         break;
5689       default:
5690         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5691         break;
5692     }
5693   } else if (strcmp (mimetype, "image/jpeg") == 0) {
5694     entry.fourcc = FOURCC_jpeg;
5695     sync = FALSE;
5696   } else if (strcmp (mimetype, "image/png") == 0) {
5697     entry.fourcc = FOURCC_png;
5698     sync = FALSE;
5699   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5700       strcmp (mimetype, "image/x-jpc") == 0) {
5701     const gchar *colorspace;
5702     const GValue *cmap_array;
5703     const GValue *cdef_array;
5704     gint ncomp = 0;
5705
5706     if (strcmp (mimetype, "image/x-jpc") == 0) {
5707       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5708     }
5709
5710     gst_structure_get_int (structure, "num-components", &ncomp);
5711     cmap_array = gst_structure_get_value (structure, "component-map");
5712     cdef_array = gst_structure_get_value (structure, "channel-definitions");
5713
5714     ext_atom = NULL;
5715     entry.fourcc = FOURCC_mjp2;
5716     sync = FALSE;
5717
5718     colorspace = gst_structure_get_string (structure, "colorspace");
5719     if (colorspace &&
5720         (ext_atom =
5721             build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5722                 cdef_array)) != NULL) {
5723       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5724
5725       ext_atom = build_jp2x_extension (codec_data);
5726       if (ext_atom)
5727         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5728     } else {
5729       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5730       goto refuse_caps;
5731     }
5732   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5733     entry.fourcc = FOURCC_vp08;
5734   } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5735     entry.fourcc = FOURCC_vp09;
5736   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5737     entry.fourcc = FOURCC_drac;
5738   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5739     guint32 fourcc = 0;
5740
5741     gst_structure_get_uint (structure, "format", &fourcc);
5742     entry.fourcc = fourcc;
5743   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5744     guint32 fourcc = 0;
5745
5746     gst_structure_get_uint (structure, "format", &fourcc);
5747     entry.fourcc = fourcc;
5748   } else if (strcmp (mimetype, "video/x-prores") == 0) {
5749     const gchar *variant;
5750
5751     variant = gst_structure_get_string (structure, "variant");
5752     if (!variant || !g_strcmp0 (variant, "standard"))
5753       entry.fourcc = FOURCC_apcn;
5754     else if (!g_strcmp0 (variant, "lt"))
5755       entry.fourcc = FOURCC_apcs;
5756     else if (!g_strcmp0 (variant, "hq"))
5757       entry.fourcc = FOURCC_apch;
5758     else if (!g_strcmp0 (variant, "proxy"))
5759       entry.fourcc = FOURCC_apco;
5760     else if (!g_strcmp0 (variant, "4444"))
5761       entry.fourcc = FOURCC_ap4h;
5762     else if (!g_strcmp0 (variant, "4444xq"))
5763       entry.fourcc = FOURCC_ap4x;
5764
5765     sync = FALSE;
5766
5767     if (!qtmux->interleave_time_set)
5768       qtmux->interleave_time = 500 * GST_MSECOND;
5769     if (!qtmux->interleave_bytes_set)
5770       qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5771   } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5772     entry.fourcc = FOURCC_cfhd;
5773     sync = FALSE;
5774   } else if (strcmp (mimetype, "video/x-av1") == 0) {
5775     gint presentation_delay;
5776     guint8 presentation_delay_byte = 0;
5777     GstBuffer *av1_codec_data;
5778
5779     if (gst_structure_get_int (structure, "presentation-delay",
5780             &presentation_delay)) {
5781       presentation_delay_byte = 1 << 5;
5782       presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
5783     }
5784
5785
5786     av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
5787     /* Fill version and 3 bytes of flags to 0 */
5788     gst_buffer_memset (av1_codec_data, 0, 0, 4);
5789     gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
5790     if (codec_data)
5791       av1_codec_data = gst_buffer_append (av1_codec_data,
5792           gst_buffer_ref ((GstBuffer *) codec_data));
5793
5794     entry.fourcc = FOURCC_av01;
5795
5796     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5797     if (ext_atom != NULL)
5798       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5799     ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
5800     if (ext_atom != NULL)
5801       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5802     gst_buffer_unref (av1_codec_data);
5803   }
5804
5805   if (!entry.fourcc)
5806     goto refuse_caps;
5807
5808   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5809       qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5810     const gchar *s;
5811     GstVideoColorimetry colorimetry;
5812
5813     s = gst_structure_get_string (structure, "colorimetry");
5814     if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5815       ext_atom =
5816           build_colr_extension (&colorimetry,
5817           qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5818       if (ext_atom)
5819         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5820     }
5821   }
5822
5823   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5824       || strcmp (mimetype, "image/x-j2c") == 0
5825       || strcmp (mimetype, "image/x-jpc") == 0) {
5826     const gchar *s;
5827     GstVideoInterlaceMode interlace_mode;
5828     GstVideoFieldOrder field_order;
5829     gint fields = -1;
5830
5831     if (strcmp (mimetype, "image/x-j2c") == 0 ||
5832         strcmp (mimetype, "image/x-jpc") == 0) {
5833
5834       fields = 1;
5835       gst_structure_get_int (structure, "fields", &fields);
5836     }
5837
5838     s = gst_structure_get_string (structure, "interlace-mode");
5839     if (s)
5840       interlace_mode = gst_video_interlace_mode_from_string (s);
5841     else
5842       interlace_mode =
5843           (fields <=
5844           1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5845           GST_VIDEO_INTERLACE_MODE_MIXED;
5846
5847     field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5848     if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5849       s = gst_structure_get_string (structure, "field-order");
5850       if (s)
5851         field_order = gst_video_field_order_from_string (s);
5852     }
5853
5854     ext_atom = build_fiel_extension (interlace_mode, field_order);
5855     if (ext_atom)
5856       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5857   }
5858
5859
5860   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5861       width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5862     /* The 'clap' extension is also defined for MP4 but inventing values in
5863      * general seems a bit tricky for this one. We only write it for
5864      * SD resolution in MOV, where it is a requirement.
5865      * The same goes for the 'tapt' extension, just that it is not defined for
5866      * MP4 and only for MOV
5867      */
5868     gint dar_num, dar_den;
5869     gint clef_width, clef_height, prof_width;
5870     gint clap_width_n, clap_width_d, clap_height;
5871     gint cdiv;
5872     double approx_dar;
5873
5874     /* First, guess display aspect ratio based on pixel aspect ratio,
5875      * width and height. We assume that display aspect ratio is either
5876      * 4:3 or 16:9
5877      */
5878     approx_dar = (gdouble) (width * par_num) / (height * par_den);
5879     if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5880       dar_num = 4;
5881       dar_den = 3;
5882     } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5883       dar_num = 16;
5884       dar_den = 9;
5885     } else {
5886       dar_num = width * par_num;
5887       dar_den = height * par_den;
5888       cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5889       dar_num /= cdiv;
5890       dar_den /= cdiv;
5891     }
5892
5893     /* Then, calculate clean-aperture values (clap and clef)
5894      * using the guessed DAR.
5895      */
5896     clef_height = clap_height = (height == 486 ? 480 : height);
5897     clef_width = gst_util_uint64_scale (clef_height,
5898         dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5899     prof_width = gst_util_uint64_scale (width,
5900         par_num * G_GUINT64_CONSTANT (65536), par_den);
5901     clap_width_n = clap_height * dar_num * par_den;
5902     clap_width_d = dar_den * par_num;
5903     cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5904     clap_width_n /= cdiv;
5905     clap_width_d /= cdiv;
5906
5907     ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5908         height << 16, width << 16, height << 16);
5909     qtpad->trak->tapt = ext_atom;
5910
5911     ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5912         clap_height, 1, 0, 1, 0, 1);
5913     if (ext_atom)
5914       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5915   }
5916
5917   /* ok, set the pad info accordingly */
5918   qtpad->fourcc = entry.fourcc;
5919   qtpad->sync = sync;
5920   qtpad->trak_ste =
5921       (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5922       qtmux->context, &entry, rate, ext_atom_list);
5923   if (strcmp (mimetype, "video/x-prores") == 0) {
5924     SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5925     const gchar *compressor = NULL;
5926     mp4v->spatial_quality = 0x3FF;
5927     mp4v->temporal_quality = 0;
5928     mp4v->vendor = FOURCC_appl;
5929     mp4v->horizontal_resolution = 72 << 16;
5930     mp4v->vertical_resolution = 72 << 16;
5931     mp4v->depth = (entry.fourcc == FOURCC_ap4h
5932         || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5933
5934     /* Set compressor name, required by some software */
5935     switch (entry.fourcc) {
5936       case FOURCC_apcn:
5937         compressor = "Apple ProRes 422";
5938         break;
5939       case FOURCC_apcs:
5940         compressor = "Apple ProRes 422 LT";
5941         break;
5942       case FOURCC_apch:
5943         compressor = "Apple ProRes 422 HQ";
5944         break;
5945       case FOURCC_apco:
5946         compressor = "Apple ProRes 422 Proxy";
5947         break;
5948       case FOURCC_ap4h:
5949         compressor = "Apple ProRes 4444";
5950         break;
5951       case FOURCC_ap4x:
5952         compressor = "Apple ProRes 4444 XQ";
5953         break;
5954     }
5955     if (compressor) {
5956       strcpy ((gchar *) mp4v->compressor + 1, compressor);
5957       mp4v->compressor[0] = strlen (compressor);
5958     }
5959   }
5960
5961   gst_object_unref (qtmux);
5962   return TRUE;
5963
5964   /* ERRORS */
5965 refuse_caps:
5966   {
5967     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5968         GST_PAD_NAME (pad), caps);
5969     gst_object_unref (qtmux);
5970     return FALSE;
5971   }
5972 }
5973
5974 static gboolean
5975 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5976 {
5977   GstPad *pad = qtpad->collect.pad;
5978   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5979   GstStructure *structure;
5980   SubtitleSampleEntry entry = { 0, };
5981
5982   if (qtpad->fourcc)
5983     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5984
5985   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5986       GST_DEBUG_PAD_NAME (pad), caps);
5987
5988   /* subtitles default */
5989   subtitle_sample_entry_init (&entry);
5990   qtpad->is_out_of_order = FALSE;
5991   qtpad->sync = FALSE;
5992   qtpad->sparse = TRUE;
5993   qtpad->prepare_buf_func = NULL;
5994
5995   structure = gst_caps_get_structure (caps, 0);
5996
5997   if (gst_structure_has_name (structure, "text/x-raw")) {
5998     const gchar *format = gst_structure_get_string (structure, "format");
5999     if (format && strcmp (format, "utf8") == 0) {
6000       entry.fourcc = FOURCC_tx3g;
6001       qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6002       qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6003     }
6004   }
6005
6006   if (!entry.fourcc)
6007     goto refuse_caps;
6008
6009   qtpad->fourcc = entry.fourcc;
6010   qtpad->trak_ste =
6011       (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6012       qtmux->context, &entry);
6013
6014   gst_object_unref (qtmux);
6015   return TRUE;
6016
6017   /* ERRORS */
6018 refuse_caps:
6019   {
6020     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6021         GST_PAD_NAME (pad), caps);
6022     gst_object_unref (qtmux);
6023     return FALSE;
6024   }
6025 }
6026
6027 static gboolean
6028 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6029 {
6030   GstPad *pad = qtpad->collect.pad;
6031   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6032   GstStructure *structure;
6033   guint32 fourcc_entry;
6034   guint32 timescale;
6035
6036   if (qtpad->fourcc)
6037     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6038
6039   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6040       GST_DEBUG_PAD_NAME (pad), caps);
6041
6042   /* captions default */
6043   qtpad->is_out_of_order = FALSE;
6044   qtpad->sync = FALSE;
6045   qtpad->sparse = TRUE;
6046   /* Closed caption data are within atoms */
6047   qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6048
6049   structure = gst_caps_get_structure (caps, 0);
6050
6051   /* We know we only handle 608,format=cc_data and 708,format=cdp */
6052   if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6053     fourcc_entry = FOURCC_c608;
6054   } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6055     fourcc_entry = FOURCC_c708;
6056   } else
6057     goto refuse_caps;
6058
6059   /* FIXME: Get the timescale from the video track ? */
6060   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6061   if (!timescale && qtmux->trak_timescale)
6062     timescale = qtmux->trak_timescale;
6063   else if (!timescale)
6064     timescale = 30000;
6065
6066   qtpad->fourcc = fourcc_entry;
6067   qtpad->trak_ste =
6068       (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6069       qtmux->context, timescale, fourcc_entry);
6070
6071   gst_object_unref (qtmux);
6072   return TRUE;
6073
6074   /* ERRORS */
6075 refuse_caps:
6076   {
6077     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6078         GST_PAD_NAME (pad), caps);
6079     gst_object_unref (qtmux);
6080     return FALSE;
6081   }
6082 }
6083
6084 static gboolean
6085 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6086     GstEvent * event, gpointer user_data)
6087 {
6088   GstQTMux *qtmux;
6089   guint32 avg_bitrate = 0, max_bitrate = 0;
6090   GstPad *pad = data->pad;
6091   gboolean ret = TRUE;
6092
6093   qtmux = GST_QT_MUX_CAST (user_data);
6094   switch (GST_EVENT_TYPE (event)) {
6095     case GST_EVENT_CAPS:
6096     {
6097       GstCaps *caps;
6098       GstQTPad *collect_pad;
6099
6100       gst_event_parse_caps (event, &caps);
6101
6102       /* find stream data */
6103       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6104       g_assert (collect_pad);
6105       g_assert (collect_pad->set_caps);
6106
6107       ret = collect_pad->set_caps (collect_pad, caps);
6108       gst_event_unref (event);
6109       event = NULL;
6110       break;
6111     }
6112     case GST_EVENT_TAG:{
6113       GstTagList *list;
6114       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6115       GstTagMergeMode mode;
6116       gchar *code;
6117       GstQTPad *collect_pad;
6118
6119       GST_OBJECT_LOCK (qtmux);
6120       mode = gst_tag_setter_get_tag_merge_mode (setter);
6121       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6122
6123       gst_event_parse_tag (event, &list);
6124       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6125           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6126
6127       if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6128         gst_tag_setter_merge_tags (setter, list, mode);
6129         qtmux->tags_changed = TRUE;
6130       } else {
6131         if (!collect_pad->tags)
6132           collect_pad->tags = gst_tag_list_new_empty ();
6133         gst_tag_list_insert (collect_pad->tags, list, mode);
6134         collect_pad->tags_changed = TRUE;
6135       }
6136       GST_OBJECT_UNLOCK (qtmux);
6137
6138       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6139           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6140         GstQTPad *qtpad = gst_pad_get_element_private (pad);
6141         g_assert (qtpad);
6142
6143         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6144           qtpad->avg_bitrate = avg_bitrate;
6145         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6146           qtpad->max_bitrate = max_bitrate;
6147       }
6148
6149       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6150         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6151         if (iso_code) {
6152           GstQTPad *qtpad = gst_pad_get_element_private (pad);
6153           g_assert (qtpad);
6154           if (qtpad->trak) {
6155             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6156             qtpad->trak->mdia.mdhd.language_code =
6157                 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
6158                 (iso_code[2] - 0x60);
6159           }
6160         }
6161         g_free (code);
6162       }
6163
6164       gst_event_unref (event);
6165       event = NULL;
6166       ret = TRUE;
6167       break;
6168     }
6169     default:
6170       break;
6171   }
6172
6173   if (event != NULL)
6174     return gst_collect_pads_event_default (pads, data, event, FALSE);
6175
6176   return ret;
6177 }
6178
6179 static void
6180 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6181 {
6182   GstQTMux *mux = GST_QT_MUX_CAST (element);
6183   GSList *walk;
6184
6185   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6186
6187   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6188     GstQTPad *qtpad = (GstQTPad *) walk->data;
6189     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6190     if (qtpad->collect.pad == pad) {
6191       /* this is it, remove */
6192       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6193       gst_element_remove_pad (element, pad);
6194       break;
6195     }
6196   }
6197
6198   if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6199     mux->current_pad = NULL;
6200     mux->current_chunk_size = 0;
6201     mux->current_chunk_duration = 0;
6202   }
6203
6204   gst_collect_pads_remove_pad (mux->collect, pad);
6205
6206   if (mux->sinkpads == NULL) {
6207     /* No more outstanding request pads, reset our counters */
6208     mux->video_pads = 0;
6209     mux->audio_pads = 0;
6210     mux->subtitle_pads = 0;
6211   }
6212 }
6213
6214 static GstPad *
6215 gst_qt_mux_request_new_pad (GstElement * element,
6216     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6217 {
6218   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6219   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6220   GstQTPad *collect_pad;
6221   GstPad *newpad;
6222   GstQTPadSetCapsFunc setcaps_func;
6223   gchar *name;
6224   gint pad_id;
6225   gboolean lock = TRUE;
6226
6227   if (templ->direction != GST_PAD_SINK)
6228     goto wrong_direction;
6229
6230   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6231     goto too_late;
6232
6233   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6234     setcaps_func = gst_qt_mux_audio_sink_set_caps;
6235     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6236       name = g_strdup (req_name);
6237     } else {
6238       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6239     }
6240   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6241     setcaps_func = gst_qt_mux_video_sink_set_caps;
6242     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6243       name = g_strdup (req_name);
6244     } else {
6245       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6246     }
6247   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6248     setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6249     if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6250       name = g_strdup (req_name);
6251     } else {
6252       name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6253     }
6254     lock = FALSE;
6255   } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6256     setcaps_func = gst_qt_mux_caption_sink_set_caps;
6257     if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6258       name = g_strdup (req_name);
6259     } else {
6260       name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6261     }
6262     lock = FALSE;
6263   } else
6264     goto wrong_template;
6265
6266   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6267
6268   /* create pad and add to collections */
6269   newpad =
6270       g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6271       templ->direction, "template", templ, NULL);
6272   g_free (name);
6273   collect_pad = (GstQTPad *)
6274       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6275       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6276   /* set up pad */
6277   gst_qt_mux_pad_reset (collect_pad);
6278   collect_pad->trak = atom_trak_new (qtmux->context);
6279   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6280
6281   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6282
6283   /* set up pad functions */
6284   collect_pad->set_caps = setcaps_func;
6285
6286   gst_pad_set_active (newpad, TRUE);
6287   gst_element_add_pad (element, newpad);
6288
6289   return newpad;
6290
6291   /* ERRORS */
6292 wrong_direction:
6293   {
6294     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6295     return NULL;
6296   }
6297 too_late:
6298   {
6299     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6300     return NULL;
6301   }
6302 wrong_template:
6303   {
6304     GST_WARNING_OBJECT (qtmux, "This is not our template!");
6305     return NULL;
6306   }
6307 }
6308
6309 static void
6310 gst_qt_mux_get_property (GObject * object,
6311     guint prop_id, GValue * value, GParamSpec * pspec)
6312 {
6313   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6314
6315   GST_OBJECT_LOCK (qtmux);
6316   switch (prop_id) {
6317     case PROP_MOVIE_TIMESCALE:
6318       g_value_set_uint (value, qtmux->timescale);
6319       break;
6320     case PROP_TRAK_TIMESCALE:
6321       g_value_set_uint (value, qtmux->trak_timescale);
6322       break;
6323     case PROP_DO_CTTS:
6324       g_value_set_boolean (value, qtmux->guess_pts);
6325       break;
6326 #ifndef GST_REMOVE_DEPRECATED
6327     case PROP_DTS_METHOD:
6328       g_value_set_enum (value, qtmux->dts_method);
6329       break;
6330 #endif
6331     case PROP_FAST_START:
6332       g_value_set_boolean (value, qtmux->fast_start);
6333       break;
6334     case PROP_FAST_START_TEMP_FILE:
6335       g_value_set_string (value, qtmux->fast_start_file_path);
6336       break;
6337     case PROP_MOOV_RECOV_FILE:
6338       g_value_set_string (value, qtmux->moov_recov_file_path);
6339       break;
6340     case PROP_FRAGMENT_DURATION:
6341       g_value_set_uint (value, qtmux->fragment_duration);
6342       break;
6343     case PROP_STREAMABLE:
6344       g_value_set_boolean (value, qtmux->streamable);
6345       break;
6346     case PROP_RESERVED_MAX_DURATION:
6347       g_value_set_uint64 (value, qtmux->reserved_max_duration);
6348       break;
6349     case PROP_RESERVED_DURATION_REMAINING:
6350       if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6351         g_value_set_uint64 (value, qtmux->reserved_max_duration);
6352       else {
6353         GstClockTime remaining = qtmux->reserved_duration_remaining;
6354
6355         /* Report the remaining space as the calculated remaining, minus
6356          * however much we've muxed since the last update */
6357         if (remaining > qtmux->muxed_since_last_update)
6358           remaining -= qtmux->muxed_since_last_update;
6359         else
6360           remaining = 0;
6361         GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6362             G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6363             remaining, qtmux->reserved_duration_remaining,
6364             qtmux->muxed_since_last_update);
6365         g_value_set_uint64 (value, remaining);
6366       }
6367       break;
6368     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6369       g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6370       break;
6371     case PROP_RESERVED_BYTES_PER_SEC:
6372       g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6373       break;
6374     case PROP_RESERVED_PREFILL:
6375       g_value_set_boolean (value, qtmux->reserved_prefill);
6376       break;
6377     case PROP_INTERLEAVE_BYTES:
6378       g_value_set_uint64 (value, qtmux->interleave_bytes);
6379       break;
6380     case PROP_INTERLEAVE_TIME:
6381       g_value_set_uint64 (value, qtmux->interleave_time);
6382       break;
6383     case PROP_MAX_RAW_AUDIO_DRIFT:
6384       g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6385       break;
6386     default:
6387       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6388       break;
6389   }
6390   GST_OBJECT_UNLOCK (qtmux);
6391 }
6392
6393 static void
6394 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6395 {
6396   gchar *tmp;
6397
6398   g_free (qtmux->fast_start_file_path);
6399   qtmux->fast_start_file_path = NULL;
6400
6401   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6402   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6403   g_free (tmp);
6404 }
6405
6406 static void
6407 gst_qt_mux_set_property (GObject * object,
6408     guint prop_id, const GValue * value, GParamSpec * pspec)
6409 {
6410   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6411
6412   GST_OBJECT_LOCK (qtmux);
6413   switch (prop_id) {
6414     case PROP_MOVIE_TIMESCALE:
6415       qtmux->timescale = g_value_get_uint (value);
6416       break;
6417     case PROP_TRAK_TIMESCALE:
6418       qtmux->trak_timescale = g_value_get_uint (value);
6419       break;
6420     case PROP_DO_CTTS:
6421       qtmux->guess_pts = g_value_get_boolean (value);
6422       break;
6423 #ifndef GST_REMOVE_DEPRECATED
6424     case PROP_DTS_METHOD:
6425       qtmux->dts_method = g_value_get_enum (value);
6426       break;
6427 #endif
6428     case PROP_FAST_START:
6429       qtmux->fast_start = g_value_get_boolean (value);
6430       break;
6431     case PROP_FAST_START_TEMP_FILE:
6432       g_free (qtmux->fast_start_file_path);
6433       qtmux->fast_start_file_path = g_value_dup_string (value);
6434       /* NULL means to generate a random one */
6435       if (!qtmux->fast_start_file_path) {
6436         gst_qt_mux_generate_fast_start_file_path (qtmux);
6437       }
6438       break;
6439     case PROP_MOOV_RECOV_FILE:
6440       g_free (qtmux->moov_recov_file_path);
6441       qtmux->moov_recov_file_path = g_value_dup_string (value);
6442       break;
6443     case PROP_FRAGMENT_DURATION:
6444       qtmux->fragment_duration = g_value_get_uint (value);
6445       break;
6446     case PROP_STREAMABLE:{
6447       GstQTMuxClass *qtmux_klass =
6448           (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6449       if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6450         qtmux->streamable = g_value_get_boolean (value);
6451       }
6452       break;
6453     }
6454     case PROP_RESERVED_MAX_DURATION:
6455       qtmux->reserved_max_duration = g_value_get_uint64 (value);
6456       break;
6457     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6458       qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6459       break;
6460     case PROP_RESERVED_BYTES_PER_SEC:
6461       qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6462       break;
6463     case PROP_RESERVED_PREFILL:
6464       qtmux->reserved_prefill = g_value_get_boolean (value);
6465       break;
6466     case PROP_INTERLEAVE_BYTES:
6467       qtmux->interleave_bytes = g_value_get_uint64 (value);
6468       qtmux->interleave_bytes_set = TRUE;
6469       break;
6470     case PROP_INTERLEAVE_TIME:
6471       qtmux->interleave_time = g_value_get_uint64 (value);
6472       qtmux->interleave_time_set = TRUE;
6473       break;
6474     case PROP_MAX_RAW_AUDIO_DRIFT:
6475       qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6476       break;
6477     default:
6478       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6479       break;
6480   }
6481   GST_OBJECT_UNLOCK (qtmux);
6482 }
6483
6484 static GstStateChangeReturn
6485 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6486 {
6487   GstStateChangeReturn ret;
6488   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6489
6490   switch (transition) {
6491     case GST_STATE_CHANGE_NULL_TO_READY:
6492       break;
6493     case GST_STATE_CHANGE_READY_TO_PAUSED:
6494       gst_collect_pads_start (qtmux->collect);
6495       qtmux->state = GST_QT_MUX_STATE_STARTED;
6496       break;
6497     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6498       break;
6499     case GST_STATE_CHANGE_PAUSED_TO_READY:
6500       gst_collect_pads_stop (qtmux->collect);
6501       break;
6502     default:
6503       break;
6504   }
6505
6506   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6507
6508   switch (transition) {
6509     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6510       break;
6511     case GST_STATE_CHANGE_PAUSED_TO_READY:
6512       gst_qt_mux_reset (qtmux, TRUE);
6513       break;
6514     case GST_STATE_CHANGE_READY_TO_NULL:
6515       break;
6516     default:
6517       break;
6518   }
6519
6520   return ret;
6521 }
6522
6523 gboolean
6524 gst_qt_mux_register (GstPlugin * plugin)
6525 {
6526   GTypeInfo typeinfo = {
6527     sizeof (GstQTMuxClass),
6528     (GBaseInitFunc) gst_qt_mux_base_init,
6529     NULL,
6530     (GClassInitFunc) gst_qt_mux_class_init,
6531     NULL,
6532     NULL,
6533     sizeof (GstQTMux),
6534     0,
6535     (GInstanceInitFunc) gst_qt_mux_init,
6536   };
6537   static const GInterfaceInfo tag_setter_info = {
6538     NULL, NULL, NULL
6539   };
6540   static const GInterfaceInfo tag_xmp_writer_info = {
6541     NULL, NULL, NULL
6542   };
6543   static const GInterfaceInfo preset_info = {
6544     NULL, NULL, NULL
6545   };
6546   GType type;
6547   GstQTMuxFormat format;
6548   GstQTMuxClassParams *params;
6549   guint i = 0;
6550
6551   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6552
6553   GST_LOG ("Registering muxers");
6554
6555   while (TRUE) {
6556     GstQTMuxFormatProp *prop;
6557     GstCaps *subtitle_caps, *caption_caps;
6558
6559     prop = &gst_qt_mux_format_list[i];
6560     format = prop->format;
6561     if (format == GST_QT_MUX_FORMAT_NONE)
6562       break;
6563
6564     /* create a cache for these properties */
6565     params = g_new0 (GstQTMuxClassParams, 1);
6566     params->prop = prop;
6567     params->src_caps = gst_static_caps_get (&prop->src_caps);
6568     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6569     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6570     subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6571     if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6572       params->subtitle_sink_caps = subtitle_caps;
6573     } else {
6574       gst_caps_unref (subtitle_caps);
6575     }
6576     caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6577     if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6578       params->caption_sink_caps = caption_caps;
6579     } else {
6580       gst_caps_unref (caption_caps);
6581     }
6582
6583     /* create the type now */
6584     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6585         0);
6586     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6587     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6588     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6589         &tag_xmp_writer_info);
6590     g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6591
6592     if (!gst_element_register (plugin, prop->name, prop->rank, type))
6593       return FALSE;
6594
6595     i++;
6596   }
6597
6598   GST_LOG ("Finished registering muxers");
6599
6600   /* FIXME: ideally classification tag should be added and
6601      registered in gstreamer core gsttaglist
6602    */
6603
6604   GST_LOG ("Registering tags");
6605
6606   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6607       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6608       gst_tag_merge_use_first);
6609
6610   GST_LOG ("Finished registering tags");
6611
6612   return TRUE;
6613 }