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