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