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