qtdemux: Avoid warning when reporting about decryptors
[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   /* Set width/height of any closed caption tracks to that of the first
3037    * video track */
3038   {
3039     guint video_width = 0, video_height = 0;
3040     GSList *walk;
3041
3042     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3043       GstCollectData *cdata = (GstCollectData *) walk->data;
3044       GstQTPad *qpad = (GstQTPad *) cdata;
3045
3046       if (!qpad->trak)
3047         continue;
3048
3049       /* Not closed caption */
3050       if (qpad->trak->mdia.hdlr.handler_type != FOURCC_clcp)
3051         continue;
3052
3053       if (video_width == 0 || video_height == 0) {
3054         GSList *walk2;
3055
3056         for (walk2 = qtmux->sinkpads; walk2; walk2 = g_slist_next (walk2)) {
3057           GstCollectData *cdata2 = (GstCollectData *) walk2->data;
3058           GstQTPad *qpad2 = (GstQTPad *) cdata2;
3059
3060           if (!qpad2->trak)
3061             continue;
3062
3063           /* not video */
3064           if (!qpad2->trak->mdia.minf.vmhd)
3065             continue;
3066
3067           video_width = qpad2->trak->tkhd.width;
3068           video_height = qpad2->trak->tkhd.height;
3069         }
3070       }
3071
3072       qpad->trak->tkhd.width = video_width << 16;
3073       qpad->trak->tkhd.height = video_height << 16;
3074     }
3075   }
3076
3077   /* initialize our moov recovery file */
3078   if (qtmux->moov_recov_file_path) {
3079     gst_qt_mux_prepare_moov_recovery (qtmux);
3080   }
3081
3082   /* Make sure the first time we update the moov, we'll
3083    * include any tagsetter tags */
3084   qtmux->tags_changed = TRUE;
3085
3086   GST_OBJECT_UNLOCK (qtmux);
3087
3088   /*
3089    * send mdat header if already needed, and mark position for later update.
3090    * We don't send ftyp now if we are on fast start mode, because we can
3091    * better fine tune using the information we gather to create the whole moov
3092    * atom.
3093    */
3094   switch (qtmux->mux_mode) {
3095     case GST_QT_MUX_MODE_MOOV_AT_END:
3096       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3097       if (ret != GST_FLOW_OK)
3098         break;
3099
3100       /* Store this as the mdat offset for later updating
3101        * when we write the moov */
3102       qtmux->mdat_pos = qtmux->header_size;
3103       /* extended atom in case we go over 4GB while writing and need
3104        * the full 64-bit atom */
3105       ret =
3106           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3107           FALSE);
3108       break;
3109     case GST_QT_MUX_MODE_ROBUST_RECORDING:
3110       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3111       if (ret != GST_FLOW_OK)
3112         break;
3113
3114       /* Pad ftyp out to an 8-byte boundary before starting the moov
3115        * ping pong region. It should be well less than 1 disk sector,
3116        * unless there's a bajillion compatible types listed,
3117        * but let's be sure the free atom doesn't cross a sector
3118        * boundary anyway */
3119       if (qtmux->header_size % 8) {
3120         /* Extra 8 bytes for the padding free atom header */
3121         guint padding = (guint) (16 - (qtmux->header_size % 8));
3122         GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3123         ret =
3124             gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3125             FALSE);
3126         if (ret != GST_FLOW_OK)
3127           return ret;
3128       }
3129
3130       /* Store this as the moov offset for later updating.
3131        * We record mdat position below */
3132       qtmux->moov_pos = qtmux->header_size;
3133
3134       /* Set up the initial 'ping' state of the ping-pong buffers */
3135       qtmux->reserved_moov_first_active = TRUE;
3136
3137       gst_qt_mux_configure_moov (qtmux);
3138       gst_qt_mux_setup_metadata (qtmux);
3139       /* Empty free atom to begin, starting on an 8-byte boundary */
3140       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3141       if (ret != GST_FLOW_OK)
3142         return ret;
3143       /* Moov header, not padded yet */
3144       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3145       if (ret != GST_FLOW_OK)
3146         return ret;
3147       /* The moov we just sent contains the 'base' size of the moov, before
3148        * we put in any time-dependent per-trak data. Use that to make
3149        * a good estimate of how much extra to reserve */
3150       /* Calculate how much space to reserve for our MOOV atom.
3151        * We actually reserve twice that, for ping-pong buffers */
3152       qtmux->base_moov_size = qtmux->last_moov_size;
3153       GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3154           qtmux->base_moov_size);
3155       qtmux->reserved_moov_size = qtmux->base_moov_size +
3156           gst_util_uint64_scale (reserved_max_duration,
3157           reserved_bytes_per_sec_per_trak *
3158           atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3159
3160       /* Need space for at least 4 atom headers. More really, but
3161        * this as an absolute minimum */
3162       if (qtmux->reserved_moov_size < 4 * 8)
3163         goto reserved_moov_too_small;
3164
3165       GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3166           2 * qtmux->reserved_moov_size + 16);
3167
3168       GST_OBJECT_LOCK (qtmux);
3169       qtmux->reserved_duration_remaining =
3170           gst_util_uint64_scale (qtmux->reserved_moov_size -
3171           qtmux->base_moov_size, GST_SECOND,
3172           reserved_bytes_per_sec_per_trak *
3173           atom_moov_get_trak_count (qtmux->moov));
3174       GST_OBJECT_UNLOCK (qtmux);
3175
3176       /* Now that we know how much reserved space is targetted,
3177        * output a free atom to fill the extra reserved */
3178       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3179           qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3180       if (ret != GST_FLOW_OK)
3181         return ret;
3182
3183       /* Then a free atom containing 'pong' buffer, with an
3184        * extra 8 bytes to account for the free atom header itself */
3185       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3186           qtmux->reserved_moov_size + 8, FALSE);
3187       if (ret != GST_FLOW_OK)
3188         return ret;
3189
3190       /* extra atoms go after the free/moov(s), before the mdat */
3191       ret =
3192           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3193       if (ret != GST_FLOW_OK)
3194         return ret;
3195
3196       qtmux->mdat_pos = qtmux->header_size;
3197       /* extended atom in case we go over 4GB while writing and need
3198        * the full 64-bit atom */
3199       ret =
3200           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3201           FALSE);
3202       break;
3203     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3204       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3205       if (ret != GST_FLOW_OK)
3206         break;
3207
3208       /* Store this as the moov offset for later updating.
3209        * We record mdat position below */
3210       qtmux->moov_pos = qtmux->header_size;
3211
3212       if (!gst_qt_mux_prefill_samples (qtmux)) {
3213         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3214             ("Unsupported codecs or configuration for prefill mode"), (NULL));
3215
3216         return GST_FLOW_ERROR;
3217       }
3218
3219       gst_qt_mux_update_global_statistics (qtmux);
3220       gst_qt_mux_configure_moov (qtmux);
3221       gst_qt_mux_update_edit_lists (qtmux);
3222       gst_qt_mux_setup_metadata (qtmux);
3223
3224       /* Moov header with pre-filled samples */
3225       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3226       if (ret != GST_FLOW_OK)
3227         return ret;
3228
3229       /* last_moov_size now contains the full size of the moov, moov_pos the
3230        * position. This allows us to rewrite it in the very end as needed */
3231       qtmux->reserved_moov_size =
3232           qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3233
3234       /* Send an additional free atom at the end so we definitely have space
3235        * to rewrite the moov header at the end and remove the samples that
3236        * were not actually written */
3237       ret =
3238           gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3239           12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3240       if (ret != GST_FLOW_OK)
3241         return ret;
3242
3243       /* extra atoms go after the free/moov(s), before the mdat */
3244       ret =
3245           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3246       if (ret != GST_FLOW_OK)
3247         return ret;
3248
3249       qtmux->mdat_pos = qtmux->header_size;
3250
3251       /* And now send the mdat header */
3252       ret =
3253           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3254           qtmux->mdat_size, TRUE, FALSE);
3255
3256       /* chunks position is set relative to the first byte of the
3257        * MDAT atom payload. Set the overall offset into the file */
3258       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3259
3260       {
3261         GstSegment segment;
3262
3263         gst_segment_init (&segment, GST_FORMAT_BYTES);
3264         segment.start = qtmux->moov_pos;
3265         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3266
3267         ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3268         if (ret != GST_FLOW_OK)
3269           return ret;
3270
3271         segment.start = qtmux->header_size;
3272         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3273       }
3274
3275       qtmux->current_chunk_size = 0;
3276       qtmux->current_chunk_duration = 0;
3277       qtmux->current_chunk_offset = -1;
3278       qtmux->mdat_size = 0;
3279       qtmux->current_pad = NULL;
3280       qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3281
3282       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3283         GstCollectData *cdata = (GstCollectData *) walk->data;
3284         GstQTPad *qtpad = (GstQTPad *) cdata;
3285
3286         qtpad->total_bytes = 0;
3287         qtpad->total_duration = 0;
3288         qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3289         qtpad->last_dts = GST_CLOCK_TIME_NONE;
3290         qtpad->sample_offset = 0;
3291       }
3292
3293       break;
3294     case GST_QT_MUX_MODE_FAST_START:
3295       GST_OBJECT_LOCK (qtmux);
3296       qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3297       if (!qtmux->fast_start_file)
3298         goto open_failed;
3299       GST_OBJECT_UNLOCK (qtmux);
3300       /* send a dummy buffer for preroll */
3301       ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3302       break;
3303     case GST_QT_MUX_MODE_FRAGMENTED:
3304     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3305       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3306       if (ret != GST_FLOW_OK)
3307         break;
3308       /* store the moov pos so we can update the duration later
3309        * in non-streamable mode */
3310       qtmux->moov_pos = qtmux->header_size;
3311
3312       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3313           qtmux->fragment_duration);
3314       /* also used as snapshot marker to indicate fragmented file */
3315       qtmux->fragment_sequence = 1;
3316       /* prepare moov and/or tags */
3317       gst_qt_mux_configure_moov (qtmux);
3318       gst_qt_mux_setup_metadata (qtmux);
3319       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3320       if (ret != GST_FLOW_OK)
3321         return ret;
3322       /* extra atoms */
3323       ret =
3324           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3325       if (ret != GST_FLOW_OK)
3326         break;
3327       /* prepare index if not streamable */
3328       if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3329         qtmux->mfra = atom_mfra_new (qtmux->context);
3330       break;
3331   }
3332
3333   return ret;
3334   /* ERRORS */
3335 invalid_isml:
3336   {
3337     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3338         ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3339     return GST_FLOW_ERROR;
3340   }
3341 reserved_moov_too_small:
3342   {
3343     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3344         ("Not enough reserved space for creating headers"), (NULL));
3345     return GST_FLOW_ERROR;
3346   }
3347 open_failed:
3348   {
3349     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3350         (("Could not open temporary file \"%s\""),
3351             qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3352     GST_OBJECT_UNLOCK (qtmux);
3353     return GST_FLOW_ERROR;
3354   }
3355 }
3356
3357 static GstFlowReturn
3358 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3359 {
3360   GstFlowReturn ret = GST_FLOW_OK;
3361   GSList *walk;
3362
3363   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3364     GstCollectData *cdata = (GstCollectData *) walk->data;
3365     GstQTPad *qtpad = (GstQTPad *) cdata;
3366
3367     /* avoid add_buffer complaining if not negotiated
3368      * in which case no buffers either, so skipping */
3369     if (!qtpad->fourcc) {
3370       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3371           GST_PAD_NAME (qtpad->collect.pad));
3372       continue;
3373     }
3374
3375     /* send last buffer; also flushes possibly queued buffers/ts */
3376     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3377         GST_PAD_NAME (qtpad->collect.pad));
3378     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3379     if (ret != GST_FLOW_OK) {
3380       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3381           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3382           gst_flow_get_name (ret));
3383     }
3384   }
3385
3386   return ret;
3387 }
3388
3389 static void
3390 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3391 {
3392   GSList *walk;
3393
3394   /* for setting some subtitles fields */
3395   guint max_width = 0;
3396   guint max_height = 0;
3397
3398   qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3399
3400   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3401     GstCollectData *cdata = (GstCollectData *) walk->data;
3402     GstQTPad *qtpad = (GstQTPad *) cdata;
3403
3404     if (!qtpad->fourcc) {
3405       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3406           GST_PAD_NAME (qtpad->collect.pad));
3407       continue;
3408     }
3409
3410     /* having flushed above, can check for buffers now */
3411     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3412       GstClockTime first_pts_in = qtpad->first_ts;
3413       /* it should be, since we got first_ts by adding adjustment
3414        * to a positive incoming PTS */
3415       if (qtpad->dts_adjustment <= first_pts_in)
3416         first_pts_in -= qtpad->dts_adjustment;
3417       /* determine max stream duration */
3418       if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3419           || qtpad->last_dts > qtmux->last_dts) {
3420         qtmux->last_dts = qtpad->last_dts;
3421       }
3422       if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3423           || first_pts_in < qtmux->first_ts) {
3424         /* we need the original incoming PTS here, as this first_ts
3425          * is used in update_edit_lists to construct the edit list that arrange
3426          * for sync'ed streams.  The first_ts is most likely obtained from
3427          * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3428          * so it makes no difference, though it matters in other cases */
3429         qtmux->first_ts = first_pts_in;
3430       }
3431     }
3432
3433     /* subtitles need to know the video width/height,
3434      * it is stored shifted 16 bits to the left according to the
3435      * spec */
3436     max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3437     max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3438
3439     /* update average bitrate of streams if needed */
3440     {
3441       guint32 avgbitrate = 0;
3442       guint32 maxbitrate = qtpad->max_bitrate;
3443
3444       if (qtpad->avg_bitrate)
3445         avgbitrate = qtpad->avg_bitrate;
3446       else if (qtpad->total_duration > 0)
3447         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3448             8 * GST_SECOND, qtpad->total_duration);
3449
3450       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3451     }
3452   }
3453
3454   /* need to update values on subtitle traks now that we know the
3455    * max width and height */
3456   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3457     GstCollectData *cdata = (GstCollectData *) walk->data;
3458     GstQTPad *qtpad = (GstQTPad *) cdata;
3459
3460     if (!qtpad->fourcc) {
3461       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3462           GST_PAD_NAME (qtpad->collect.pad));
3463       continue;
3464     }
3465
3466     if (qtpad->fourcc == FOURCC_tx3g) {
3467       atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3468     }
3469   }
3470 }
3471
3472 /* Called after gst_qt_mux_update_global_statistics() updates the
3473  * first_ts tracking, to create/set edit lists for delayed streams */
3474 static void
3475 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3476 {
3477   GSList *walk;
3478
3479   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3480       GST_TIME_ARGS (qtmux->first_ts));
3481   /* add/update EDTSs for late streams. configure_moov will have
3482    * set the trak durations above by summing the sample tables,
3483    * here we extend that if needing to insert an empty segment */
3484   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3485     GstCollectData *cdata = (GstCollectData *) walk->data;
3486     GstQTPad *qtpad = (GstQTPad *) cdata;
3487
3488     atom_trak_edts_clear (qtpad->trak);
3489
3490     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3491       guint32 lateness = 0;
3492       guint32 duration = qtpad->trak->tkhd.duration;
3493       gboolean has_gap;
3494
3495       has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3496
3497       if (has_gap) {
3498         GstClockTime diff, trak_lateness, one_percent_of_frame_duration = 0;
3499
3500         diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3501         lateness = gst_util_uint64_scale_round (diff,
3502             qtmux->timescale, GST_SECOND);
3503         /* Allow up to 1 trak timescale unit of lateness, Such a small
3504          * timestamp/duration can't be represented by the trak-specific parts
3505          * of the headers anyway, so it's irrelevantly small */
3506         trak_lateness = gst_util_uint64_scale (diff,
3507             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3508
3509         /* If the lateness is less than 1% of the (video) frame duration, we
3510          * just allow it. It's usually irrelevantly small anyway, and having
3511          * such a short edit list of -1 might break other cases (e.g. in
3512          * prefill mode it will just error out for no real reason) */
3513         if (qtpad->expected_sample_duration_n != 0) {
3514           one_percent_of_frame_duration =
3515               gst_util_uint64_scale (qtpad->expected_sample_duration_d,
3516               GST_SECOND, 100 * qtpad->expected_sample_duration_n);
3517         }
3518
3519         if (lateness > one_percent_of_frame_duration && trak_lateness > 0) {
3520           GST_DEBUG_OBJECT (qtmux,
3521               "Pad %s is a late stream by %" GST_TIME_FORMAT,
3522               GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3523
3524           atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3525               (guint32) (1 * 65536.0));
3526         }
3527       }
3528
3529       /* Always write an edit list for the whole track. In general this is not
3530        * necessary except for the case of having a gap or DTS adjustment but
3531        * it allows to give the whole track's duration in the usually more
3532        * accurate media timescale
3533        */
3534       {
3535         GstClockTime ctts = 0;
3536         guint32 media_start;
3537
3538         if (qtpad->first_ts > qtpad->first_dts)
3539           ctts = qtpad->first_ts - qtpad->first_dts;
3540
3541         media_start = gst_util_uint64_scale_round (ctts,
3542             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3543
3544         /* atom_trak_set_elst_entry() has a quirk - if the edit list
3545          * is empty because there's no gap added above, this call
3546          * will not replace index 1, it will create the entry at index 0.
3547          * Luckily, that's exactly what we want here */
3548         atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3549             (guint32) (1 * 65536.0));
3550       }
3551
3552       /* need to add the empty time to the trak duration */
3553       duration += lateness;
3554       qtpad->trak->tkhd.duration = duration;
3555       if (qtpad->tc_trak) {
3556         qtpad->tc_trak->tkhd.duration = duration;
3557         qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3558       }
3559
3560       /* And possibly grow the moov duration */
3561       if (duration > qtmux->moov->mvhd.time_info.duration) {
3562         qtmux->moov->mvhd.time_info.duration = duration;
3563         qtmux->moov->mvex.mehd.fragment_duration = duration;
3564       }
3565     }
3566   }
3567 }
3568
3569 static GstFlowReturn
3570 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3571 {
3572   GstSegment segment;
3573   GstBuffer *buf;
3574   GstMapInfo map;
3575   guint64 offset = qtpad->tc_pos;
3576   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3577
3578   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3579     return GST_FLOW_OK;
3580
3581   g_assert (qtpad->tc_pos != -1);
3582
3583   gst_segment_init (&segment, GST_FORMAT_BYTES);
3584   segment.start = offset;
3585   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3586
3587   buf = gst_buffer_new_and_alloc (4);
3588   gst_buffer_map (buf, &map, GST_MAP_WRITE);
3589
3590   GST_WRITE_UINT32_BE (map.data,
3591       gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3592   gst_buffer_unmap (buf, &map);
3593
3594   /* Reset this value, so the timecode won't be re-rewritten */
3595   qtpad->tc_pos = -1;
3596
3597   return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3598 }
3599
3600 static GstFlowReturn
3601 gst_qt_mux_stop_file (GstQTMux * qtmux)
3602 {
3603   gboolean ret = GST_FLOW_OK;
3604   guint64 offset = 0, size = 0;
3605   gboolean large_file;
3606   GSList *walk;
3607
3608   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3609
3610   /* pushing last buffers for each pad */
3611   if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3612     return ret;
3613
3614   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3615     /* Streamable mode; no need to write duration or MFRA */
3616     GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3617     return GST_FLOW_OK;
3618   }
3619
3620   gst_qt_mux_update_global_statistics (qtmux);
3621   for (walk = qtmux->collect->data; walk; walk = walk->next) {
3622     GstQTPad *qtpad = (GstQTPad *) walk->data;
3623
3624     if (qtpad->tc_pos != -1) {
3625       /* File is being stopped and timecode hasn't been updated. Update it now
3626        * with whatever we have */
3627       ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3628       if (ret != GST_FLOW_OK)
3629         return ret;
3630     }
3631   }
3632
3633   switch (qtmux->mux_mode) {
3634     case GST_QT_MUX_MODE_FRAGMENTED:{
3635       GstSegment segment;
3636       guint8 *data = NULL;
3637       GstBuffer *buf;
3638
3639       size = offset = 0;
3640       GST_DEBUG_OBJECT (qtmux, "adding mfra");
3641       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3642         goto serialize_error;
3643       buf = _gst_buffer_new_take_data (data, offset);
3644       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3645       if (ret != GST_FLOW_OK)
3646         return ret;
3647
3648       /* only mvex duration is updated,
3649        * mvhd should be consistent with empty moov
3650        * (but TODO maybe some clients do not handle that well ?) */
3651       qtmux->moov->mvex.mehd.fragment_duration =
3652           gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3653       GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3654           GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3655       /* seek and rewrite the header */
3656       gst_segment_init (&segment, GST_FORMAT_BYTES);
3657       segment.start = qtmux->moov_pos;
3658       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3659       /* no need to seek back */
3660       return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3661     }
3662     case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3663       ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3664       if (G_UNLIKELY (ret != GST_FLOW_OK))
3665         return ret;
3666       /* Finalise by writing the final size into the mdat. Up until now
3667        * it's been 0, which means 'rest of the file'
3668        * No need to seek back after this, we won't write any more */
3669       return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3670           qtmux->mdat_size, NULL, TRUE);
3671     }
3672     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3673       GSList *walk;
3674       guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3675
3676       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3677         GstCollectData *cdata = (GstCollectData *) walk->data;
3678         GstQTPad *qpad = (GstQTPad *) cdata;
3679         guint64 block_idx;
3680         AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3681
3682         /* Get the block index of the last sample we wrote, not of the next
3683          * sample we would write */
3684         block_idx = prefill_get_block_index (qtmux, qpad);
3685
3686         /* stts */
3687         if (block_idx > 0) {
3688           STTSEntry *entry;
3689           guint64 nsamples = 0;
3690           gint i, n;
3691
3692           n = atom_array_get_len (&stbl->stts.entries);
3693           for (i = 0; i < n; i++) {
3694             entry = &atom_array_index (&stbl->stts.entries, i);
3695             if (nsamples + entry->sample_count >= qpad->sample_offset) {
3696               entry->sample_count = qpad->sample_offset - nsamples;
3697               stbl->stts.entries.len = i + 1;
3698               break;
3699             }
3700             nsamples += entry->sample_count;
3701           }
3702           g_assert (i < n);
3703         } else {
3704           stbl->stts.entries.len = 0;
3705         }
3706
3707         /* stsz */
3708         {
3709           g_assert (stbl->stsz.entries.len == 0);
3710           stbl->stsz.table_size = qpad->sample_offset;
3711         }
3712
3713         /* stco/stsc */
3714         {
3715           gint i, n;
3716           guint64 nsamples = 0;
3717           gint chunk_index = 0;
3718           const TrakBufferEntryInfo *sample_entry;
3719
3720           if (block_idx > 0) {
3721             sample_entry =
3722                 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3723                 block_idx - 1);
3724
3725             n = stbl->stco64.entries.len;
3726             for (i = 0; i < n; i++) {
3727               guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3728
3729               if (*entry == sample_entry->chunk_offset) {
3730                 stbl->stco64.entries.len = i + 1;
3731                 chunk_index = i + 1;
3732                 break;
3733               }
3734             }
3735             g_assert (i < n);
3736             g_assert (chunk_index > 0);
3737
3738             n = stbl->stsc.entries.len;
3739             for (i = 0; i < n; i++) {
3740               STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3741
3742               if (entry->first_chunk >= chunk_index)
3743                 break;
3744
3745               if (i > 0) {
3746                 nsamples +=
3747                     (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3748                         i -
3749                         1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3750                     i - 1).samples_per_chunk;
3751               }
3752             }
3753             g_assert (i <= n);
3754
3755             if (i > 0) {
3756               STSCEntry *prev_entry =
3757                   &atom_array_index (&stbl->stsc.entries, i - 1);
3758               nsamples +=
3759                   (chunk_index -
3760                   prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3761               if (qpad->sample_offset - nsamples > 0) {
3762                 stbl->stsc.entries.len = i;
3763                 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3764                     qpad->sample_offset - nsamples);
3765               } else {
3766                 stbl->stsc.entries.len = i;
3767                 stbl->stco64.entries.len--;
3768               }
3769             } else {
3770               /* Everything in a single chunk */
3771               stbl->stsc.entries.len = 0;
3772               atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3773                   qpad->sample_offset);
3774             }
3775           } else {
3776             stbl->stco64.entries.len = 0;
3777             stbl->stsc.entries.len = 0;
3778           }
3779         }
3780
3781         {
3782           GList *walk2;
3783
3784           for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3785             AtomTREX *trex = walk2->data;
3786
3787             if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3788               trex->track_ID = next_track_id;
3789               break;
3790             }
3791           }
3792
3793           qpad->trak->tkhd.track_ID = next_track_id++;
3794         }
3795       }
3796       qtmux->moov->mvhd.next_track_id = next_track_id;
3797
3798       gst_qt_mux_update_global_statistics (qtmux);
3799       gst_qt_mux_configure_moov (qtmux);
3800
3801       gst_qt_mux_update_edit_lists (qtmux);
3802
3803       /* Check if any gap edit lists were added. We don't have any space
3804        * reserved for this in the moov and the pre-finalized moov would have
3805        * broken A/V synchronization. Error out here now
3806        */
3807       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3808         GstCollectData *cdata = (GstCollectData *) walk->data;
3809         GstQTPad *qpad = (GstQTPad *) cdata;
3810
3811         if (qpad->trak->edts
3812             && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3813           GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3814               ("Can't support gaps in prefill mode"));
3815
3816           return GST_FLOW_ERROR;
3817         }
3818       }
3819
3820       gst_qt_mux_setup_metadata (qtmux);
3821       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3822
3823       {
3824         GstSegment segment;
3825
3826         gst_segment_init (&segment, GST_FORMAT_BYTES);
3827         segment.start = qtmux->moov_pos;
3828         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3829
3830         ret =
3831             gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3832             FALSE);
3833         if (ret != GST_FLOW_OK)
3834           return ret;
3835
3836         if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3837           ret =
3838               gst_qt_mux_send_free_atom (qtmux, NULL,
3839               qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3840         }
3841
3842         if (ret != GST_FLOW_OK)
3843           return ret;
3844       }
3845
3846       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3847           qtmux->mdat_size, NULL, FALSE);
3848       return ret;
3849     }
3850     default:
3851       break;
3852   }
3853
3854   /* Moov-at-end or fast-start mode from here down */
3855   gst_qt_mux_configure_moov (qtmux);
3856
3857   gst_qt_mux_update_edit_lists (qtmux);
3858
3859   /* tags into file metadata */
3860   gst_qt_mux_setup_metadata (qtmux);
3861
3862   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3863
3864   switch (qtmux->mux_mode) {
3865     case GST_QT_MUX_MODE_FAST_START:{
3866       /* if faststart, update the offset of the atoms in the movie with the offset
3867        * that the movie headers before mdat will cause.
3868        * Also, send the ftyp */
3869       offset = size = 0;
3870
3871       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3872       if (ret != GST_FLOW_OK) {
3873         goto ftyp_error;
3874       }
3875       /* copy into NULL to obtain size */
3876       if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3877         goto serialize_error;
3878       GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3879           offset);
3880       offset += qtmux->header_size + (large_file ? 16 : 8);
3881
3882       /* sum up with the extra atoms size */
3883       ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3884       if (ret != GST_FLOW_OK)
3885         return ret;
3886       break;
3887     }
3888     default:
3889       offset = qtmux->header_size;
3890       break;
3891   }
3892
3893   /* Now that we know the size of moov + extra atoms, we can adjust
3894    * the chunk offsets stored into the moov */
3895   atom_moov_chunks_set_offset (qtmux->moov, offset);
3896
3897   /* write out moov and extra atoms */
3898   /* note: as of this point, we no longer care about tracking written data size,
3899    * since there is no more use for it anyway */
3900   ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3901   if (ret != GST_FLOW_OK)
3902     return ret;
3903
3904   /* extra atoms */
3905   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3906   if (ret != GST_FLOW_OK)
3907     return ret;
3908
3909   switch (qtmux->mux_mode) {
3910     case GST_QT_MUX_MODE_MOOV_AT_END:
3911     {
3912       /* mdat needs update iff not using faststart */
3913       GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3914       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3915           qtmux->mdat_size, NULL, FALSE);
3916       /* note; no seeking back to the end of file is done,
3917        * since we no longer write anything anyway */
3918       break;
3919     }
3920     case GST_QT_MUX_MODE_FAST_START:
3921     {
3922       /* send mdat atom and move buffered data into it */
3923       /* mdat_size = accumulated (buffered data) */
3924       ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3925           large_file, FALSE);
3926       if (ret != GST_FLOW_OK)
3927         return ret;
3928       ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3929       if (ret != GST_FLOW_OK)
3930         return ret;
3931       break;
3932     }
3933     default:
3934       g_assert_not_reached ();
3935   }
3936
3937   return ret;
3938
3939   /* ERRORS */
3940 serialize_error:
3941   {
3942     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3943         ("Failed to serialize moov"));
3944     return GST_FLOW_ERROR;
3945   }
3946 ftyp_error:
3947   {
3948     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3949     return GST_FLOW_ERROR;
3950   }
3951 }
3952
3953 static GstFlowReturn
3954 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3955     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3956     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3957 {
3958   GstFlowReturn ret = GST_FLOW_OK;
3959
3960   /* setup if needed */
3961   if (G_UNLIKELY (!pad->traf || force))
3962     goto init;
3963
3964 flush:
3965   /* flush pad fragment if threshold reached,
3966    * or at new keyframe if we should be minding those in the first place */
3967   if (G_UNLIKELY (force || (sync && pad->sync) ||
3968           pad->fragment_duration < (gint64) delta)) {
3969     AtomMOOF *moof;
3970     guint64 size = 0, offset = 0;
3971     guint8 *data = NULL;
3972     GstBuffer *buffer;
3973     guint i, total_size;
3974
3975     /* now we know where moof ends up, update offset in tfra */
3976     if (pad->tfra)
3977       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3978
3979     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3980     /* takes ownership */
3981     atom_moof_add_traf (moof, pad->traf);
3982     pad->traf = NULL;
3983     atom_moof_copy_data (moof, &data, &size, &offset);
3984     buffer = _gst_buffer_new_take_data (data, offset);
3985     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3986         gst_buffer_get_size (buffer));
3987     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3988
3989     /* and actual data */
3990     total_size = 0;
3991     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3992       total_size +=
3993           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3994     }
3995
3996     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3997         atom_array_get_len (&pad->fragment_buffers), total_size);
3998     if (ret == GST_FLOW_OK)
3999       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
4000           FALSE, FALSE);
4001     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4002       if (G_LIKELY (ret == GST_FLOW_OK))
4003         ret = gst_qt_mux_send_buffer (qtmux,
4004             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
4005             FALSE);
4006       else
4007         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4008     }
4009
4010     atom_array_clear (&pad->fragment_buffers);
4011     atom_moof_free (moof);
4012     qtmux->fragment_sequence++;
4013     force = FALSE;
4014   }
4015
4016 init:
4017   if (G_UNLIKELY (!pad->traf)) {
4018     GST_LOG_OBJECT (qtmux, "setting up new fragment");
4019     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4020     atom_array_init (&pad->fragment_buffers, 512);
4021     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4022         atom_trak_get_timescale (pad->trak), 1000);
4023
4024     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
4025       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
4026       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
4027     }
4028     atom_traf_set_base_decode_time (pad->traf, dts);
4029   }
4030
4031   /* add buffer and metadata */
4032   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
4033       pad->sync && sync);
4034   atom_array_append (&pad->fragment_buffers, buf, 256);
4035   pad->fragment_duration -= delta;
4036
4037   if (pad->tfra) {
4038     guint32 sn = atom_traf_get_sample_num (pad->traf);
4039
4040     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
4041       atom_tfra_add_entry (pad->tfra, dts, sn);
4042   }
4043
4044   if (G_UNLIKELY (force))
4045     goto flush;
4046
4047   return ret;
4048 }
4049
4050 /* Here's the clever bit of robust recording: Updating the moov
4051  * header is done using a ping-pong scheme inside 2 blocks of size
4052  * 'reserved_moov_size' at the start of the file, in such a way that the
4053  * file on-disk is always valid if interrupted.
4054  * Inside the reserved space, we have 2 pairs of free + moov atoms
4055  * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4056  * at offset "reserved_moov_size".
4057  *
4058  * 1. Free-A has 0 size payload, moov-A immediately after is
4059  *    active/current, and is padded with an internal Free atom to
4060  *    end at reserved_space/2. Free-B is at reserved_space/2, sized
4061  *    to cover the remaining free space (including moov-B).
4062  * 2. We write moov-B (which is invisible inside free-B), and pad it to
4063  *    end at the end of free space. Then, we update free-A to size
4064  *    reserved_space/2 + sizeof(free-B), which hides moov-A and the
4065  *    free-B header, and makes moov-B active.
4066  * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4067  *    Change the size of free-A to make moov-A active again.
4068  * 4. Rinse and repeat.
4069  *
4070  */
4071 static GstFlowReturn
4072 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4073 {
4074   GstSegment segment;
4075   GstFlowReturn ret;
4076   guint64 freeA_offset;
4077   guint32 new_freeA_size;
4078   guint64 new_moov_offset;
4079
4080   /* Update moov info, then seek and rewrite the MOOV atom */
4081   gst_qt_mux_update_global_statistics (qtmux);
4082   gst_qt_mux_configure_moov (qtmux);
4083
4084   gst_qt_mux_update_edit_lists (qtmux);
4085
4086   /* tags into file metadata */
4087   gst_qt_mux_setup_metadata (qtmux);
4088
4089   /* chunks position is set relative to the first byte of the
4090    * MDAT atom payload. Set the overall offset into the file */
4091   atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4092
4093   /* Calculate which moov to rewrite. qtmux->moov_pos points to
4094    * the start of the free-A header */
4095   freeA_offset = qtmux->moov_pos;
4096   if (qtmux->reserved_moov_first_active) {
4097     GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4098     /* After this, freeA will include itself, moovA, plus the freeB
4099      * header */
4100     new_freeA_size = qtmux->reserved_moov_size + 16;
4101   } else {
4102     GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4103     new_freeA_size = 8;
4104   }
4105   /* the moov we update is after free-A, calculate its offset */
4106   new_moov_offset = freeA_offset + new_freeA_size;
4107
4108   /* Swap ping-pong cadence marker */
4109   qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4110
4111   /* seek and rewrite the MOOV atom */
4112   gst_segment_init (&segment, GST_FORMAT_BYTES);
4113   segment.start = new_moov_offset;
4114   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4115
4116   ret =
4117       gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4118       TRUE);
4119   if (ret != GST_FLOW_OK)
4120     return ret;
4121
4122   /* Update the estimated recording space remaining, based on amount used so
4123    * far and duration muxed so far */
4124   if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4125     GstClockTime remain;
4126     GstClockTime time_muxed = qtmux->last_dts;
4127
4128     remain =
4129         gst_util_uint64_scale (qtmux->reserved_moov_size -
4130         qtmux->last_moov_size, time_muxed,
4131         qtmux->last_moov_size - qtmux->base_moov_size);
4132     /* Always under-estimate slightly, so users
4133      * have time to stop muxing before we run out */
4134     if (remain < GST_SECOND / 2)
4135       remain = 0;
4136     else
4137       remain -= GST_SECOND / 2;
4138
4139     GST_INFO_OBJECT (qtmux,
4140         "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4141         ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4142         qtmux->reserved_moov_size, qtmux->last_moov_size,
4143         GST_TIME_ARGS (qtmux->last_dts),
4144         qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4145
4146     GST_OBJECT_LOCK (qtmux);
4147     qtmux->reserved_duration_remaining = remain;
4148     qtmux->muxed_since_last_update = 0;
4149     GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4150         G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4151     GST_OBJECT_UNLOCK (qtmux);
4152   }
4153
4154
4155   /* Now update the moov-A size. Don't pass offset, since we don't need
4156    * send_free_atom() to seek for us - all our callers seek back to
4157    * where they need after this, or they don't need it */
4158   gst_segment_init (&segment, GST_FORMAT_BYTES);
4159   segment.start = freeA_offset;
4160   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4161
4162   ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4163
4164   return ret;
4165 }
4166
4167 static GstFlowReturn
4168 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4169 {
4170   GstSegment segment;
4171   GstFlowReturn flow_ret;
4172
4173   guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4174
4175   GST_OBJECT_LOCK (qtmux);
4176
4177   /* Update the offset of how much we've muxed, so the
4178    * report of remaining space keeps counting down */
4179   if (position > qtmux->last_moov_update &&
4180       position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4181     GST_LOG_OBJECT (qtmux,
4182         "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4183         qtmux->muxed_since_last_update);
4184     qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4185   }
4186
4187   /* Next, check if we're supposed to send periodic moov updates downstream */
4188   if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4189     GST_OBJECT_UNLOCK (qtmux);
4190     return GST_FLOW_OK;
4191   }
4192
4193   /* Update if position is > the threshold or there's been no update yet */
4194   if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4195       (position <= qtmux->last_moov_update ||
4196           (position - qtmux->last_moov_update) <
4197           qtmux->reserved_moov_update_period)) {
4198     GST_OBJECT_UNLOCK (qtmux);
4199     return GST_FLOW_OK;         /* No update needed yet */
4200   }
4201
4202   qtmux->last_moov_update = position;
4203   GST_OBJECT_UNLOCK (qtmux);
4204
4205   GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4206       " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4207       GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4208
4209   flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4210   if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4211     return flow_ret;
4212
4213   /* Seek back to previous position */
4214   gst_segment_init (&segment, GST_FORMAT_BYTES);
4215   segment.start = mdat_offset;
4216   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4217
4218   return flow_ret;
4219 }
4220
4221 static GstFlowReturn
4222 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4223     GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4224     gint64 last_dts, gint64 scaled_duration, guint sample_size,
4225     guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4226 {
4227   GstFlowReturn ret = GST_FLOW_OK;
4228
4229   /* note that a new chunk is started each time (not fancy but works) */
4230   if (qtmux->moov_recov_file) {
4231     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4232             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4233             do_pts, pts_offset)) {
4234       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4235           "recovery file, disabling recovery");
4236       fclose (qtmux->moov_recov_file);
4237       qtmux->moov_recov_file = NULL;
4238     }
4239   }
4240
4241   switch (qtmux->mux_mode) {
4242     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4243       const TrakBufferEntryInfo *sample_entry;
4244       guint64 block_idx = prefill_get_block_index (qtmux, pad);
4245
4246       if (block_idx >= pad->samples->len) {
4247         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4248             ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4249                 block_idx, pad->samples->len));
4250         gst_buffer_unref (buffer);
4251         return GST_FLOW_ERROR;
4252       }
4253
4254       /* Check if all values are as expected */
4255       sample_entry =
4256           &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4257
4258       /* Allow +/- 1 difference for the scaled_duration to allow
4259        * for some rounding errors
4260        */
4261       if (sample_entry->nsamples != nsamples
4262           || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4263           || sample_entry->size != sample_size
4264           || sample_entry->chunk_offset != chunk_offset
4265           || sample_entry->pts_offset != pts_offset
4266           || sample_entry->sync != sync) {
4267         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4268             ("Unexpected values in sample %" G_GUINT64_FORMAT,
4269                 pad->sample_offset + 1));
4270         GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4271             "chunk offset %" G_GUINT64_FORMAT ", "
4272             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4273             sample_entry->nsamples,
4274             sample_entry->delta,
4275             sample_entry->size,
4276             sample_entry->chunk_offset,
4277             sample_entry->pts_offset, sample_entry->sync);
4278         GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4279             "chunk offset %" G_GUINT64_FORMAT ", "
4280             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4281             nsamples,
4282             (guint) scaled_duration,
4283             sample_size, chunk_offset, pts_offset, sync);
4284
4285         gst_buffer_unref (buffer);
4286         return GST_FLOW_ERROR;
4287       }
4288
4289       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4290       break;
4291     }
4292     case GST_QT_MUX_MODE_MOOV_AT_END:
4293     case GST_QT_MUX_MODE_FAST_START:
4294     case GST_QT_MUX_MODE_ROBUST_RECORDING:
4295       atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4296           sample_size, chunk_offset, sync, pts_offset);
4297       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4298       /* Check if it's time to re-write the headers in robust-recording mode */
4299       if (ret == GST_FLOW_OK
4300           && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4301         ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4302       break;
4303     case GST_QT_MUX_MODE_FRAGMENTED:
4304     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4305       /* ensure that always sync samples are marked as such */
4306       ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4307           is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4308           sample_size, !pad->sync || sync, pts_offset);
4309       break;
4310   }
4311
4312   return ret;
4313 }
4314
4315 static void
4316 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4317     guint buffer_size, GstClockTime duration)
4318 {
4319   /* not that much happens here,
4320    * but updating any of this very likely needs to happen all in sync,
4321    * unless there is a very good reason not to */
4322
4323   /* for computing the avg bitrate */
4324   pad->total_bytes += buffer_size;
4325   pad->total_duration += duration;
4326   /* for keeping track of where we are in chunk;
4327    * ensures that data really is located as recorded in atoms */
4328   qtmux->current_chunk_size += buffer_size;
4329   qtmux->current_chunk_duration += duration;
4330 }
4331
4332 static GstFlowReturn
4333 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4334     GstBuffer * buf, GstFlowReturn ret)
4335 {
4336   GstVideoTimeCodeMeta *tc_meta;
4337   GstVideoTimeCode *tc;
4338   GstBuffer *tc_buf;
4339   gsize szret;
4340   guint32 frames_since_daily_jam;
4341   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4342
4343   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4344     return ret;
4345
4346   if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4347     return ret;
4348
4349   tc_meta = gst_buffer_get_video_time_code_meta (buf);
4350   if (!tc_meta)
4351     return ret;
4352
4353   tc = &tc_meta->tc;
4354
4355   /* This means we never got a timecode before */
4356   if (pad->first_tc == NULL) {
4357 #ifndef GST_DISABLE_GST_DEBUG
4358     gchar *tc_str = gst_video_time_code_to_string (tc);
4359     GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4360     g_free (tc_str);
4361 #endif
4362     g_assert (pad->tc_trak == NULL);
4363     pad->first_tc = gst_video_time_code_copy (tc);
4364     /* If frames are out of order, the frame we're currently getting might
4365      * not be the first one. Just write a 0 timecode for now and wait
4366      * until we receive a timecode that's lower than the current one */
4367     if (pad->is_out_of_order) {
4368       pad->first_pts = GST_BUFFER_PTS (buf);
4369       frames_since_daily_jam = 0;
4370       /* Position to rewrite */
4371       pad->tc_pos = qtmux->mdat_size;
4372     } else {
4373       frames_since_daily_jam =
4374           gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4375       frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4376     }
4377     /* Write the timecode trak now */
4378     pad->tc_trak = atom_trak_new (qtmux->context);
4379     atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4380
4381     pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4382     atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4383
4384     atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4385         pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4386
4387     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4388     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4389     g_assert (szret == 4);
4390
4391     atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4392     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4393
4394     /* Need to reset the current chunk (of the previous pad) here because
4395      * some other data was written now above, and the pad has to start a
4396      * new chunk now */
4397     qtmux->current_chunk_offset = -1;
4398     qtmux->current_chunk_size = 0;
4399     qtmux->current_chunk_duration = 0;
4400   } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4401     frames_since_daily_jam =
4402         gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4403     frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4404
4405     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4406     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4407     g_assert (szret == 4);
4408
4409     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4410     pad->tc_pos = -1;
4411
4412     qtmux->current_chunk_offset = -1;
4413     qtmux->current_chunk_size = 0;
4414     qtmux->current_chunk_duration = 0;
4415   } else if (pad->is_out_of_order) {
4416     /* Check for a lower timecode than the one stored */
4417     g_assert (pad->tc_trak != NULL);
4418     if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4419       if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4420         gst_video_time_code_free (pad->first_tc);
4421         pad->first_tc = gst_video_time_code_copy (tc);
4422       }
4423     } else {
4424       guint64 bk_size = qtmux->mdat_size;
4425       GstSegment segment;
4426       /* If this frame's DTS is after the first PTS received, it means
4427        * we've already received the first frame to be presented. Otherwise
4428        * the decoder would need to go back in time */
4429       gst_qt_mux_update_timecode (qtmux, pad);
4430
4431       /* Reset writing position */
4432       gst_segment_init (&segment, GST_FORMAT_BYTES);
4433       segment.start = bk_size;
4434       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4435     }
4436   }
4437
4438   return ret;
4439 }
4440
4441 /*
4442  * Here we push the buffer and update the tables in the track atoms
4443  */
4444 static GstFlowReturn
4445 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4446 {
4447   GstBuffer *last_buf = NULL;
4448   GstClockTime duration;
4449   guint nsamples, sample_size;
4450   guint64 chunk_offset;
4451   gint64 last_dts, scaled_duration;
4452   gint64 pts_offset = 0;
4453   gboolean sync = FALSE;
4454   GstFlowReturn ret = GST_FLOW_OK;
4455   guint buffer_size;
4456
4457   if (!pad->fourcc)
4458     goto not_negotiated;
4459
4460   /* if this pad has a prepare function, call it */
4461   if (pad->prepare_buf_func != NULL) {
4462     GstBuffer *new_buf;
4463
4464     new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4465     if (buf && !new_buf)
4466       return GST_FLOW_OK;
4467     buf = new_buf;
4468   }
4469
4470   ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4471   if (ret != GST_FLOW_OK) {
4472     if (buf)
4473       gst_buffer_unref (buf);
4474     return ret;
4475   }
4476
4477   last_buf = pad->last_buf;
4478   pad->last_buf = buf;
4479
4480   if (last_buf == NULL) {
4481 #ifndef GST_DISABLE_GST_DEBUG
4482     if (buf == NULL) {
4483       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4484           "received NULL buffer, doing nothing",
4485           GST_PAD_NAME (pad->collect.pad));
4486     } else {
4487       GST_LOG_OBJECT (qtmux,
4488           "Pad %s has no previous buffer stored, storing now",
4489           GST_PAD_NAME (pad->collect.pad));
4490     }
4491 #endif
4492     goto exit;
4493   }
4494
4495   if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4496     goto no_pts;
4497
4498   /* if this is the first buffer, store the timestamp */
4499   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4500     if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4501       pad->first_ts = GST_BUFFER_PTS (last_buf);
4502     } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4503       pad->first_ts = GST_BUFFER_DTS (last_buf);
4504     }
4505
4506     if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4507       pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4508     } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4509       pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4510     }
4511
4512     if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4513       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4514     } else {
4515       GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4516           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4517       pad->first_ts = pad->first_dts = 0;
4518     }
4519     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4520         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4521         GST_TIME_ARGS (pad->first_ts));
4522   }
4523
4524   if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4525       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4526       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4527     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4528         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4529         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4530     pad->last_buf = buf = gst_buffer_make_writable (buf);
4531     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4532   }
4533
4534   buffer_size = gst_buffer_get_size (last_buf);
4535
4536   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4537     guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4538     guint fill_size = required_buffer_size - buffer_size;
4539     GstMemory *mem;
4540     GstMapInfo map;
4541
4542     if (required_buffer_size < buffer_size) {
4543       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4544           ("Sample size %u bigger than expected maximum %u", buffer_size,
4545               required_buffer_size));
4546       goto bail;
4547     }
4548
4549     if (fill_size > 0) {
4550       GST_DEBUG_OBJECT (qtmux,
4551           "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4552           required_buffer_size);
4553       mem = gst_allocator_alloc (NULL, fill_size, NULL);
4554       gst_memory_map (mem, &map, GST_MAP_WRITE);
4555       memset (map.data, 0, map.size);
4556       gst_memory_unmap (mem, &map);
4557       last_buf = gst_buffer_make_writable (last_buf);
4558       gst_buffer_append_memory (last_buf, mem);
4559       buffer_size = required_buffer_size;
4560     }
4561   }
4562
4563   /* duration actually means time delta between samples, so we calculate
4564    * the duration based on the difference in DTS or PTS, falling back
4565    * to DURATION if the other two don't exist, such as with the last
4566    * sample before EOS. Or use 0 if nothing else is available */
4567   if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4568     duration = GST_BUFFER_DURATION (last_buf);
4569   else
4570     duration = 0;
4571   if (!pad->sparse) {
4572     if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4573         && GST_BUFFER_DTS_IS_VALID (last_buf))
4574       duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4575     else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4576         && GST_BUFFER_PTS_IS_VALID (last_buf))
4577       duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4578   }
4579
4580   if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4581     GST_DEBUG_OBJECT (qtmux,
4582         "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4583         ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4584         GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4585         qtmux->current_chunk_size,
4586         GST_TIME_ARGS (qtmux->current_chunk_duration));
4587     qtmux->current_pad = pad;
4588     if (qtmux->current_chunk_offset == -1)
4589       qtmux->current_chunk_offset = qtmux->mdat_size;
4590     else
4591       qtmux->current_chunk_offset += qtmux->current_chunk_size;
4592     qtmux->current_chunk_size = 0;
4593     qtmux->current_chunk_duration = 0;
4594   }
4595
4596   last_dts = gst_util_uint64_scale_round (pad->last_dts,
4597       atom_trak_get_timescale (pad->trak), GST_SECOND);
4598
4599   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4600   if (pad->sample_size && !qtmux->fragment_sequence) {
4601     GstClockTime expected_timestamp;
4602
4603     /* Constant size packets: usually raw audio (with many samples per
4604        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4605      */
4606     sample_size = pad->sample_size;
4607     if (buffer_size % sample_size != 0)
4608       goto fragmented_sample;
4609
4610     /* note: qt raw audio storage warps it implicitly into a timewise
4611      * perfect stream, discarding buffer times.
4612      * If the difference between the current PTS and the expected one
4613      * becomes too big, we error out: there was a gap and we have no way to
4614      * represent that, causing A/V sync to be off */
4615     expected_timestamp =
4616         gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4617         atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4618     if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4619             expected_timestamp) > qtmux->max_raw_audio_drift)
4620       goto raw_audio_timestamp_drift;
4621
4622     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4623       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4624           atom_trak_get_timescale (pad->trak), GST_SECOND);
4625       duration = GST_BUFFER_DURATION (last_buf);
4626     } else {
4627       nsamples = buffer_size / sample_size;
4628       duration =
4629           gst_util_uint64_scale_round (nsamples, GST_SECOND,
4630           atom_trak_get_timescale (pad->trak));
4631     }
4632
4633     /* timescale = samplerate */
4634     scaled_duration = 1;
4635     pad->last_dts =
4636         pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4637         nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4638   } else {
4639     nsamples = 1;
4640     sample_size = buffer_size;
4641     if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4642             || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4643       gint64 scaled_dts;
4644       if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4645         pad->last_dts = GST_BUFFER_DTS (buf);
4646       } else {
4647         pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4648       }
4649       if ((gint64) (pad->last_dts) < 0) {
4650         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4651             atom_trak_get_timescale (pad->trak), GST_SECOND);
4652       } else {
4653         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4654             atom_trak_get_timescale (pad->trak), GST_SECOND);
4655       }
4656       scaled_duration = scaled_dts - last_dts;
4657       last_dts = scaled_dts;
4658     } else {
4659       /* first convert intended timestamp (in GstClockTime resolution) to
4660        * trak timescale, then derive delta;
4661        * this ensures sums of (scale)delta add up to converted timestamp,
4662        * which only deviates at most 1/scale from timestamp itself */
4663       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4664           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4665       pad->last_dts += duration;
4666     }
4667   }
4668
4669   gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4670
4671   chunk_offset = qtmux->current_chunk_offset;
4672
4673   GST_LOG_OBJECT (qtmux,
4674       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4675       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4676   GST_LOG_OBJECT (qtmux,
4677       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4678       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4679       nsamples, scaled_duration, sample_size, chunk_offset);
4680
4681   /* might be a sync sample */
4682   if (pad->sync &&
4683       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4684     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4685         GST_PAD_NAME (pad->collect.pad));
4686     sync = TRUE;
4687   }
4688
4689   if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4690     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4691         atom_trak_get_timescale (pad->trak), GST_SECOND);
4692     pts_offset =
4693         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4694             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4695   } else {
4696     pts_offset = 0;
4697     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4698         atom_trak_get_timescale (pad->trak), GST_SECOND);
4699   }
4700   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4701       " timebase_dts: %d pts_offset: %d",
4702       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4703       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4704       (int) (last_dts), (int) (pts_offset));
4705
4706   if (GST_CLOCK_TIME_IS_VALID (duration)
4707       && (qtmux->current_chunk_duration > qtmux->longest_chunk
4708           || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4709     GST_DEBUG_OBJECT (qtmux,
4710         "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4711         GST_TIME_ARGS (qtmux->current_chunk_duration),
4712         GST_PAD_NAME (pad->collect.pad));
4713     qtmux->longest_chunk = qtmux->current_chunk_duration;
4714   }
4715
4716   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4717     const TrakBufferEntryInfo *sample_entry;
4718     guint64 block_idx = prefill_get_block_index (qtmux, pad);
4719
4720     if (block_idx >= pad->samples->len) {
4721       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4722           ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4723               block_idx, pad->samples->len));
4724       goto bail;
4725     }
4726
4727     /* Check if all values are as expected */
4728     sample_entry =
4729         &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4730
4731     if (chunk_offset < sample_entry->chunk_offset) {
4732       guint fill_size = sample_entry->chunk_offset - chunk_offset;
4733       GstBuffer *fill_buf;
4734
4735       fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4736       gst_buffer_memset (fill_buf, 0, 0, fill_size);
4737
4738       ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4739       if (ret != GST_FLOW_OK)
4740         goto bail;
4741       qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4742       qtmux->current_chunk_size = buffer_size;
4743       qtmux->current_chunk_duration = duration;
4744     } else if (chunk_offset != sample_entry->chunk_offset) {
4745       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4746           ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4747               G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4748       goto bail;
4749     }
4750   }
4751
4752   /* now we go and register this buffer/sample all over */
4753   ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4754       buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4755       chunk_offset, sync, TRUE, pts_offset);
4756   pad->sample_offset += nsamples;
4757
4758   /* if this is sparse and we have a next buffer, check if there is any gap
4759    * between them to insert an empty sample */
4760   if (pad->sparse && buf) {
4761     if (pad->create_empty_buffer) {
4762       GstBuffer *empty_buf;
4763       gint64 empty_duration =
4764           GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4765       gint64 empty_duration_scaled;
4766       guint empty_size;
4767
4768       empty_buf = pad->create_empty_buffer (pad, empty_duration);
4769
4770       pad->last_dts = GST_BUFFER_PTS (buf);
4771       empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4772           atom_trak_get_timescale (pad->trak), GST_SECOND)
4773           - (last_dts + scaled_duration);
4774       empty_size = gst_buffer_get_size (empty_buf);
4775
4776       gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4777           empty_duration);
4778
4779       ret =
4780           gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4781           last_dts + scaled_duration, empty_duration_scaled,
4782           empty_size, chunk_offset, sync, TRUE, 0);
4783     } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4784       /* This assert is kept here to make sure implementors of new
4785        * sparse input format decide whether there needs to be special
4786        * gap handling or not */
4787       g_assert_not_reached ();
4788       GST_WARNING_OBJECT (qtmux,
4789           "no empty buffer creation function found for pad %s",
4790           GST_PAD_NAME (pad->collect.pad));
4791     }
4792   }
4793
4794 exit:
4795
4796   return ret;
4797
4798   /* ERRORS */
4799 bail:
4800   {
4801     gst_buffer_unref (last_buf);
4802     return GST_FLOW_ERROR;
4803   }
4804 fragmented_sample:
4805   {
4806     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4807         ("Audio buffer contains fragmented sample."));
4808     goto bail;
4809   }
4810 raw_audio_timestamp_drift:
4811   {
4812     /* TODO: Could in theory be implemented with edit lists */
4813     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4814         ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4815             ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4816             GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4817             GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4818                     GST_SECOND,
4819                     atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4820     goto bail;
4821   }
4822 no_pts:
4823   {
4824     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4825     goto bail;
4826   }
4827 not_negotiated:
4828   {
4829     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4830         ("format wasn't negotiated before buffer flow on pad %s",
4831             GST_PAD_NAME (pad->collect.pad)));
4832     if (buf)
4833       gst_buffer_unref (buf);
4834     return GST_FLOW_NOT_NEGOTIATED;
4835   }
4836 }
4837
4838 /*
4839  * DTS running time can be negative. There is no way to represent that in
4840  * MP4 however, thus we need to offset DTS so that it starts from 0.
4841  */
4842 static void
4843 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4844     GstCollectData * cdata, GstBuffer ** buf)
4845 {
4846   GstClockTime pts;
4847   gint64 dts;
4848
4849   pts = GST_BUFFER_PTS (*buf);
4850   dts = GST_COLLECT_PADS_DTS (cdata);
4851
4852   GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4853       " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4854       GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4855
4856   if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4857     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4858       pad->dts_adjustment = -dts;
4859     else
4860       pad->dts_adjustment = 0;
4861   }
4862
4863   if (pad->dts_adjustment > 0) {
4864     *buf = gst_buffer_make_writable (*buf);
4865
4866     dts += pad->dts_adjustment;
4867
4868     if (GST_CLOCK_TIME_IS_VALID (pts))
4869       pts += pad->dts_adjustment;
4870
4871     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4872       GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4873       dts = 0;
4874     }
4875
4876     if (pts < dts) {
4877       GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4878       pts = dts;
4879     }
4880
4881     GST_BUFFER_PTS (*buf) = pts;
4882     GST_BUFFER_DTS (*buf) = dts;
4883
4884     GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4885         " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4886   }
4887 }
4888
4889 static GstQTPad *
4890 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4891 {
4892   GSList *walk;
4893   GstQTPad *best_pad = NULL;
4894
4895   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4896     guint64 smallest_offset = G_MAXUINT64;
4897     guint64 chunk_offset = 0;
4898
4899     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4900       GstCollectData *cdata = (GstCollectData *) walk->data;
4901       GstQTPad *qtpad = (GstQTPad *) cdata;
4902       const TrakBufferEntryInfo *sample_entry;
4903       guint64 block_idx, current_block_idx;
4904       guint64 chunk_offset_offset = 0;
4905       GstBuffer *tmp_buf =
4906           gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4907
4908       /* Check for EOS pads and just skip them */
4909       if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4910               || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4911         continue;
4912       if (tmp_buf)
4913         gst_buffer_unref (tmp_buf);
4914
4915       /* Find the exact offset where the next sample of this track is supposed
4916        * to be written at */
4917       block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4918       sample_entry =
4919           &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4920       while (block_idx > 0) {
4921         const TrakBufferEntryInfo *tmp =
4922             &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4923
4924         if (tmp->chunk_offset != sample_entry->chunk_offset)
4925           break;
4926         chunk_offset_offset += tmp->size * tmp->nsamples;
4927         block_idx--;
4928       }
4929
4930       /* Except for the previously selected pad being EOS we always have
4931        *  qtmux->current_chunk_offset + qtmux->current_chunk_size
4932        *    ==
4933        *  sample_entry->chunk_offset + chunk_offset_offset
4934        * for the best pad. Instead of checking that, we just return the
4935        * pad that has the smallest offset for the next to-be-written sample.
4936        */
4937       if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4938         smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4939         best_pad = qtpad;
4940         chunk_offset = sample_entry->chunk_offset;
4941       }
4942     }
4943
4944     if (chunk_offset != qtmux->current_chunk_offset) {
4945       qtmux->current_pad = NULL;
4946     }
4947
4948     return best_pad;
4949   }
4950
4951   if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4952           || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4953           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4954       && (qtmux->interleave_time == 0
4955           || qtmux->current_chunk_duration <= qtmux->interleave_time)
4956       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4957       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4958     GstBuffer *tmp_buf =
4959         gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4960
4961     if (tmp_buf || qtmux->current_pad->last_buf) {
4962       best_pad = qtmux->current_pad;
4963       if (tmp_buf)
4964         gst_buffer_unref (tmp_buf);
4965       GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4966           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4967     }
4968   } else if (qtmux->collect->data->next) {
4969     /* Only switch pads if we have more than one, otherwise
4970      * we can just put everything into a single chunk and save
4971      * a few bytes of offsets
4972      */
4973     if (qtmux->current_pad)
4974       GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4975           GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4976     best_pad = qtmux->current_pad = NULL;
4977   }
4978
4979   if (!best_pad) {
4980     GstClockTime best_time = GST_CLOCK_TIME_NONE;
4981
4982     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4983       GstCollectData *cdata = (GstCollectData *) walk->data;
4984       GstQTPad *qtpad = (GstQTPad *) cdata;
4985       GstBuffer *tmp_buf;
4986       GstClockTime timestamp;
4987
4988       tmp_buf = gst_collect_pads_peek (pads, cdata);
4989       if (!tmp_buf) {
4990         /* This one is newly EOS now, finish it for real */
4991         if (qtpad->last_buf) {
4992           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4993         } else {
4994           continue;
4995         }
4996       } else {
4997         if (qtpad->last_buf)
4998           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4999         else
5000           timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
5001       }
5002
5003       if (best_pad == NULL ||
5004           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
5005         best_pad = qtpad;
5006         best_time = timestamp;
5007       }
5008
5009       if (tmp_buf)
5010         gst_buffer_unref (tmp_buf);
5011     }
5012
5013     if (best_pad) {
5014       GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
5015           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
5016     } else {
5017       GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
5018     }
5019   }
5020
5021   return best_pad;
5022 }
5023
5024 static GstFlowReturn
5025 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
5026 {
5027   GstFlowReturn ret = GST_FLOW_OK;
5028   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
5029   GstQTPad *best_pad = NULL;
5030
5031   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
5032     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
5033       return ret;
5034
5035     qtmux->state = GST_QT_MUX_STATE_DATA;
5036   }
5037
5038   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
5039     return GST_FLOW_EOS;
5040
5041   best_pad = find_best_pad (qtmux, pads);
5042
5043   /* clipping already converted to running time */
5044   if (best_pad != NULL) {
5045     GstBuffer *buf = NULL;
5046
5047     if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
5048         best_pad->raw_audio_adapter == NULL ||
5049         best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
5050       buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
5051
5052     g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
5053             && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
5054
5055     if (buf)
5056       gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
5057           (GstCollectData *) best_pad, &buf);
5058
5059     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5060   } else {
5061     qtmux->state = GST_QT_MUX_STATE_EOS;
5062     ret = gst_qt_mux_stop_file (qtmux);
5063     if (ret == GST_FLOW_OK) {
5064       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
5065       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5066       ret = GST_FLOW_EOS;
5067     } else {
5068       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5069           gst_flow_get_name (ret));
5070     }
5071   }
5072
5073   return ret;
5074 }
5075
5076 static gboolean
5077 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5078 {
5079   GstStructure *structure = (GstStructure *) user_data;
5080   const GValue *other = gst_structure_id_get_value (structure, field_id);
5081   if (other == NULL)
5082     return FALSE;
5083   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5084 }
5085
5086 static gboolean
5087 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5088     GstCaps * superset)
5089 {
5090   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5091   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5092
5093   return gst_structure_foreach (sub_s, check_field, sup_s);
5094 }
5095
5096 /* will unref @qtmux */
5097 static gboolean
5098 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5099 {
5100   GstCaps *current_caps;
5101
5102   /* does not go well to renegotiate stream mid-way, unless
5103    * the old caps are a subset of the new one (this means upstream
5104    * added more info to the caps, as both should be 'fixed' caps) */
5105   current_caps = gst_pad_get_current_caps (pad);
5106   g_assert (caps != NULL);
5107
5108   if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5109     gst_caps_unref (current_caps);
5110     GST_WARNING_OBJECT (qtmux,
5111         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5112         GST_PAD_NAME (pad), caps);
5113     gst_object_unref (qtmux);
5114     return FALSE;
5115   }
5116
5117   GST_DEBUG_OBJECT (qtmux,
5118       "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5119       GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5120   gst_object_unref (qtmux);
5121   gst_caps_unref (current_caps);
5122
5123   return TRUE;
5124 }
5125
5126 static gboolean
5127 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5128 {
5129   GstPad *pad = qtpad->collect.pad;
5130   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5131   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5132   GstStructure *structure;
5133   const gchar *mimetype;
5134   gint rate, channels;
5135   const GValue *value = NULL;
5136   const GstBuffer *codec_data = NULL;
5137   GstQTMuxFormat format;
5138   AudioSampleEntry entry = { 0, };
5139   AtomInfo *ext_atom = NULL;
5140   gint constant_size = 0;
5141   const gchar *stream_format;
5142   guint32 timescale;
5143
5144   if (qtpad->fourcc)
5145     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5146
5147   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5148       GST_DEBUG_PAD_NAME (pad), caps);
5149
5150   qtpad->prepare_buf_func = NULL;
5151
5152   format = qtmux_klass->format;
5153   structure = gst_caps_get_structure (caps, 0);
5154   mimetype = gst_structure_get_name (structure);
5155
5156   /* common info */
5157   if (!gst_structure_get_int (structure, "channels", &channels) ||
5158       !gst_structure_get_int (structure, "rate", &rate)) {
5159     goto refuse_caps;
5160   }
5161
5162   /* optional */
5163   value = gst_structure_get_value (structure, "codec_data");
5164   if (value != NULL)
5165     codec_data = gst_value_get_buffer (value);
5166
5167   qtpad->is_out_of_order = FALSE;
5168
5169   /* set common properties */
5170   entry.sample_rate = rate;
5171   entry.channels = channels;
5172   /* default */
5173   entry.sample_size = 16;
5174   /* this is the typical compressed case */
5175   if (format == GST_QT_MUX_FORMAT_QT) {
5176     entry.version = 1;
5177     entry.compression_id = -2;
5178   }
5179
5180   /* now map onto a fourcc, and some extra properties */
5181   if (strcmp (mimetype, "audio/mpeg") == 0) {
5182     gint mpegversion = 0, mpegaudioversion = 0;
5183     gint layer = -1;
5184
5185     gst_structure_get_int (structure, "mpegversion", &mpegversion);
5186     switch (mpegversion) {
5187       case 1:
5188         gst_structure_get_int (structure, "layer", &layer);
5189         gst_structure_get_int (structure, "mpegaudioversion",
5190             &mpegaudioversion);
5191
5192         /* mp1/2/3 */
5193         /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5194         if (format == GST_QT_MUX_FORMAT_QT)
5195           entry.fourcc = FOURCC__mp3;
5196         else {
5197           entry.fourcc = FOURCC_mp4a;
5198           ext_atom =
5199               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5200               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5201               qtpad->max_bitrate);
5202         }
5203         if (layer == 1) {
5204           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5205               || format == GST_QT_MUX_FORMAT_QT);
5206           entry.samples_per_packet = 384;
5207         } else if (layer == 2) {
5208           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5209               || format == GST_QT_MUX_FORMAT_QT);
5210           entry.samples_per_packet = 1152;
5211         } else {
5212           g_warn_if_fail (layer == 3);
5213           entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5214         }
5215         entry.bytes_per_sample = 2;
5216         break;
5217       case 4:
5218
5219         /* check stream-format */
5220         stream_format = gst_structure_get_string (structure, "stream-format");
5221         if (stream_format) {
5222           if (strcmp (stream_format, "raw") != 0) {
5223             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5224                 "please use 'raw'", stream_format);
5225             goto refuse_caps;
5226           }
5227         } else {
5228           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5229               "assuming 'raw'");
5230         }
5231
5232         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5233           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5234           goto refuse_caps;
5235         } else {
5236           guint8 profile;
5237
5238           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5239           /* warn if not Low Complexity profile */
5240           profile >>= 3;
5241           if (profile != 2)
5242             GST_WARNING_OBJECT (qtmux,
5243                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5244         }
5245
5246         /* AAC */
5247         entry.fourcc = FOURCC_mp4a;
5248
5249         if (format == GST_QT_MUX_FORMAT_QT)
5250           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5251               qtpad->avg_bitrate, qtpad->max_bitrate);
5252         else
5253           ext_atom =
5254               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5255               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5256               qtpad->max_bitrate);
5257         break;
5258       default:
5259         break;
5260     }
5261   } else if (strcmp (mimetype, "audio/AMR") == 0) {
5262     entry.fourcc = FOURCC_samr;
5263     entry.sample_size = 16;
5264     entry.samples_per_packet = 160;
5265     entry.bytes_per_sample = 2;
5266     ext_atom = build_amr_extension ();
5267   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5268     entry.fourcc = FOURCC_sawb;
5269     entry.sample_size = 16;
5270     entry.samples_per_packet = 320;
5271     entry.bytes_per_sample = 2;
5272     ext_atom = build_amr_extension ();
5273   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5274     GstAudioInfo info;
5275
5276     gst_audio_info_init (&info);
5277     if (!gst_audio_info_from_caps (&info, caps))
5278       goto refuse_caps;
5279
5280     /* spec has no place for a distinction in these */
5281     if (info.finfo->width != info.finfo->depth) {
5282       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5283       goto refuse_caps;
5284     }
5285
5286     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5287       if (info.finfo->endianness == G_LITTLE_ENDIAN)
5288         entry.fourcc = FOURCC_sowt;
5289       else if (info.finfo->endianness == G_BIG_ENDIAN)
5290         entry.fourcc = FOURCC_twos;
5291       else
5292         entry.fourcc = FOURCC_sowt;
5293       /* maximum backward compatibility; only new version for > 16 bit */
5294       if (info.finfo->depth <= 16)
5295         entry.version = 0;
5296       /* not compressed in any case */
5297       entry.compression_id = 0;
5298       /* QT spec says: max at 16 bit even if sample size were actually larger,
5299        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5300       entry.sample_size = info.finfo->depth;
5301       entry.bytes_per_sample = info.finfo->depth / 8;
5302       entry.samples_per_packet = 1;
5303       entry.bytes_per_packet = info.finfo->depth / 8;
5304       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5305     } else {
5306       if (info.finfo->width == 8 && info.finfo->depth == 8) {
5307         /* fall back to old 8-bit version */
5308         entry.fourcc = FOURCC_raw_;
5309         entry.version = 0;
5310         entry.compression_id = 0;
5311         entry.sample_size = 8;
5312       } else {
5313         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5314         goto refuse_caps;
5315       }
5316     }
5317     constant_size = (info.finfo->depth / 8) * info.channels;
5318   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5319     entry.fourcc = FOURCC_alaw;
5320     entry.samples_per_packet = 1023;
5321     entry.bytes_per_sample = 2;
5322   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5323     entry.fourcc = FOURCC_ulaw;
5324     entry.samples_per_packet = 1023;
5325     entry.bytes_per_sample = 2;
5326   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5327     gint blocksize;
5328     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5329       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5330       goto refuse_caps;
5331     }
5332     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5333        0x11 */
5334     entry.fourcc = MS_WAVE_FOURCC (0x11);
5335     /* 4 byte header per channel (including one sample). 2 samples per byte
5336        remaining. Simplifying gives the following (samples per block per
5337        channel) */
5338     entry.samples_per_packet = 2 * blocksize / channels - 7;
5339     entry.bytes_per_sample = 2;
5340
5341     entry.bytes_per_frame = blocksize;
5342     entry.bytes_per_packet = blocksize / channels;
5343     /* ADPCM has constant size packets */
5344     constant_size = 1;
5345     /* TODO: I don't really understand why this helps, but it does! Constant
5346      * size and compression_id of -2 seem to be incompatible, and other files
5347      * in the wild use this too. */
5348     entry.compression_id = -1;
5349
5350     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5351   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5352     GstBuffer *codec_config;
5353     gint len;
5354     GstMapInfo map;
5355
5356     entry.fourcc = FOURCC_alac;
5357     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5358     /* let's check if codec data already comes with 'alac' atom prefix */
5359     if (!codec_data || (len = map.size) < 28) {
5360       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5361       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5362       goto refuse_caps;
5363     }
5364     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5365       len -= 8;
5366       codec_config =
5367           gst_buffer_copy_region ((GstBuffer *) codec_data,
5368           GST_BUFFER_COPY_MEMORY, 8, len);
5369     } else {
5370       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5371     }
5372     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5373     if (len != 28) {
5374       /* does not look good, but perhaps some trailing unneeded stuff */
5375       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5376     }
5377     if (format == GST_QT_MUX_FORMAT_QT)
5378       ext_atom = build_mov_alac_extension (codec_config);
5379     else
5380       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5381     /* set some more info */
5382     gst_buffer_map (codec_config, &map, GST_MAP_READ);
5383     entry.bytes_per_sample = 2;
5384     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5385     gst_buffer_unmap (codec_config, &map);
5386     gst_buffer_unref (codec_config);
5387   } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5388     entry.fourcc = FOURCC_ac_3;
5389
5390     /* Fixed values according to TS 102 366 but it also mentions that
5391      * they should be ignored */
5392     entry.channels = 2;
5393     entry.sample_size = 16;
5394
5395     /* AC-3 needs an extension atom but its data can only be obtained from
5396      * the stream itself. Abuse the prepare_buf_func so we parse a frame
5397      * and get the needed data */
5398     qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5399   } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5400     /* Based on the specification defined in:
5401      * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5402     guint8 channels, mapping_family, stream_count, coupled_count;
5403     guint16 pre_skip;
5404     gint16 output_gain;
5405     guint32 rate;
5406     guint8 channel_mapping[256];
5407     const GValue *streamheader;
5408     const GValue *first_element;
5409     GstBuffer *header;
5410
5411     entry.fourcc = FOURCC_opus;
5412     entry.sample_size = 16;
5413
5414     streamheader = gst_structure_get_value (structure, "streamheader");
5415     if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5416         gst_value_array_get_size (streamheader) != 0) {
5417       first_element = gst_value_array_get_value (streamheader, 0);
5418       header = gst_value_get_buffer (first_element);
5419       if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5420               &mapping_family, &stream_count, &coupled_count, channel_mapping,
5421               &pre_skip, &output_gain)) {
5422         GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5423         goto refuse_caps;
5424       }
5425     } else {
5426       GST_WARNING_OBJECT (qtmux,
5427           "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5428
5429       if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5430               &mapping_family, &stream_count, &coupled_count,
5431               channel_mapping)) {
5432         GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5433         goto refuse_caps;
5434       }
5435       pre_skip = 0;
5436       output_gain = 0;
5437     }
5438
5439     entry.channels = channels;
5440     ext_atom = build_opus_extension (rate, channels, mapping_family,
5441         stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5442   }
5443
5444   if (!entry.fourcc)
5445     goto refuse_caps;
5446
5447   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5448   if (!timescale && qtmux->trak_timescale)
5449     timescale = qtmux->trak_timescale;
5450   else if (!timescale)
5451     timescale = entry.sample_rate;
5452
5453   /* ok, set the pad info accordingly */
5454   qtpad->fourcc = entry.fourcc;
5455   qtpad->sample_size = constant_size;
5456   qtpad->trak_ste =
5457       (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5458       qtmux->context, &entry, timescale, ext_atom, constant_size);
5459
5460   gst_object_unref (qtmux);
5461   return TRUE;
5462
5463   /* ERRORS */
5464 refuse_caps:
5465   {
5466     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5467         GST_PAD_NAME (pad), caps);
5468     gst_object_unref (qtmux);
5469     return FALSE;
5470   }
5471 }
5472
5473 static gboolean
5474 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5475 {
5476   GstPad *pad = qtpad->collect.pad;
5477   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5478   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5479   GstStructure *structure;
5480   const gchar *mimetype;
5481   gint width, height, depth = -1;
5482   gint framerate_num, framerate_den;
5483   guint32 rate;
5484   const GValue *value = NULL;
5485   const GstBuffer *codec_data = NULL;
5486   VisualSampleEntry entry = { 0, };
5487   GstQTMuxFormat format;
5488   AtomInfo *ext_atom = NULL;
5489   GList *ext_atom_list = NULL;
5490   gboolean sync = FALSE;
5491   int par_num, par_den;
5492   const gchar *multiview_mode;
5493
5494   if (qtpad->fourcc)
5495     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5496
5497   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5498       GST_DEBUG_PAD_NAME (pad), caps);
5499
5500   qtpad->prepare_buf_func = NULL;
5501
5502   format = qtmux_klass->format;
5503   structure = gst_caps_get_structure (caps, 0);
5504   mimetype = gst_structure_get_name (structure);
5505
5506   /* required parts */
5507   if (!gst_structure_get_int (structure, "width", &width) ||
5508       !gst_structure_get_int (structure, "height", &height))
5509     goto refuse_caps;
5510
5511   /* optional */
5512   depth = -1;
5513   /* works as a default timebase */
5514   framerate_num = 10000;
5515   framerate_den = 1;
5516   gst_structure_get_fraction (structure, "framerate", &framerate_num,
5517       &framerate_den);
5518   gst_structure_get_int (structure, "depth", &depth);
5519   value = gst_structure_get_value (structure, "codec_data");
5520   if (value != NULL)
5521     codec_data = gst_value_get_buffer (value);
5522
5523   par_num = 1;
5524   par_den = 1;
5525   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5526       &par_den);
5527
5528   qtpad->is_out_of_order = FALSE;
5529
5530   /* bring frame numerator into a range that ensures both reasonable resolution
5531    * as well as a fair duration */
5532   qtpad->expected_sample_duration_n = framerate_num;
5533   qtpad->expected_sample_duration_d = framerate_den;
5534
5535   rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5536   if (!rate && qtmux->trak_timescale)
5537     rate = qtmux->trak_timescale;
5538   else if (!rate)
5539     rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5540
5541   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5542       rate);
5543
5544   multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5545   if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5546     GstVideoMultiviewMode mode;
5547     GstVideoMultiviewFlags flags = 0;
5548
5549     mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5550     gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5551     switch (mode) {
5552       case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5553         qtpad->trak->mdia.minf.stbl.svmi =
5554             atom_svmi_new (0,
5555             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5556         break;
5557       case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5558         qtpad->trak->mdia.minf.stbl.svmi =
5559             atom_svmi_new (1,
5560             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5561         break;
5562       case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5563         qtpad->trak->mdia.minf.stbl.svmi =
5564             atom_svmi_new (2,
5565             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5566         break;
5567       default:
5568         GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5569             multiview_mode);
5570         break;
5571     }
5572   }
5573
5574   /* set common properties */
5575   entry.width = width;
5576   entry.height = height;
5577   entry.par_n = par_num;
5578   entry.par_d = par_den;
5579   /* should be OK according to qt and iso spec, override if really needed */
5580   entry.color_table_id = -1;
5581   entry.frame_count = 1;
5582   entry.depth = 24;
5583
5584   /* sync entries by default */
5585   sync = TRUE;
5586
5587   /* now map onto a fourcc, and some extra properties */
5588   if (strcmp (mimetype, "video/x-raw") == 0) {
5589     const gchar *format;
5590     GstVideoFormat fmt;
5591     const GstVideoFormatInfo *vinfo;
5592
5593     format = gst_structure_get_string (structure, "format");
5594     fmt = gst_video_format_from_string (format);
5595     vinfo = gst_video_format_get_info (fmt);
5596
5597     switch (fmt) {
5598       case GST_VIDEO_FORMAT_UYVY:
5599         if (depth == -1)
5600           depth = 24;
5601         entry.fourcc = FOURCC_2vuy;
5602         entry.depth = depth;
5603         sync = FALSE;
5604         break;
5605       case GST_VIDEO_FORMAT_v210:
5606         if (depth == -1)
5607           depth = 24;
5608         entry.fourcc = FOURCC_v210;
5609         entry.depth = depth;
5610         sync = FALSE;
5611         break;
5612       default:
5613         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5614           entry.fourcc = FOURCC_raw_;
5615           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5616           sync = FALSE;
5617         }
5618         break;
5619     }
5620   } else if (strcmp (mimetype, "video/x-h263") == 0) {
5621     ext_atom = NULL;
5622     if (format == GST_QT_MUX_FORMAT_QT)
5623       entry.fourcc = FOURCC_h263;
5624     else
5625       entry.fourcc = FOURCC_s263;
5626     ext_atom = build_h263_extension ();
5627     if (ext_atom != NULL)
5628       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5629   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5630       strcmp (mimetype, "video/mpeg") == 0) {
5631     gint version = 0;
5632
5633     if (strcmp (mimetype, "video/x-divx") == 0) {
5634       gst_structure_get_int (structure, "divxversion", &version);
5635       version = version == 5 ? 1 : 0;
5636     } else {
5637       gst_structure_get_int (structure, "mpegversion", &version);
5638       version = version == 4 ? 1 : 0;
5639     }
5640     if (version) {
5641       entry.fourcc = FOURCC_mp4v;
5642       ext_atom =
5643           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5644           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5645           qtpad->max_bitrate);
5646       if (ext_atom != NULL)
5647         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5648       if (!codec_data)
5649         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5650             "output might not play in Apple QuickTime (try global-headers?)");
5651     }
5652   } else if (strcmp (mimetype, "video/x-h264") == 0) {
5653     if (!codec_data) {
5654       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5655       goto refuse_caps;
5656     }
5657
5658     entry.fourcc = FOURCC_avc1;
5659
5660     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5661     if (ext_atom != NULL)
5662       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5663     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5664     if (ext_atom != NULL)
5665       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5666   } else if (strcmp (mimetype, "video/x-h265") == 0) {
5667     const gchar *format;
5668
5669     if (!codec_data) {
5670       GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5671       goto refuse_caps;
5672     }
5673
5674     format = gst_structure_get_string (structure, "stream-format");
5675     if (strcmp (format, "hvc1") == 0)
5676       entry.fourcc = FOURCC_hvc1;
5677     else if (strcmp (format, "hev1") == 0)
5678       entry.fourcc = FOURCC_hev1;
5679
5680     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5681     if (ext_atom != NULL)
5682       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5683
5684     ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5685     if (ext_atom != NULL)
5686       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5687
5688   } else if (strcmp (mimetype, "video/x-svq") == 0) {
5689     gint version = 0;
5690     const GstBuffer *seqh = NULL;
5691     const GValue *seqh_value;
5692     gdouble gamma = 0;
5693
5694     gst_structure_get_int (structure, "svqversion", &version);
5695     if (version == 3) {
5696       entry.fourcc = FOURCC_SVQ3;
5697       entry.version = 3;
5698       entry.depth = 32;
5699
5700       seqh_value = gst_structure_get_value (structure, "seqh");
5701       if (seqh_value) {
5702         seqh = gst_value_get_buffer (seqh_value);
5703         ext_atom = build_SMI_atom (seqh);
5704         if (ext_atom)
5705           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5706       }
5707
5708       /* we need to add the gamma anyway because quicktime might crash
5709        * when it doesn't find it */
5710       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5711         /* it seems that using 0 here makes it ignored */
5712         gamma = 0.0;
5713       }
5714       ext_atom = build_gama_atom (gamma);
5715       if (ext_atom)
5716         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5717     } else {
5718       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5719           "a bug at http://bugzilla.gnome.org", version);
5720     }
5721   } else if (strcmp (mimetype, "video/x-dv") == 0) {
5722     gint version = 0;
5723     gboolean pal = TRUE;
5724
5725     sync = FALSE;
5726     if (framerate_num != 25 || framerate_den != 1)
5727       pal = FALSE;
5728     gst_structure_get_int (structure, "dvversion", &version);
5729     /* fall back to typical one */
5730     if (!version)
5731       version = 25;
5732     switch (version) {
5733       case 25:
5734         if (pal)
5735           entry.fourcc = FOURCC_dvcp;
5736         else
5737           entry.fourcc = FOURCC_dvc_;
5738         break;
5739       case 50:
5740         if (pal)
5741           entry.fourcc = FOURCC_dv5p;
5742         else
5743           entry.fourcc = FOURCC_dv5n;
5744         break;
5745       default:
5746         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5747         break;
5748     }
5749   } else if (strcmp (mimetype, "image/jpeg") == 0) {
5750     entry.fourcc = FOURCC_jpeg;
5751     sync = FALSE;
5752   } else if (strcmp (mimetype, "image/png") == 0) {
5753     entry.fourcc = FOURCC_png;
5754     sync = FALSE;
5755   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5756       strcmp (mimetype, "image/x-jpc") == 0) {
5757     const gchar *colorspace;
5758     const GValue *cmap_array;
5759     const GValue *cdef_array;
5760     gint ncomp = 0;
5761
5762     if (strcmp (mimetype, "image/x-jpc") == 0) {
5763       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5764     }
5765
5766     gst_structure_get_int (structure, "num-components", &ncomp);
5767     cmap_array = gst_structure_get_value (structure, "component-map");
5768     cdef_array = gst_structure_get_value (structure, "channel-definitions");
5769
5770     ext_atom = NULL;
5771     entry.fourcc = FOURCC_mjp2;
5772     sync = FALSE;
5773
5774     colorspace = gst_structure_get_string (structure, "colorspace");
5775     if (colorspace &&
5776         (ext_atom =
5777             build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5778                 cdef_array)) != NULL) {
5779       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5780
5781       ext_atom = build_jp2x_extension (codec_data);
5782       if (ext_atom)
5783         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5784     } else {
5785       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5786       goto refuse_caps;
5787     }
5788   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5789     entry.fourcc = FOURCC_vp08;
5790   } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5791     entry.fourcc = FOURCC_vp09;
5792   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5793     entry.fourcc = FOURCC_drac;
5794   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5795     guint32 fourcc = 0;
5796
5797     gst_structure_get_uint (structure, "format", &fourcc);
5798     entry.fourcc = fourcc;
5799   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5800     guint32 fourcc = 0;
5801
5802     gst_structure_get_uint (structure, "format", &fourcc);
5803     entry.fourcc = fourcc;
5804   } else if (strcmp (mimetype, "video/x-prores") == 0) {
5805     const gchar *variant;
5806
5807     variant = gst_structure_get_string (structure, "variant");
5808     if (!variant || !g_strcmp0 (variant, "standard"))
5809       entry.fourcc = FOURCC_apcn;
5810     else if (!g_strcmp0 (variant, "lt"))
5811       entry.fourcc = FOURCC_apcs;
5812     else if (!g_strcmp0 (variant, "hq"))
5813       entry.fourcc = FOURCC_apch;
5814     else if (!g_strcmp0 (variant, "proxy"))
5815       entry.fourcc = FOURCC_apco;
5816     else if (!g_strcmp0 (variant, "4444"))
5817       entry.fourcc = FOURCC_ap4h;
5818     else if (!g_strcmp0 (variant, "4444xq"))
5819       entry.fourcc = FOURCC_ap4x;
5820
5821     sync = FALSE;
5822
5823     if (!qtmux->interleave_time_set)
5824       qtmux->interleave_time = 500 * GST_MSECOND;
5825     if (!qtmux->interleave_bytes_set)
5826       qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5827   } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5828     entry.fourcc = FOURCC_cfhd;
5829     sync = FALSE;
5830   } else if (strcmp (mimetype, "video/x-av1") == 0) {
5831     gint presentation_delay;
5832     guint8 presentation_delay_byte = 0;
5833     GstBuffer *av1_codec_data;
5834
5835     if (gst_structure_get_int (structure, "presentation-delay",
5836             &presentation_delay)) {
5837       presentation_delay_byte = 1 << 5;
5838       presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
5839     }
5840
5841
5842     av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
5843     /* Fill version and 3 bytes of flags to 0 */
5844     gst_buffer_memset (av1_codec_data, 0, 0, 4);
5845     gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
5846     if (codec_data)
5847       av1_codec_data = gst_buffer_append (av1_codec_data,
5848           gst_buffer_ref ((GstBuffer *) codec_data));
5849
5850     entry.fourcc = FOURCC_av01;
5851
5852     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5853     if (ext_atom != NULL)
5854       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5855     ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
5856     if (ext_atom != NULL)
5857       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5858     gst_buffer_unref (av1_codec_data);
5859   }
5860
5861   if (!entry.fourcc)
5862     goto refuse_caps;
5863
5864   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5865       qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5866     const gchar *s;
5867     GstVideoColorimetry colorimetry;
5868
5869     s = gst_structure_get_string (structure, "colorimetry");
5870     if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5871       ext_atom =
5872           build_colr_extension (&colorimetry,
5873           qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5874       if (ext_atom)
5875         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5876     }
5877   }
5878
5879   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5880       || strcmp (mimetype, "image/x-j2c") == 0
5881       || strcmp (mimetype, "image/x-jpc") == 0) {
5882     const gchar *s;
5883     GstVideoInterlaceMode interlace_mode;
5884     GstVideoFieldOrder field_order;
5885     gint fields = -1;
5886
5887     if (strcmp (mimetype, "image/x-j2c") == 0 ||
5888         strcmp (mimetype, "image/x-jpc") == 0) {
5889
5890       fields = 1;
5891       gst_structure_get_int (structure, "fields", &fields);
5892     }
5893
5894     s = gst_structure_get_string (structure, "interlace-mode");
5895     if (s)
5896       interlace_mode = gst_video_interlace_mode_from_string (s);
5897     else
5898       interlace_mode =
5899           (fields <=
5900           1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5901           GST_VIDEO_INTERLACE_MODE_MIXED;
5902
5903     field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5904     if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5905       s = gst_structure_get_string (structure, "field-order");
5906       if (s)
5907         field_order = gst_video_field_order_from_string (s);
5908     }
5909
5910     ext_atom = build_fiel_extension (interlace_mode, field_order);
5911     if (ext_atom)
5912       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5913   }
5914
5915
5916   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5917       width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5918     /* The 'clap' extension is also defined for MP4 but inventing values in
5919      * general seems a bit tricky for this one. We only write it for
5920      * SD resolution in MOV, where it is a requirement.
5921      * The same goes for the 'tapt' extension, just that it is not defined for
5922      * MP4 and only for MOV
5923      */
5924     gint dar_num, dar_den;
5925     gint clef_width, clef_height, prof_width;
5926     gint clap_width_n, clap_width_d, clap_height;
5927     gint cdiv;
5928     double approx_dar;
5929
5930     /* First, guess display aspect ratio based on pixel aspect ratio,
5931      * width and height. We assume that display aspect ratio is either
5932      * 4:3 or 16:9
5933      */
5934     approx_dar = (gdouble) (width * par_num) / (height * par_den);
5935     if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5936       dar_num = 4;
5937       dar_den = 3;
5938     } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5939       dar_num = 16;
5940       dar_den = 9;
5941     } else {
5942       dar_num = width * par_num;
5943       dar_den = height * par_den;
5944       cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5945       dar_num /= cdiv;
5946       dar_den /= cdiv;
5947     }
5948
5949     /* Then, calculate clean-aperture values (clap and clef)
5950      * using the guessed DAR.
5951      */
5952     clef_height = clap_height = (height == 486 ? 480 : height);
5953     clef_width = gst_util_uint64_scale (clef_height,
5954         dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5955     prof_width = gst_util_uint64_scale (width,
5956         par_num * G_GUINT64_CONSTANT (65536), par_den);
5957     clap_width_n = clap_height * dar_num * par_den;
5958     clap_width_d = dar_den * par_num;
5959     cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5960     clap_width_n /= cdiv;
5961     clap_width_d /= cdiv;
5962
5963     ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5964         height << 16, width << 16, height << 16);
5965     qtpad->trak->tapt = ext_atom;
5966
5967     ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5968         clap_height, 1, 0, 1, 0, 1);
5969     if (ext_atom)
5970       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5971   }
5972
5973   /* ok, set the pad info accordingly */
5974   qtpad->fourcc = entry.fourcc;
5975   qtpad->sync = sync;
5976   qtpad->trak_ste =
5977       (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5978       qtmux->context, &entry, rate, ext_atom_list);
5979   if (strcmp (mimetype, "video/x-prores") == 0) {
5980     SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5981     const gchar *compressor = NULL;
5982     mp4v->spatial_quality = 0x3FF;
5983     mp4v->temporal_quality = 0;
5984     mp4v->vendor = FOURCC_appl;
5985     mp4v->horizontal_resolution = 72 << 16;
5986     mp4v->vertical_resolution = 72 << 16;
5987     mp4v->depth = (entry.fourcc == FOURCC_ap4h
5988         || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5989
5990     /* Set compressor name, required by some software */
5991     switch (entry.fourcc) {
5992       case FOURCC_apcn:
5993         compressor = "Apple ProRes 422";
5994         break;
5995       case FOURCC_apcs:
5996         compressor = "Apple ProRes 422 LT";
5997         break;
5998       case FOURCC_apch:
5999         compressor = "Apple ProRes 422 HQ";
6000         break;
6001       case FOURCC_apco:
6002         compressor = "Apple ProRes 422 Proxy";
6003         break;
6004       case FOURCC_ap4h:
6005         compressor = "Apple ProRes 4444";
6006         break;
6007       case FOURCC_ap4x:
6008         compressor = "Apple ProRes 4444 XQ";
6009         break;
6010     }
6011     if (compressor) {
6012       strcpy ((gchar *) mp4v->compressor + 1, compressor);
6013       mp4v->compressor[0] = strlen (compressor);
6014     }
6015   }
6016
6017   gst_object_unref (qtmux);
6018   return TRUE;
6019
6020   /* ERRORS */
6021 refuse_caps:
6022   {
6023     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6024         GST_PAD_NAME (pad), caps);
6025     gst_object_unref (qtmux);
6026     return FALSE;
6027   }
6028 }
6029
6030 static gboolean
6031 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6032 {
6033   GstPad *pad = qtpad->collect.pad;
6034   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6035   GstStructure *structure;
6036   SubtitleSampleEntry entry = { 0, };
6037
6038   if (qtpad->fourcc)
6039     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6040
6041   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6042       GST_DEBUG_PAD_NAME (pad), caps);
6043
6044   /* subtitles default */
6045   subtitle_sample_entry_init (&entry);
6046   qtpad->is_out_of_order = FALSE;
6047   qtpad->sync = FALSE;
6048   qtpad->sparse = TRUE;
6049   qtpad->prepare_buf_func = NULL;
6050
6051   structure = gst_caps_get_structure (caps, 0);
6052
6053   if (gst_structure_has_name (structure, "text/x-raw")) {
6054     const gchar *format = gst_structure_get_string (structure, "format");
6055     if (format && strcmp (format, "utf8") == 0) {
6056       entry.fourcc = FOURCC_tx3g;
6057       qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6058       qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6059     }
6060   }
6061
6062   if (!entry.fourcc)
6063     goto refuse_caps;
6064
6065   qtpad->fourcc = entry.fourcc;
6066   qtpad->trak_ste =
6067       (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6068       qtmux->context, &entry);
6069
6070   gst_object_unref (qtmux);
6071   return TRUE;
6072
6073   /* ERRORS */
6074 refuse_caps:
6075   {
6076     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6077         GST_PAD_NAME (pad), caps);
6078     gst_object_unref (qtmux);
6079     return FALSE;
6080   }
6081 }
6082
6083 static gboolean
6084 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6085 {
6086   GstPad *pad = qtpad->collect.pad;
6087   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6088   GstStructure *structure;
6089   guint32 fourcc_entry;
6090   guint32 timescale;
6091
6092   if (qtpad->fourcc)
6093     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6094
6095   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6096       GST_DEBUG_PAD_NAME (pad), caps);
6097
6098   /* captions default */
6099   qtpad->is_out_of_order = FALSE;
6100   qtpad->sync = FALSE;
6101   qtpad->sparse = TRUE;
6102   /* Closed caption data are within atoms */
6103   qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6104
6105   structure = gst_caps_get_structure (caps, 0);
6106
6107   /* We know we only handle 608,format=cc_data and 708,format=cdp */
6108   if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6109     fourcc_entry = FOURCC_c608;
6110   } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6111     fourcc_entry = FOURCC_c708;
6112   } else
6113     goto refuse_caps;
6114
6115   /* FIXME: Get the timescale from the video track ? */
6116   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6117   if (!timescale && qtmux->trak_timescale)
6118     timescale = qtmux->trak_timescale;
6119   else if (!timescale)
6120     timescale = 30000;
6121
6122   qtpad->fourcc = fourcc_entry;
6123   qtpad->trak_ste =
6124       (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6125       qtmux->context, timescale, fourcc_entry);
6126
6127   /* Initialize caption track language code to 0 unless something else is
6128    * specified. Without this, Final Cut considers it "non-standard"
6129    */
6130   qtpad->trak->mdia.mdhd.language_code = 0;
6131
6132   gst_object_unref (qtmux);
6133   return TRUE;
6134
6135   /* ERRORS */
6136 refuse_caps:
6137   {
6138     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6139         GST_PAD_NAME (pad), caps);
6140     gst_object_unref (qtmux);
6141     return FALSE;
6142   }
6143 }
6144
6145 static gboolean
6146 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6147     GstEvent * event, gpointer user_data)
6148 {
6149   GstQTMux *qtmux;
6150   guint32 avg_bitrate = 0, max_bitrate = 0;
6151   GstPad *pad = data->pad;
6152   gboolean ret = TRUE;
6153
6154   qtmux = GST_QT_MUX_CAST (user_data);
6155   switch (GST_EVENT_TYPE (event)) {
6156     case GST_EVENT_CAPS:
6157     {
6158       GstCaps *caps;
6159       GstQTPad *collect_pad;
6160
6161       gst_event_parse_caps (event, &caps);
6162
6163       /* find stream data */
6164       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6165       g_assert (collect_pad);
6166       g_assert (collect_pad->set_caps);
6167
6168       ret = collect_pad->set_caps (collect_pad, caps);
6169       gst_event_unref (event);
6170       event = NULL;
6171       break;
6172     }
6173     case GST_EVENT_TAG:{
6174       GstTagList *list;
6175       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6176       GstTagMergeMode mode;
6177       gchar *code;
6178       GstQTPad *collect_pad;
6179
6180       GST_OBJECT_LOCK (qtmux);
6181       mode = gst_tag_setter_get_tag_merge_mode (setter);
6182       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6183
6184       gst_event_parse_tag (event, &list);
6185       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6186           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6187
6188       if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6189         gst_tag_setter_merge_tags (setter, list, mode);
6190         qtmux->tags_changed = TRUE;
6191       } else {
6192         if (!collect_pad->tags)
6193           collect_pad->tags = gst_tag_list_new_empty ();
6194         gst_tag_list_insert (collect_pad->tags, list, mode);
6195         collect_pad->tags_changed = TRUE;
6196       }
6197       GST_OBJECT_UNLOCK (qtmux);
6198
6199       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6200           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6201         GstQTPad *qtpad = gst_pad_get_element_private (pad);
6202         g_assert (qtpad);
6203
6204         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6205           qtpad->avg_bitrate = avg_bitrate;
6206         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6207           qtpad->max_bitrate = max_bitrate;
6208       }
6209
6210       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6211         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6212         if (iso_code) {
6213           GstQTPad *qtpad = gst_pad_get_element_private (pad);
6214           g_assert (qtpad);
6215           if (qtpad->trak) {
6216             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6217             qtpad->trak->mdia.mdhd.language_code = language_code (iso_code);
6218           }
6219         }
6220         g_free (code);
6221       }
6222
6223       gst_event_unref (event);
6224       event = NULL;
6225       ret = TRUE;
6226       break;
6227     }
6228     default:
6229       break;
6230   }
6231
6232   if (event != NULL)
6233     return gst_collect_pads_event_default (pads, data, event, FALSE);
6234
6235   return ret;
6236 }
6237
6238 static void
6239 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6240 {
6241   GstQTMux *mux = GST_QT_MUX_CAST (element);
6242   GSList *walk;
6243
6244   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6245
6246   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6247     GstQTPad *qtpad = (GstQTPad *) walk->data;
6248     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6249     if (qtpad->collect.pad == pad) {
6250       /* this is it, remove */
6251       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6252       gst_element_remove_pad (element, pad);
6253       break;
6254     }
6255   }
6256
6257   if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6258     mux->current_pad = NULL;
6259     mux->current_chunk_size = 0;
6260     mux->current_chunk_duration = 0;
6261   }
6262
6263   gst_collect_pads_remove_pad (mux->collect, pad);
6264
6265   if (mux->sinkpads == NULL) {
6266     /* No more outstanding request pads, reset our counters */
6267     mux->video_pads = 0;
6268     mux->audio_pads = 0;
6269     mux->subtitle_pads = 0;
6270   }
6271 }
6272
6273 static GstPad *
6274 gst_qt_mux_request_new_pad (GstElement * element,
6275     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6276 {
6277   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6278   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6279   GstQTPad *collect_pad;
6280   GstPad *newpad;
6281   GstQTPadSetCapsFunc setcaps_func;
6282   gchar *name;
6283   gint pad_id;
6284   gboolean lock = TRUE;
6285
6286   if (templ->direction != GST_PAD_SINK)
6287     goto wrong_direction;
6288
6289   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6290     goto too_late;
6291
6292   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6293     setcaps_func = gst_qt_mux_audio_sink_set_caps;
6294     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6295       name = g_strdup (req_name);
6296     } else {
6297       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6298     }
6299   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6300     setcaps_func = gst_qt_mux_video_sink_set_caps;
6301     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6302       name = g_strdup (req_name);
6303     } else {
6304       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6305     }
6306   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6307     setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6308     if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6309       name = g_strdup (req_name);
6310     } else {
6311       name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6312     }
6313     lock = FALSE;
6314   } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6315     setcaps_func = gst_qt_mux_caption_sink_set_caps;
6316     if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6317       name = g_strdup (req_name);
6318     } else {
6319       name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6320     }
6321     lock = FALSE;
6322   } else
6323     goto wrong_template;
6324
6325   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6326
6327   /* create pad and add to collections */
6328   newpad =
6329       g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6330       templ->direction, "template", templ, NULL);
6331   g_free (name);
6332   collect_pad = (GstQTPad *)
6333       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6334       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6335   /* set up pad */
6336   gst_qt_mux_pad_reset (collect_pad);
6337   collect_pad->trak = atom_trak_new (qtmux->context);
6338   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6339
6340   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6341
6342   /* set up pad functions */
6343   collect_pad->set_caps = setcaps_func;
6344
6345   gst_pad_set_active (newpad, TRUE);
6346   gst_element_add_pad (element, newpad);
6347
6348   return newpad;
6349
6350   /* ERRORS */
6351 wrong_direction:
6352   {
6353     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6354     return NULL;
6355   }
6356 too_late:
6357   {
6358     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6359     return NULL;
6360   }
6361 wrong_template:
6362   {
6363     GST_WARNING_OBJECT (qtmux, "This is not our template!");
6364     return NULL;
6365   }
6366 }
6367
6368 static void
6369 gst_qt_mux_get_property (GObject * object,
6370     guint prop_id, GValue * value, GParamSpec * pspec)
6371 {
6372   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6373
6374   GST_OBJECT_LOCK (qtmux);
6375   switch (prop_id) {
6376     case PROP_MOVIE_TIMESCALE:
6377       g_value_set_uint (value, qtmux->timescale);
6378       break;
6379     case PROP_TRAK_TIMESCALE:
6380       g_value_set_uint (value, qtmux->trak_timescale);
6381       break;
6382     case PROP_DO_CTTS:
6383       g_value_set_boolean (value, qtmux->guess_pts);
6384       break;
6385 #ifndef GST_REMOVE_DEPRECATED
6386     case PROP_DTS_METHOD:
6387       g_value_set_enum (value, qtmux->dts_method);
6388       break;
6389 #endif
6390     case PROP_FAST_START:
6391       g_value_set_boolean (value, qtmux->fast_start);
6392       break;
6393     case PROP_FAST_START_TEMP_FILE:
6394       g_value_set_string (value, qtmux->fast_start_file_path);
6395       break;
6396     case PROP_MOOV_RECOV_FILE:
6397       g_value_set_string (value, qtmux->moov_recov_file_path);
6398       break;
6399     case PROP_FRAGMENT_DURATION:
6400       g_value_set_uint (value, qtmux->fragment_duration);
6401       break;
6402     case PROP_STREAMABLE:
6403       g_value_set_boolean (value, qtmux->streamable);
6404       break;
6405     case PROP_RESERVED_MAX_DURATION:
6406       g_value_set_uint64 (value, qtmux->reserved_max_duration);
6407       break;
6408     case PROP_RESERVED_DURATION_REMAINING:
6409       if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6410         g_value_set_uint64 (value, qtmux->reserved_max_duration);
6411       else {
6412         GstClockTime remaining = qtmux->reserved_duration_remaining;
6413
6414         /* Report the remaining space as the calculated remaining, minus
6415          * however much we've muxed since the last update */
6416         if (remaining > qtmux->muxed_since_last_update)
6417           remaining -= qtmux->muxed_since_last_update;
6418         else
6419           remaining = 0;
6420         GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6421             G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6422             remaining, qtmux->reserved_duration_remaining,
6423             qtmux->muxed_since_last_update);
6424         g_value_set_uint64 (value, remaining);
6425       }
6426       break;
6427     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6428       g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6429       break;
6430     case PROP_RESERVED_BYTES_PER_SEC:
6431       g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6432       break;
6433     case PROP_RESERVED_PREFILL:
6434       g_value_set_boolean (value, qtmux->reserved_prefill);
6435       break;
6436     case PROP_INTERLEAVE_BYTES:
6437       g_value_set_uint64 (value, qtmux->interleave_bytes);
6438       break;
6439     case PROP_INTERLEAVE_TIME:
6440       g_value_set_uint64 (value, qtmux->interleave_time);
6441       break;
6442     case PROP_MAX_RAW_AUDIO_DRIFT:
6443       g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6444       break;
6445     default:
6446       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6447       break;
6448   }
6449   GST_OBJECT_UNLOCK (qtmux);
6450 }
6451
6452 static void
6453 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6454 {
6455   gchar *tmp;
6456
6457   g_free (qtmux->fast_start_file_path);
6458   qtmux->fast_start_file_path = NULL;
6459
6460   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6461   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6462   g_free (tmp);
6463 }
6464
6465 static void
6466 gst_qt_mux_set_property (GObject * object,
6467     guint prop_id, const GValue * value, GParamSpec * pspec)
6468 {
6469   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6470
6471   GST_OBJECT_LOCK (qtmux);
6472   switch (prop_id) {
6473     case PROP_MOVIE_TIMESCALE:
6474       qtmux->timescale = g_value_get_uint (value);
6475       break;
6476     case PROP_TRAK_TIMESCALE:
6477       qtmux->trak_timescale = g_value_get_uint (value);
6478       break;
6479     case PROP_DO_CTTS:
6480       qtmux->guess_pts = g_value_get_boolean (value);
6481       break;
6482 #ifndef GST_REMOVE_DEPRECATED
6483     case PROP_DTS_METHOD:
6484       qtmux->dts_method = g_value_get_enum (value);
6485       break;
6486 #endif
6487     case PROP_FAST_START:
6488       qtmux->fast_start = g_value_get_boolean (value);
6489       break;
6490     case PROP_FAST_START_TEMP_FILE:
6491       g_free (qtmux->fast_start_file_path);
6492       qtmux->fast_start_file_path = g_value_dup_string (value);
6493       /* NULL means to generate a random one */
6494       if (!qtmux->fast_start_file_path) {
6495         gst_qt_mux_generate_fast_start_file_path (qtmux);
6496       }
6497       break;
6498     case PROP_MOOV_RECOV_FILE:
6499       g_free (qtmux->moov_recov_file_path);
6500       qtmux->moov_recov_file_path = g_value_dup_string (value);
6501       break;
6502     case PROP_FRAGMENT_DURATION:
6503       qtmux->fragment_duration = g_value_get_uint (value);
6504       break;
6505     case PROP_STREAMABLE:{
6506       GstQTMuxClass *qtmux_klass =
6507           (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6508       if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6509         qtmux->streamable = g_value_get_boolean (value);
6510       }
6511       break;
6512     }
6513     case PROP_RESERVED_MAX_DURATION:
6514       qtmux->reserved_max_duration = g_value_get_uint64 (value);
6515       break;
6516     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6517       qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6518       break;
6519     case PROP_RESERVED_BYTES_PER_SEC:
6520       qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6521       break;
6522     case PROP_RESERVED_PREFILL:
6523       qtmux->reserved_prefill = g_value_get_boolean (value);
6524       break;
6525     case PROP_INTERLEAVE_BYTES:
6526       qtmux->interleave_bytes = g_value_get_uint64 (value);
6527       qtmux->interleave_bytes_set = TRUE;
6528       break;
6529     case PROP_INTERLEAVE_TIME:
6530       qtmux->interleave_time = g_value_get_uint64 (value);
6531       qtmux->interleave_time_set = TRUE;
6532       break;
6533     case PROP_MAX_RAW_AUDIO_DRIFT:
6534       qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6535       break;
6536     default:
6537       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6538       break;
6539   }
6540   GST_OBJECT_UNLOCK (qtmux);
6541 }
6542
6543 static GstStateChangeReturn
6544 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6545 {
6546   GstStateChangeReturn ret;
6547   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6548
6549   switch (transition) {
6550     case GST_STATE_CHANGE_NULL_TO_READY:
6551       break;
6552     case GST_STATE_CHANGE_READY_TO_PAUSED:
6553       gst_collect_pads_start (qtmux->collect);
6554       qtmux->state = GST_QT_MUX_STATE_STARTED;
6555       break;
6556     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6557       break;
6558     case GST_STATE_CHANGE_PAUSED_TO_READY:
6559       gst_collect_pads_stop (qtmux->collect);
6560       break;
6561     default:
6562       break;
6563   }
6564
6565   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6566
6567   switch (transition) {
6568     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6569       break;
6570     case GST_STATE_CHANGE_PAUSED_TO_READY:
6571       gst_qt_mux_reset (qtmux, TRUE);
6572       break;
6573     case GST_STATE_CHANGE_READY_TO_NULL:
6574       break;
6575     default:
6576       break;
6577   }
6578
6579   return ret;
6580 }
6581
6582 gboolean
6583 gst_qt_mux_register (GstPlugin * plugin)
6584 {
6585   GTypeInfo typeinfo = {
6586     sizeof (GstQTMuxClass),
6587     (GBaseInitFunc) gst_qt_mux_base_init,
6588     NULL,
6589     (GClassInitFunc) gst_qt_mux_class_init,
6590     NULL,
6591     NULL,
6592     sizeof (GstQTMux),
6593     0,
6594     (GInstanceInitFunc) gst_qt_mux_init,
6595   };
6596   static const GInterfaceInfo tag_setter_info = {
6597     NULL, NULL, NULL
6598   };
6599   static const GInterfaceInfo tag_xmp_writer_info = {
6600     NULL, NULL, NULL
6601   };
6602   static const GInterfaceInfo preset_info = {
6603     NULL, NULL, NULL
6604   };
6605   GType type;
6606   GstQTMuxFormat format;
6607   GstQTMuxClassParams *params;
6608   guint i = 0;
6609
6610   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6611
6612   GST_LOG ("Registering muxers");
6613
6614   while (TRUE) {
6615     GstQTMuxFormatProp *prop;
6616     GstCaps *subtitle_caps, *caption_caps;
6617
6618     prop = &gst_qt_mux_format_list[i];
6619     format = prop->format;
6620     if (format == GST_QT_MUX_FORMAT_NONE)
6621       break;
6622
6623     /* create a cache for these properties */
6624     params = g_new0 (GstQTMuxClassParams, 1);
6625     params->prop = prop;
6626     params->src_caps = gst_static_caps_get (&prop->src_caps);
6627     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6628     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6629     subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6630     if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6631       params->subtitle_sink_caps = subtitle_caps;
6632     } else {
6633       gst_caps_unref (subtitle_caps);
6634     }
6635     caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6636     if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6637       params->caption_sink_caps = caption_caps;
6638     } else {
6639       gst_caps_unref (caption_caps);
6640     }
6641
6642     /* create the type now */
6643     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6644         0);
6645     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6646     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6647     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6648         &tag_xmp_writer_info);
6649     g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6650
6651     if (!gst_element_register (plugin, prop->name, prop->rank, type))
6652       return FALSE;
6653
6654     i++;
6655   }
6656
6657   GST_LOG ("Finished registering muxers");
6658
6659   /* FIXME: ideally classification tag should be added and
6660      registered in gstreamer core gsttaglist
6661    */
6662
6663   GST_LOG ("Registering tags");
6664
6665   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6666       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6667       gst_tag_merge_use_first);
6668
6669   GST_LOG ("Finished registering tags");
6670
6671   return TRUE;
6672 }