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