a3eb031666045b1ca4234ec5dc38a9313c0c7abe
[platform/upstream/gstreamer.git] / gst / isomp4 / gstqtmux.c
1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4  * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5  * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6  * Contact: Stefan Kost <stefan.kost@nokia.com>
7
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /*
24  * Unless otherwise indicated, Source Code is licensed under MIT license.
25  * See further explanation attached in License Statement (distributed in the file
26  * LICENSE).
27  *
28  * Permission is hereby granted, free of charge, to any person obtaining a copy of
29  * this software and associated documentation files (the "Software"), to deal in
30  * the Software without restriction, including without limitation the rights to
31  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32  * of the Software, and to permit persons to whom the Software is furnished to do
33  * so, subject to the following conditions:
34  *
35  * The above copyright notice and this permission notice shall be included in all
36  * copies or substantial portions of the Software.
37  *
38  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44  * SOFTWARE.
45  */
46
47
48 /**
49  * SECTION:element-qtmux
50  * @short_description: Muxer for quicktime(.mov) files
51  *
52  * This element merges streams (audio and video) into QuickTime(.mov) files.
53  *
54  * The following background intends to explain why various similar muxers
55  * are present in this plugin.
56  *
57  * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58  * QuickTime file format specification</ulink> served as basis for the MP4 file
59  * format specification (mp4mux), and as such the QuickTime file structure is
60  * nearly identical to the so-called ISO Base Media file format defined in
61  * ISO 14496-12 (except for some media specific parts).
62  * In turn, the latter ISO Base Media format was further specialized as a
63  * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64  * and in various 3GPP(2) specs (gppmux).
65  * The fragmented file features defined (only) in ISO Base Media are used by
66  * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
67  *
68  * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale) allow
69  * adjusting some technical parameters, which might be useful in (rare) cases to
70  * resolve compatibility issues in some situations.
71  *
72  * Some other properties influence the result more fundamentally.
73  * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
74  * file, somewhat contrary to this usually being called "the header".
75  * However, a #GstQTMux:faststart file will (with some effort) arrange this to
76  * be located near start of the file, which then allows it e.g. to be played
77  * while downloading. Alternatively, rather than having one chunk of metadata at
78  * start (or end), there can be some metadata at start and most of the other
79  * data can be spread out into fragments of #GstQTMux:fragment-duration.
80  * If such fragmented layout is intended for streaming purposes, then
81  * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
82  * file).
83  *
84  * When the maximum duration to be recorded can be known in advance, #GstQTMux
85  * also supports a 'Robust Muxing' mode. In robust muxing mode,  space for the
86  * headers are reserved at the start of muxing, and rewritten at a configurable
87  * interval, so that the output file is always playable, even if the recording
88  * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
89  * output, such as filesink, because it needs to rewrite the start of the file.
90  *
91  * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
92  * and #GstQTMux::reserved-max-duration property. Also present is the
93  * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
94  * for some reason the default is not large enough and the initial reserved
95  * space for headers is too small. Applications can monitor the
96  * #GstQTMux::reserved-duration-remaining property to see how close to full
97  * the reserved space is becoming.
98  *
99  * <refsect2>
100  * <title>Example pipelines</title>
101  * |[
102  * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
103  * ]|
104  * Records a video stream captured from a v4l2 device and muxes it into a qt file.
105  * </refsect2>
106  */
107
108 /*
109  * Based on avimux
110  */
111
112 #ifdef HAVE_CONFIG_H
113 #include "config.h"
114 #endif
115
116 #include <glib/gstdio.h>
117
118 #include <gst/gst.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/base/gstbytereader.h>
121 #include <gst/base/gstbitreader.h>
122 #include <gst/audio/audio.h>
123 #include <gst/video/video.h>
124 #include <gst/tag/tag.h>
125 #include <gst/pbutils/pbutils.h>
126
127 #include <sys/types.h>
128 #ifdef G_OS_WIN32
129 #include <io.h>                 /* lseek, open, close, read */
130 #undef lseek
131 #define lseek _lseeki64
132 #undef off_t
133 #define off_t guint64
134 #endif
135
136 #ifdef _MSC_VER
137 #define ftruncate g_win32_ftruncate
138 #endif
139
140 #ifdef HAVE_UNISTD_H
141 #  include <unistd.h>
142 #endif
143
144 #include "gstqtmux.h"
145
146 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
147 #define GST_CAT_DEFAULT gst_qt_mux_debug
148
149 /* Hacker notes.
150  *
151  * The basic building blocks of MP4 files are:
152  *  - an 'ftyp' box at the very start
153  *  - an 'mdat' box which contains the raw audio/video/subtitle data;
154  *    this is just a bunch of bytes, completely unframed and possibly
155  *    unordered with no additional meta-information
156  *  - a 'moov' box that contains information about the different streams
157  *    and what they contain, as well as sample tables for each stream
158  *    that tell the demuxer where in the mdat box each buffer/sample is
159  *    and what its duration/timestamp etc. is, and whether it's a
160  *    keyframe etc.
161  * Additionally, fragmented MP4 works by writing chunks of data in
162  * pairs of 'moof' and 'mdat' boxes:
163  *  - 'moof' boxes, header preceding each mdat fragment describing the
164  *    contents, like a moov but only for that fragment.
165  *  - a 'mfra' box for Fragmented MP4, which is written at the end and
166  *    contains a summary of all fragments and seek tables.
167  *
168  * Currently mp4mux can work in 4 different modes / generate 4 types
169  * of output files/streams:
170  *
171  * - Normal mp4: mp4mux will write a little ftyp identifier at the
172  *   beginning, then start an mdat box into which it will write all the
173  *   sample data. At EOS it will then write the moov header with track
174  *   headers and sample tables at the end of the file, and rewrite the
175  *   start of the file to fix up the mdat box size at the beginning.
176  *   It has to wait for EOS to write the moov (which includes the
177  *   sample tables) because it doesn't know how much space those
178  *   tables will be. The output downstream must be seekable to rewrite
179  *   the mdat box at EOS.
180  *
181  * - Fragmented mp4: moov header with track headers at start
182  *   but no sample table, followed by N fragments, each containing
183  *   track headers with sample tables followed by some data. Downstream
184  *   does not need to be seekable if the 'streamable' flag is TRUE,
185  *   as the final mfra and total duration will be omitted.
186  *
187  * - Fast-start mp4: the goal here is to create a file where the moov
188  *   headers are at the beginning; what mp4mux will do is write all
189  *   sample data into a temp file and build moov header plus sample
190  *   tables in memory and then when EOS comes, it will push out the
191  *   moov header plus sample tables at the beginning, followed by the
192  *   mdat sample data at the end which is read in from the temp file
193  *   Files created in this mode are better for streaming over the
194  *   network, since the client doesn't have to seek to the end of the
195  *   file to get the headers, but it requires copying all sample data
196  *   out of the temp file at EOS, which can be expensive. Downstream does
197  *   not need to be seekable, because of the use of the temp file.
198  *
199  * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
200  *   and reserved-moov-update-period properties to reserve free space
201  *   at the start of the file and periodically write the MOOV atom out
202  *   to it. That means that killing the muxing at any point still
203  *   results in a playable file, at the cost of wasting some amount of
204  *   free space at the start of file. The approximate recording duration
205  *   has to be known in advance to estimate how much free space to reserve
206  *   for the moov, and the downstream must be seekable.
207  *   If the moov header grows larger than the reserved space, an error
208  *   is generated - so it's better to over-estimate the amount of space
209  *   to reserve. To ensure the file is playable at any point, the moov
210  *   is updated using a 'ping-pong' strategy, so the output is never in
211  *   an invalid state.
212  */
213
214 #ifndef GST_REMOVE_DEPRECATED
215 enum
216 {
217   DTS_METHOD_DD,
218   DTS_METHOD_REORDER,
219   DTS_METHOD_ASC
220 };
221
222 static GType
223 gst_qt_mux_dts_method_get_type (void)
224 {
225   static GType gst_qt_mux_dts_method = 0;
226
227   if (!gst_qt_mux_dts_method) {
228     static const GEnumValue dts_methods[] = {
229       {DTS_METHOD_DD, "delta/duration", "dd"},
230       {DTS_METHOD_REORDER, "reorder", "reorder"},
231       {DTS_METHOD_ASC, "ascending", "asc"},
232       {0, NULL, NULL},
233     };
234
235     gst_qt_mux_dts_method =
236         g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
237   }
238
239   return gst_qt_mux_dts_method;
240 }
241
242 #define GST_TYPE_QT_MUX_DTS_METHOD \
243   (gst_qt_mux_dts_method_get_type ())
244 #endif
245
246 /* QTMux signals and args */
247 enum
248 {
249   /* FILL ME */
250   LAST_SIGNAL
251 };
252
253 enum
254 {
255   PROP_0,
256   PROP_MOVIE_TIMESCALE,
257   PROP_TRAK_TIMESCALE,
258   PROP_FAST_START,
259   PROP_FAST_START_TEMP_FILE,
260   PROP_MOOV_RECOV_FILE,
261   PROP_FRAGMENT_DURATION,
262   PROP_STREAMABLE,
263   PROP_RESERVED_MAX_DURATION,
264   PROP_RESERVED_DURATION_REMAINING,
265   PROP_RESERVED_MOOV_UPDATE_PERIOD,
266   PROP_RESERVED_BYTES_PER_SEC,
267 #ifndef GST_REMOVE_DEPRECATED
268   PROP_DTS_METHOD,
269 #endif
270   PROP_DO_CTTS,
271   PROP_INTERLEAVE_BYTES,
272   PROP_INTERLEAVE_TIME,
273 };
274
275 /* some spare for header size as well */
276 #define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)
277
278 #define DEFAULT_MOVIE_TIMESCALE         0
279 #define DEFAULT_TRAK_TIMESCALE          0
280 #define DEFAULT_DO_CTTS                 TRUE
281 #define DEFAULT_FAST_START              FALSE
282 #define DEFAULT_FAST_START_TEMP_FILE    NULL
283 #define DEFAULT_MOOV_RECOV_FILE         NULL
284 #define DEFAULT_FRAGMENT_DURATION       0
285 #define DEFAULT_STREAMABLE              TRUE
286 #ifndef GST_REMOVE_DEPRECATED
287 #define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
288 #endif
289 #define DEFAULT_RESERVED_MAX_DURATION   GST_CLOCK_TIME_NONE
290 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD   GST_CLOCK_TIME_NONE
291 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
292 #define DEFAULT_INTERLEAVE_BYTES 0
293 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
294
295 static void gst_qt_mux_finalize (GObject * object);
296
297 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
298     GstStateChange transition);
299
300 /* property functions */
301 static void gst_qt_mux_set_property (GObject * object,
302     guint prop_id, const GValue * value, GParamSpec * pspec);
303 static void gst_qt_mux_get_property (GObject * object,
304     guint prop_id, GValue * value, GParamSpec * pspec);
305
306 /* pad functions */
307 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
308     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
309 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
310
311 /* event */
312 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
313     GstCollectData * data, GstEvent * event, gpointer user_data);
314
315 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
316     gpointer user_data);
317 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
318     GstBuffer * buf);
319
320 static GstFlowReturn
321 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
322
323 static GstElementClass *parent_class = NULL;
324
325 static void
326 gst_qt_mux_base_init (gpointer g_class)
327 {
328   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
329   GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
330   GstQTMuxClassParams *params;
331   GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
332   GstPadTemplate *srctempl;
333   gchar *longname, *description;
334
335   params =
336       (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
337       GST_QT_MUX_PARAMS_QDATA);
338   g_assert (params != NULL);
339
340   /* construct the element details struct */
341   longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
342   description = g_strdup_printf ("Multiplex audio and video into a %s file",
343       params->prop->long_name);
344   gst_element_class_set_static_metadata (element_class, longname,
345       "Codec/Muxer", description,
346       "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
347   g_free (longname);
348   g_free (description);
349
350   /* pad templates */
351   srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
352       GST_PAD_ALWAYS, params->src_caps);
353   gst_element_class_add_pad_template (element_class, srctempl);
354
355   if (params->audio_sink_caps) {
356     audiosinktempl = gst_pad_template_new ("audio_%u",
357         GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
358     gst_element_class_add_pad_template (element_class, audiosinktempl);
359   }
360
361   if (params->video_sink_caps) {
362     videosinktempl = gst_pad_template_new ("video_%u",
363         GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
364     gst_element_class_add_pad_template (element_class, videosinktempl);
365   }
366
367   if (params->subtitle_sink_caps) {
368     subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
369         GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
370     gst_element_class_add_pad_template (element_class, subtitlesinktempl);
371   }
372
373   klass->format = params->prop->format;
374 }
375
376 static void
377 gst_qt_mux_class_init (GstQTMuxClass * klass)
378 {
379   GObjectClass *gobject_class;
380   GstElementClass *gstelement_class;
381   GParamFlags streamable_flags;
382   const gchar *streamable_desc;
383   gboolean streamable;
384 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
385   "be streamed and hence no indexes written or duration written."
386
387   gobject_class = (GObjectClass *) klass;
388   gstelement_class = (GstElementClass *) klass;
389
390   parent_class = g_type_class_peek_parent (klass);
391
392   gobject_class->finalize = gst_qt_mux_finalize;
393   gobject_class->get_property = gst_qt_mux_get_property;
394   gobject_class->set_property = gst_qt_mux_set_property;
395
396   streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
397   if (klass->format == GST_QT_MUX_FORMAT_ISML) {
398     streamable_desc = STREAMABLE_DESC;
399     streamable = DEFAULT_STREAMABLE;
400   } else {
401     streamable_desc =
402         STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
403     streamable_flags |= G_PARAM_DEPRECATED;
404     streamable = FALSE;
405   }
406
407   g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
408       g_param_spec_uint ("movie-timescale", "Movie timescale",
409           "Timescale to use in the movie (units per second, 0 == default)",
410           0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
411           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
412   g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
413       g_param_spec_uint ("trak-timescale", "Track timescale",
414           "Timescale to use for the tracks (units per second, 0 is automatic)",
415           0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
416           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
417   g_object_class_install_property (gobject_class, PROP_DO_CTTS,
418       g_param_spec_boolean ("presentation-time",
419           "Include presentation-time info",
420           "Calculate and include presentation/composition time "
421           "(in addition to decoding time)", DEFAULT_DO_CTTS,
422           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
423 #ifndef GST_REMOVE_DEPRECATED
424   g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
425       g_param_spec_enum ("dts-method", "dts-method",
426           "Method to determine DTS time (DEPRECATED)",
427           GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
428           G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
429           G_PARAM_STATIC_STRINGS));
430 #endif
431   g_object_class_install_property (gobject_class, PROP_FAST_START,
432       g_param_spec_boolean ("faststart", "Format file to faststart",
433           "If the file should be formatted for faststart (headers first)",
434           DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435   g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
436       g_param_spec_string ("faststart-file", "File to use for storing buffers",
437           "File that will be used temporarily to store data from the stream "
438           "when creating a faststart file. If null a filepath will be "
439           "created automatically", DEFAULT_FAST_START_TEMP_FILE,
440           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
441   g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
442       g_param_spec_string ("moov-recovery-file",
443           "File to store data for posterior moov atom recovery",
444           "File to be used to store "
445           "data for moov atom making movie file recovery possible in case "
446           "of a crash during muxing. Null for disabled. (Experimental)",
447           DEFAULT_MOOV_RECOV_FILE,
448           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
449   g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
450       g_param_spec_uint ("fragment-duration", "Fragment duration",
451           "Fragment durations in ms (produce a fragmented file if > 0)",
452           0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
453           2000 : DEFAULT_FRAGMENT_DURATION,
454           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
455   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
456       g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
457           streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
458   g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
459       g_param_spec_uint64 ("reserved-max-duration",
460           "Reserved maximum file duration (ns)",
461           "When set to a value > 0, reserves space for index tables at the "
462           "beginning of the file.",
463           0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
464           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
465   g_object_class_install_property (gobject_class,
466       PROP_RESERVED_DURATION_REMAINING,
467       g_param_spec_uint64 ("reserved-duration-remaining",
468           "Report the approximate amount of remaining recording space (ns)",
469           "Reports the approximate amount of remaining moov header space "
470           "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
471           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
472   g_object_class_install_property (gobject_class,
473       PROP_RESERVED_MOOV_UPDATE_PERIOD,
474       g_param_spec_uint64 ("reserved-moov-update-period",
475           "Interval at which to update index tables (ns)",
476           "When used with reserved-max-duration, periodically updates the "
477           "index tables with information muxed so far.", 0, G_MAXUINT64,
478           DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
479           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
480   g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
481       g_param_spec_uint ("reserved-bytes-per-sec",
482           "Reserved MOOV bytes per second, per track",
483           "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
484           0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
485           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
486   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
487       g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
488           "Interleave between streams in bytes",
489           0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
490           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
492       g_param_spec_uint64 ("interleave-time", "Interleave (time)",
493           "Interleave between streams in nanoseconds",
494           0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
495           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
496
497   gstelement_class->request_new_pad =
498       GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
499   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
500   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
501 }
502
503 static void
504 gst_qt_mux_pad_reset (GstQTPad * qtpad)
505 {
506   qtpad->fourcc = 0;
507   qtpad->is_out_of_order = FALSE;
508   qtpad->sample_size = 0;
509   qtpad->sync = FALSE;
510   qtpad->last_dts = 0;
511   qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
512   qtpad->first_ts = GST_CLOCK_TIME_NONE;
513   qtpad->first_dts = GST_CLOCK_TIME_NONE;
514   qtpad->prepare_buf_func = NULL;
515   qtpad->create_empty_buffer = NULL;
516   qtpad->avg_bitrate = 0;
517   qtpad->max_bitrate = 0;
518   qtpad->total_duration = 0;
519   qtpad->total_bytes = 0;
520   qtpad->sparse = FALSE;
521
522   qtpad->buf_head = 0;
523   qtpad->buf_tail = 0;
524
525   gst_buffer_replace (&qtpad->last_buf, NULL);
526
527   if (qtpad->tags) {
528     gst_tag_list_unref (qtpad->tags);
529     qtpad->tags = NULL;
530   }
531
532   /* reference owned elsewhere */
533   qtpad->trak = NULL;
534   qtpad->tc_trak = NULL;
535
536   if (qtpad->traf) {
537     atom_traf_free (qtpad->traf);
538     qtpad->traf = NULL;
539   }
540   atom_array_clear (&qtpad->fragment_buffers);
541
542   /* reference owned elsewhere */
543   qtpad->tfra = NULL;
544
545   qtpad->first_pts = GST_CLOCK_TIME_NONE;
546   qtpad->tc_pos = -1;
547   if (qtpad->first_tc)
548     gst_video_time_code_free (qtpad->first_tc);
549   qtpad->first_tc = NULL;
550 }
551
552 /*
553  * Takes GstQTMux back to its initial state
554  */
555 static void
556 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
557 {
558   GSList *walk;
559
560   qtmux->state = GST_QT_MUX_STATE_NONE;
561   qtmux->header_size = 0;
562   qtmux->mdat_size = 0;
563   qtmux->moov_pos = 0;
564   qtmux->mdat_pos = 0;
565   qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
566   qtmux->fragment_sequence = 0;
567
568   if (qtmux->ftyp) {
569     atom_ftyp_free (qtmux->ftyp);
570     qtmux->ftyp = NULL;
571   }
572   if (qtmux->moov) {
573     atom_moov_free (qtmux->moov);
574     qtmux->moov = NULL;
575   }
576   if (qtmux->mfra) {
577     atom_mfra_free (qtmux->mfra);
578     qtmux->mfra = NULL;
579   }
580   if (qtmux->fast_start_file) {
581     fclose (qtmux->fast_start_file);
582     g_remove (qtmux->fast_start_file_path);
583     qtmux->fast_start_file = NULL;
584   }
585   if (qtmux->moov_recov_file) {
586     fclose (qtmux->moov_recov_file);
587     qtmux->moov_recov_file = NULL;
588   }
589   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
590     AtomInfo *ainfo = (AtomInfo *) walk->data;
591     ainfo->free_func (ainfo->atom);
592     g_free (ainfo);
593   }
594   g_slist_free (qtmux->extra_atoms);
595   qtmux->extra_atoms = NULL;
596
597   GST_OBJECT_LOCK (qtmux);
598   gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
599   GST_OBJECT_UNLOCK (qtmux);
600
601   /* reset pad data */
602   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
603     GstQTPad *qtpad = (GstQTPad *) walk->data;
604     gst_qt_mux_pad_reset (qtpad);
605
606     /* hm, moov_free above yanked the traks away from us,
607      * so do not free, but do clear */
608     qtpad->trak = NULL;
609   }
610
611   if (alloc) {
612     qtmux->moov = atom_moov_new (qtmux->context);
613     /* ensure all is as nice and fresh as request_new_pad would provide it */
614     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
615       GstQTPad *qtpad = (GstQTPad *) walk->data;
616
617       qtpad->trak = atom_trak_new (qtmux->context);
618       atom_moov_add_trak (qtmux->moov, qtpad->trak);
619     }
620   }
621
622   qtmux->current_pad = NULL;
623   qtmux->current_chunk_size = 0;
624   qtmux->current_chunk_duration = 0;
625   qtmux->current_chunk_offset = -1;
626
627   qtmux->reserved_moov_size = 0;
628   qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
629   qtmux->muxed_since_last_update = 0;
630   qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
631 }
632
633 static void
634 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
635 {
636   GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
637   GstPadTemplate *templ;
638
639   templ = gst_element_class_get_pad_template (klass, "src");
640   qtmux->srcpad = gst_pad_new_from_template (templ, "src");
641   gst_pad_use_fixed_caps (qtmux->srcpad);
642   gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
643
644   qtmux->sinkpads = NULL;
645   qtmux->collect = gst_collect_pads_new ();
646   gst_collect_pads_set_event_function (qtmux->collect,
647       GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
648   gst_collect_pads_set_clip_function (qtmux->collect,
649       GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
650   gst_collect_pads_set_function (qtmux->collect,
651       GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
652
653   /* properties set to default upon construction */
654
655   qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
656   qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
657   qtmux->reserved_bytes_per_sec_per_trak =
658       DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
659   qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
660   qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
661
662   /* always need this */
663   qtmux->context =
664       atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
665
666   /* internals to initial state */
667   gst_qt_mux_reset (qtmux, TRUE);
668 }
669
670
671 static void
672 gst_qt_mux_finalize (GObject * object)
673 {
674   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
675
676   gst_qt_mux_reset (qtmux, FALSE);
677
678   g_free (qtmux->fast_start_file_path);
679   g_free (qtmux->moov_recov_file_path);
680
681   atoms_context_free (qtmux->context);
682   gst_object_unref (qtmux->collect);
683
684   g_slist_free (qtmux->sinkpads);
685
686   G_OBJECT_CLASS (parent_class)->finalize (object);
687 }
688
689 static GstBuffer *
690 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
691     GstQTMux * qtmux)
692 {
693   GstBuffer *newbuf;
694   GstMapInfo map;
695   gsize size;
696
697   GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
698
699   if (buf == NULL)
700     return NULL;
701
702   size = gst_buffer_get_size (buf);
703   newbuf = gst_buffer_new_and_alloc (size + 8);
704   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
705
706   gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
707   GST_WRITE_UINT32_BE (map.data, map.size);
708   GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
709
710   gst_buffer_unmap (buf, &map);
711   gst_buffer_unref (buf);
712
713   return newbuf;
714 }
715
716 static GstBuffer *
717 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
718     GstQTMux * qtmux)
719 {
720   GstBuffer *newbuf;
721   GstMapInfo frommap;
722   GstMapInfo tomap;
723   gsize size;
724   const guint8 *dataend;
725
726   GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
727
728   if (buf == NULL)
729     return NULL;
730
731   gst_buffer_map (buf, &frommap, GST_MAP_READ);
732
733   dataend = memchr (frommap.data, 0, frommap.size);
734   size = dataend ? dataend - frommap.data : frommap.size;
735   newbuf = gst_buffer_new_and_alloc (size + 2);
736
737   gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
738
739   GST_WRITE_UINT16_BE (tomap.data, size);
740   memcpy (tomap.data + 2, frommap.data, size);
741
742   gst_buffer_unmap (newbuf, &tomap);
743   gst_buffer_unmap (buf, &frommap);
744
745   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
746
747   /* gst_buffer_copy_into is trying to be too clever and
748    * won't copy duration when size is different */
749   GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
750
751   gst_buffer_unref (buf);
752
753   return newbuf;
754 }
755
756 static void
757 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
758     guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
759     guint8 lfe_on)
760 {
761   AtomInfo *ext;
762
763   g_return_if_fail (qtpad->trak_ste);
764
765   ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1);        /* bitrate_code is inside frmsizcod */
766
767   sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
768 }
769
770 static GstBuffer *
771 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
772     GstQTMux * qtmux)
773 {
774   GstMapInfo map;
775   GstByteReader reader;
776   guint off;
777
778   if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
779     GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
780     return buf;
781   }
782
783   if (G_UNLIKELY (map.size < 8))
784     goto done;
785
786   gst_byte_reader_init (&reader, map.data, map.size);
787   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
788       0, map.size);
789
790   if (off != -1) {
791     GstBitReader bits;
792     guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
793
794     GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
795         off);
796
797     gst_bit_reader_init (&bits, map.data, map.size);
798
799     /* off + sync + crc */
800     gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
801
802     fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
803     frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
804     bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
805     bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
806     acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
807
808     if ((acmod & 0x1) && (acmod != 0x1))        /* 3 front channels */
809       gst_bit_reader_skip_unchecked (&bits, 2);
810     if ((acmod & 0x4))          /* if a surround channel exists */
811       gst_bit_reader_skip_unchecked (&bits, 2);
812     if (acmod == 0x2)           /* if in 2/0 mode */
813       gst_bit_reader_skip_unchecked (&bits, 2);
814
815     lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
816
817     gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
818         bsmod, acmod, lfe_on);
819
820     /* AC-3 spec says that those values should be constant for the
821      * whole stream when muxed in mp4. We trust the input follows it */
822     GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
823         "prepare buffer function");
824     qtpad->prepare_buf_func = NULL;
825   }
826
827 done:
828   gst_buffer_unmap (buf, &map);
829   return buf;
830 }
831
832 static GstBuffer *
833 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
834 {
835   guint8 *data;
836
837   data = g_malloc (2);
838   GST_WRITE_UINT16_BE (data, 0);
839
840   return gst_buffer_new_wrapped (data, 2);
841 }
842
843 static void
844 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
845     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
846 {
847   switch (gst_tag_get_type (tag)) {
848       /* strings */
849     case G_TYPE_STRING:
850     {
851       gchar *str = NULL;
852
853       if (!gst_tag_list_get_string (list, tag, &str) || !str)
854         break;
855       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
856           GST_FOURCC_ARGS (fourcc), str);
857       atom_udta_add_str_tag (udta, fourcc, str);
858       g_free (str);
859       break;
860     }
861       /* double */
862     case G_TYPE_DOUBLE:
863     {
864       gdouble value;
865
866       if (!gst_tag_list_get_double (list, tag, &value))
867         break;
868       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
869           GST_FOURCC_ARGS (fourcc), (gint) value);
870       atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
871       break;
872     }
873     case G_TYPE_UINT:
874     {
875       guint value = 0;
876       if (tag2) {
877         /* paired unsigned integers */
878         guint count = 0;
879         gboolean got_tag;
880
881         got_tag = gst_tag_list_get_uint (list, tag, &value);
882         got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
883         if (!got_tag)
884           break;
885         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
886             GST_FOURCC_ARGS (fourcc), value, count);
887         atom_udta_add_uint_tag (udta, fourcc, 0,
888             value << 16 | (count & 0xFFFF));
889       } else {
890         /* unpaired unsigned integers */
891         if (!gst_tag_list_get_uint (list, tag, &value))
892           break;
893         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
894             GST_FOURCC_ARGS (fourcc), value);
895         atom_udta_add_uint_tag (udta, fourcc, 1, value);
896       }
897       break;
898     }
899     default:
900       g_assert_not_reached ();
901       break;
902   }
903 }
904
905 static void
906 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
907     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
908 {
909   GDate *date = NULL;
910   GDateYear year;
911   GDateMonth month;
912   GDateDay day;
913   gchar *str;
914
915   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
916
917   if (!gst_tag_list_get_date (list, tag, &date) || !date)
918     return;
919
920   year = g_date_get_year (date);
921   month = g_date_get_month (date);
922   day = g_date_get_day (date);
923
924   g_date_free (date);
925
926   if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
927       day == G_DATE_BAD_DAY) {
928     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
929     return;
930   }
931
932   str = g_strdup_printf ("%u-%u-%u", year, month, day);
933   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
934       GST_FOURCC_ARGS (fourcc), str);
935   atom_udta_add_str_tag (udta, fourcc, str);
936   g_free (str);
937 }
938
939 static void
940 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
941     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
942 {
943   GValue value = { 0, };
944   GstBuffer *buf;
945   GstSample *sample;
946   GstCaps *caps;
947   GstStructure *structure;
948   gint flags = 0;
949   GstMapInfo map;
950
951   g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
952
953   if (!gst_tag_list_copy_value (&value, list, tag))
954     return;
955
956   sample = gst_value_get_sample (&value);
957
958   if (!sample)
959     goto done;
960
961   buf = gst_sample_get_buffer (sample);
962   if (!buf)
963     goto done;
964
965   caps = gst_sample_get_caps (sample);
966   if (!caps) {
967     GST_WARNING_OBJECT (qtmux, "preview image without caps");
968     goto done;
969   }
970
971   GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
972
973   structure = gst_caps_get_structure (caps, 0);
974   if (gst_structure_has_name (structure, "image/jpeg"))
975     flags = 13;
976   else if (gst_structure_has_name (structure, "image/png"))
977     flags = 14;
978
979   if (!flags) {
980     GST_WARNING_OBJECT (qtmux, "preview image format not supported");
981     goto done;
982   }
983
984   gst_buffer_map (buf, &map, GST_MAP_READ);
985   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
986       " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
987   atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
988   gst_buffer_unmap (buf, &map);
989 done:
990   g_value_unset (&value);
991 }
992
993 static void
994 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
995     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
996 {
997   gchar *str = NULL;
998   guint number;
999
1000   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1001   g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1002
1003   if (!gst_tag_list_get_string (list, tag, &str) || !str)
1004     return;
1005
1006   if (tag2)
1007     if (!gst_tag_list_get_uint (list, tag2, &number))
1008       tag2 = NULL;
1009
1010   if (!tag2) {
1011     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1012         GST_FOURCC_ARGS (fourcc), str);
1013     atom_udta_add_3gp_str_tag (udta, fourcc, str);
1014   } else {
1015     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1016         GST_FOURCC_ARGS (fourcc), str, number);
1017     atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1018   }
1019
1020   g_free (str);
1021 }
1022
1023 static void
1024 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1025     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1026 {
1027   GDate *date = NULL;
1028   GDateYear year;
1029
1030   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1031
1032   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1033     return;
1034
1035   year = g_date_get_year (date);
1036   g_date_free (date);
1037
1038   if (year == G_DATE_BAD_YEAR) {
1039     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1040     return;
1041   }
1042
1043   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1044       GST_FOURCC_ARGS (fourcc), year);
1045   atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1046 }
1047
1048 static void
1049 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1050     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1051 {
1052   gdouble latitude = -360, longitude = -360, altitude = 0;
1053   gchar *location = NULL;
1054   guint8 *data, *ddata;
1055   gint size = 0, len = 0;
1056   gboolean ret = FALSE;
1057
1058   g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1059
1060   ret = gst_tag_list_get_string (list, tag, &location);
1061   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1062       &longitude);
1063   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1064       &latitude);
1065   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1066       &altitude);
1067
1068   if (!ret)
1069     return;
1070
1071   if (location)
1072     len = strlen (location);
1073   size += len + 1 + 2;
1074
1075   /* role + (long, lat, alt) + body + notes */
1076   size += 1 + 3 * 4 + 1 + 1;
1077
1078   data = ddata = g_malloc (size);
1079
1080   /* language tag */
1081   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1082   /* location */
1083   if (location)
1084     memcpy (data + 2, location, len);
1085   GST_WRITE_UINT8 (data + 2 + len, 0);
1086   data += len + 1 + 2;
1087   /* role */
1088   GST_WRITE_UINT8 (data, 0);
1089   /* long, lat, alt */
1090 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1091   QT_WRITE_SFP32 (data + 1, longitude);
1092   QT_WRITE_SFP32 (data + 5, latitude);
1093   QT_WRITE_SFP32 (data + 9, altitude);
1094   /* neither astronomical body nor notes */
1095   GST_WRITE_UINT16_BE (data + 13, 0);
1096
1097   GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1098   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1099   g_free (ddata);
1100 }
1101
1102 static void
1103 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1104     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1105 {
1106   gchar *keywords = NULL;
1107   guint8 *data, *ddata;
1108   gint size = 0, i;
1109   gchar **kwds;
1110
1111   g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1112
1113   if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1114     return;
1115
1116   kwds = g_strsplit (keywords, ",", 0);
1117   g_free (keywords);
1118
1119   size = 0;
1120   for (i = 0; kwds[i]; i++) {
1121     /* size byte + null-terminator */
1122     size += strlen (kwds[i]) + 1 + 1;
1123   }
1124
1125   /* language tag + count + keywords */
1126   size += 2 + 1;
1127
1128   data = ddata = g_malloc (size);
1129
1130   /* language tag */
1131   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1132   /* count */
1133   GST_WRITE_UINT8 (data + 2, i);
1134   data += 3;
1135   /* keywords */
1136   for (i = 0; kwds[i]; ++i) {
1137     gint len = strlen (kwds[i]);
1138
1139     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1140         GST_FOURCC_ARGS (fourcc), kwds[i]);
1141     /* size */
1142     GST_WRITE_UINT8 (data, len + 1);
1143     memcpy (data + 1, kwds[i], len + 1);
1144     data += len + 2;
1145   }
1146
1147   g_strfreev (kwds);
1148
1149   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1150   g_free (ddata);
1151 }
1152
1153 static gboolean
1154 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1155     guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1156 {
1157   guint32 fourcc;
1158   gint table;
1159   gint size;
1160   const gchar *data;
1161
1162   data = input;
1163   size = strlen (input);
1164
1165   if (size < 4 + 3 + 1 + 1 + 1) {
1166     /* at least the minimum xxxx://y/z */
1167     GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1168         "ignoring", input);
1169     return FALSE;
1170   }
1171
1172   /* read the fourcc */
1173   memcpy (&fourcc, data, 4);
1174   size -= 4;
1175   data += 4;
1176
1177   if (strncmp (data, "://", 3) != 0) {
1178     goto mismatch;
1179   }
1180   data += 3;
1181   size -= 3;
1182
1183   /* read the table number */
1184   if (sscanf (data, "%d", &table) != 1) {
1185     goto mismatch;
1186   }
1187   if (table < 0) {
1188     GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1189         ", table numbers should be positive, ignoring tag", table);
1190     return FALSE;
1191   }
1192
1193   /* find the next / */
1194   while (size > 0 && data[0] != '/') {
1195     data += 1;
1196     size -= 1;
1197   }
1198   if (size == 0) {
1199     goto mismatch;
1200   }
1201   g_assert (data[0] == '/');
1202
1203   /* skip the '/' */
1204   data += 1;
1205   size -= 1;
1206   if (size == 0) {
1207     goto mismatch;
1208   }
1209
1210   /* read up the rest of the string */
1211   *p_content = g_strdup (data);
1212   *p_table = (guint16) table;
1213   *p_fourcc = fourcc;
1214   return TRUE;
1215
1216 mismatch:
1217   {
1218     GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1219         "input (%s) didn't match the expected entitycode://table/content",
1220         input);
1221     return FALSE;
1222   }
1223 }
1224
1225 static void
1226 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1227     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1228 {
1229   gchar *clsf_data = NULL;
1230   gint size = 0;
1231   guint32 entity = 0;
1232   guint16 table = 0;
1233   gchar *content = NULL;
1234   guint8 *data;
1235
1236   g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1237
1238   if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1239     return;
1240
1241   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1242       GST_FOURCC_ARGS (fourcc), clsf_data);
1243
1244   /* parse the string, format is:
1245    * entityfourcc://table/content
1246    */
1247   gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1248       &content);
1249   g_free (clsf_data);
1250   /* +1 for the \0 */
1251   size = strlen (content) + 1;
1252
1253   /* now we have everything, build the atom
1254    * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1255   data = g_malloc (4 + 2 + 2 + size);
1256   GST_WRITE_UINT32_LE (data, entity);
1257   GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1258   GST_WRITE_UINT16_BE (data + 6, 0);
1259   memcpy (data + 8, content, size);
1260   g_free (content);
1261
1262   atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1263   g_free (data);
1264 }
1265
1266 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1267     const GstTagList * list, AtomUDTA * udta, const char *tag,
1268     const char *tag2, guint32 fourcc);
1269
1270 /*
1271  * Struct to record mappings from gstreamer tags to fourcc codes
1272  */
1273 typedef struct _GstTagToFourcc
1274 {
1275   guint32 fourcc;
1276   const gchar *gsttag;
1277   const gchar *gsttag2;
1278   const GstQTMuxAddUdtaTagFunc func;
1279 } GstTagToFourcc;
1280
1281 /* tag list tags to fourcc matching */
1282 static const GstTagToFourcc tag_matches_mp4[] = {
1283   {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1284   {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1285   {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1286   {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1287   {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1288   {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1289   {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1290   {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1291   {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1292   {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1293   {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1294   {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1295   {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1296   {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1297   {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1298   {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1299   {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1300   {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1301   {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1302   {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1303   {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1304   {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1305   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1306   {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1307   {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1308   {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1309   {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1310       gst_qt_mux_add_mp4_tag},
1311   {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1312       gst_qt_mux_add_mp4_tag},
1313   {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1314   {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1315   {0, NULL,}
1316 };
1317
1318 static const GstTagToFourcc tag_matches_3gp[] = {
1319   {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1320   {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1321   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1322   {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1323   {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1324   {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1325   {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1326   {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1327   {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1328   {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1329   {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1330       gst_qt_mux_add_3gp_classification},
1331   {0, NULL,}
1332 };
1333
1334 /* qtdemux produces these for atoms it cannot parse */
1335 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1336
1337 static void
1338 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1339 {
1340   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1341   GstBuffer *xmp = NULL;
1342
1343   /* adobe specs only have 'quicktime' and 'mp4',
1344    * but I guess we can extrapolate to gpp.
1345    * Keep mj2 out for now as we don't add any tags for it yet.
1346    * If you have further info about xmp on these formats, please share */
1347   if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1348     return;
1349
1350   GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1351
1352   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1353     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1354         list, TRUE);
1355     if (xmp)
1356       atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1357   } else {
1358     AtomInfo *ainfo;
1359     /* for isom/mp4, it is a top level uuid atom */
1360     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1361         list, TRUE);
1362     if (xmp) {
1363       ainfo = build_uuid_xmp_atom (xmp);
1364       if (ainfo) {
1365         qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1366       }
1367     }
1368   }
1369   if (xmp)
1370     gst_buffer_unref (xmp);
1371 }
1372
1373 static void
1374 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1375     AtomUDTA * udta)
1376 {
1377   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1378   guint32 fourcc;
1379   gint i;
1380   const gchar *tag, *tag2;
1381   const GstTagToFourcc *tag_matches;
1382
1383   switch (qtmux_klass->format) {
1384     case GST_QT_MUX_FORMAT_3GP:
1385       tag_matches = tag_matches_3gp;
1386       break;
1387     case GST_QT_MUX_FORMAT_MJ2:
1388       tag_matches = NULL;
1389       break;
1390     default:
1391       /* sort of iTunes style for mp4 and QT (?) */
1392       tag_matches = tag_matches_mp4;
1393       break;
1394   }
1395
1396   if (!tag_matches)
1397     return;
1398
1399   /* Clear existing tags so we don't add them over and over */
1400   atom_udta_clear_tags (udta);
1401
1402   for (i = 0; tag_matches[i].fourcc; i++) {
1403     fourcc = tag_matches[i].fourcc;
1404     tag = tag_matches[i].gsttag;
1405     tag2 = tag_matches[i].gsttag2;
1406
1407     g_assert (tag_matches[i].func);
1408     tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1409   }
1410
1411   /* add unparsed blobs if present */
1412   if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1413     guint num_tags;
1414
1415     num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1416     for (i = 0; i < num_tags; ++i) {
1417       GstSample *sample = NULL;
1418       GstBuffer *buf;
1419       const GstStructure *s;
1420
1421       if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1422               &sample))
1423         continue;
1424       buf = gst_sample_get_buffer (sample);
1425
1426       if (buf && (s = gst_sample_get_info (sample))) {
1427         const gchar *style = NULL;
1428         GstMapInfo map;
1429
1430         gst_buffer_map (buf, &map, GST_MAP_READ);
1431         GST_DEBUG_OBJECT (qtmux,
1432             "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1433             GST_PTR_FORMAT, i, num_tags, map.size, s);
1434         if (s && (style = gst_structure_get_string (s, "style"))) {
1435           /* try to prevent some style tag ending up into another variant
1436            * (todo: make into a list if more cases) */
1437           if ((strcmp (style, "itunes") == 0 &&
1438                   qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1439               (strcmp (style, "iso") == 0 &&
1440                   qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1441             GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1442             atom_udta_add_blob_tag (udta, map.data, map.size);
1443           }
1444         }
1445         gst_buffer_unmap (buf, &map);
1446       }
1447       gst_sample_unref (sample);
1448     }
1449   }
1450
1451   return;
1452 }
1453
1454 /*
1455  * Gets the tagsetter iface taglist and puts the known tags
1456  * into the output stream
1457  */
1458 static void
1459 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1460 {
1461   const GstTagList *tags = NULL;
1462   GSList *walk;
1463
1464   GST_OBJECT_LOCK (qtmux);
1465   if (qtmux->tags_changed) {
1466     tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1467     qtmux->tags_changed = FALSE;
1468   }
1469   GST_OBJECT_UNLOCK (qtmux);
1470
1471   GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1472
1473   if (tags && !gst_tag_list_is_empty (tags)) {
1474     GstTagList *copy = gst_tag_list_copy (tags);
1475
1476     GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1477     gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1478     gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1479     gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1480
1481     GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1482     gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1483     gst_qt_mux_add_xmp_tags (qtmux, copy);
1484     gst_tag_list_unref (copy);
1485   } else {
1486     GST_DEBUG_OBJECT (qtmux, "No new tags received");
1487   }
1488
1489   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1490     GstCollectData *cdata = (GstCollectData *) walk->data;
1491     GstQTPad *qpad = (GstQTPad *) cdata;
1492     GstPad *pad = qpad->collect.pad;
1493
1494     if (qpad->tags_changed && qpad->tags) {
1495       GST_DEBUG_OBJECT (pad, "Adding tags");
1496       gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1497       gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1498       qpad->tags_changed = FALSE;
1499       GST_DEBUG_OBJECT (pad, "Tags added");
1500     } else {
1501       GST_DEBUG_OBJECT (pad, "No new tags received");
1502     }
1503   }
1504 }
1505
1506 static inline GstBuffer *
1507 _gst_buffer_new_take_data (guint8 * data, guint size)
1508 {
1509   GstBuffer *buf;
1510
1511   buf = gst_buffer_new ();
1512   gst_buffer_append_memory (buf,
1513       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1514
1515   return buf;
1516 }
1517
1518 static GstFlowReturn
1519 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1520     gboolean mind_fast)
1521 {
1522   GstFlowReturn res;
1523   gsize size;
1524
1525   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1526
1527   size = gst_buffer_get_size (buf);
1528   GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1529
1530   if (mind_fast && qtmux->fast_start_file) {
1531     GstMapInfo map;
1532     gint ret;
1533
1534     GST_LOG_OBJECT (qtmux, "to temporary file");
1535     gst_buffer_map (buf, &map, GST_MAP_READ);
1536     ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1537     gst_buffer_unmap (buf, &map);
1538     gst_buffer_unref (buf);
1539     if (ret != size)
1540       goto write_error;
1541     else
1542       res = GST_FLOW_OK;
1543   } else {
1544     GST_LOG_OBJECT (qtmux, "downstream");
1545     res = gst_pad_push (qtmux->srcpad, buf);
1546   }
1547
1548   if (G_LIKELY (offset))
1549     *offset += size;
1550
1551   return res;
1552
1553   /* ERRORS */
1554 write_error:
1555   {
1556     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1557         ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1558     return GST_FLOW_ERROR;
1559   }
1560 }
1561
1562 static gboolean
1563 gst_qt_mux_seek_to_beginning (FILE * f)
1564 {
1565 #ifdef HAVE_FSEEKO
1566   if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1567     return FALSE;
1568 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1569   if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1570     return FALSE;
1571 #else
1572   if (fseek (f, (long) 0, SEEK_SET) != 0)
1573     return FALSE;
1574 #endif
1575   return TRUE;
1576 }
1577
1578 static GstFlowReturn
1579 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1580 {
1581   GstFlowReturn ret = GST_FLOW_OK;
1582   GstBuffer *buf = NULL;
1583
1584   if (fflush (qtmux->fast_start_file))
1585     goto flush_failed;
1586
1587   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1588     goto seek_failed;
1589
1590   /* hm, this could all take a really really long time,
1591    * but there may not be another way to get moov atom first
1592    * (somehow optimize copy?) */
1593   GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1594   while (ret == GST_FLOW_OK) {
1595     const int bufsize = 4096;
1596     GstMapInfo map;
1597     gsize size;
1598
1599     buf = gst_buffer_new_and_alloc (bufsize);
1600     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1601     size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1602     if (size == 0) {
1603       gst_buffer_unmap (buf, &map);
1604       break;
1605     }
1606     GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1607     gst_buffer_unmap (buf, &map);
1608     if (size != bufsize)
1609       gst_buffer_set_size (buf, size);
1610     ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1611     buf = NULL;
1612   }
1613   if (buf)
1614     gst_buffer_unref (buf);
1615
1616   if (ftruncate (fileno (qtmux->fast_start_file), 0))
1617     goto seek_failed;
1618   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1619     goto seek_failed;
1620
1621   return ret;
1622
1623   /* ERRORS */
1624 flush_failed:
1625   {
1626     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1627         ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1628     ret = GST_FLOW_ERROR;
1629     goto fail;
1630   }
1631 seek_failed:
1632   {
1633     GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1634         ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1635     ret = GST_FLOW_ERROR;
1636     goto fail;
1637   }
1638 fail:
1639   {
1640     /* clear descriptor so we don't remove temp file later on,
1641      * might be possible to recover */
1642     fclose (qtmux->fast_start_file);
1643     qtmux->fast_start_file = NULL;
1644     return ret;
1645   }
1646 }
1647
1648 /*
1649  * Sends the initial mdat atom fields (size fields and fourcc type),
1650  * the subsequent buffers are considered part of it's data.
1651  * As we can't predict the amount of data that we are going to place in mdat
1652  * we need to record the position of the size field in the stream so we can
1653  * seek back to it later and update when the streams have finished.
1654  */
1655 static GstFlowReturn
1656 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1657     gboolean extended, gboolean fsync_after)
1658 {
1659   GstBuffer *buf;
1660   GstMapInfo map;
1661
1662   GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1663       "size %" G_GUINT64_FORMAT, size);
1664
1665   /* if the qtmux state is EOS, really write the mdat, otherwise
1666    * allow size == 0 for a placeholder atom */
1667   if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1668     size += 8;
1669
1670   if (extended) {
1671     gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1672     /* Always write 16-bytes, but put a free atom first
1673      * if the size is < 4GB. */
1674     buf = gst_buffer_new_and_alloc (16);
1675     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1676
1677     if (large_file) {
1678       /* Write extended mdat header and large_size field */
1679       GST_WRITE_UINT32_BE (map.data, 1);
1680       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1681       GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1682     } else {
1683       /* Write an empty free atom, then standard 32-bit mdat */
1684       GST_WRITE_UINT32_BE (map.data, 8);
1685       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1686       GST_WRITE_UINT32_BE (map.data + 8, size);
1687       GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1688     }
1689     gst_buffer_unmap (buf, &map);
1690   } else {
1691     buf = gst_buffer_new_and_alloc (8);
1692     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1693
1694     /* Vanilla 32-bit mdat */
1695     GST_WRITE_UINT32_BE (map.data, size);
1696     GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1697     gst_buffer_unmap (buf, &map);
1698   }
1699
1700   GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1701   if (fsync_after)
1702     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1703
1704   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1705
1706 }
1707
1708 /*
1709  * We get the position of the mdat size field, seek back to it
1710  * and overwrite with the real value
1711  */
1712 static GstFlowReturn
1713 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1714     guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1715 {
1716   GstSegment segment;
1717
1718   /* We must have recorded the mdat position for this to work */
1719   g_assert (mdat_pos != 0);
1720
1721   /* seek and rewrite the header */
1722   gst_segment_init (&segment, GST_FORMAT_BYTES);
1723   segment.start = mdat_pos;
1724   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1725
1726   return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1727       fsync_after);
1728 }
1729
1730 static GstFlowReturn
1731 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1732 {
1733   GstBuffer *buf;
1734   guint64 size = 0, offset = 0;
1735   guint8 *data = NULL;
1736
1737   GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1738
1739   if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1740     goto serialize_error;
1741
1742   buf = _gst_buffer_new_take_data (data, offset);
1743
1744   GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1745   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1746
1747   /* ERRORS */
1748 serialize_error:
1749   {
1750     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1751         ("Failed to serialize ftyp"));
1752     return GST_FLOW_ERROR;
1753   }
1754 }
1755
1756 static void
1757 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1758     GstBuffer ** p_prefix)
1759 {
1760   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1761   guint32 major, version;
1762   GList *comp;
1763   GstBuffer *prefix = NULL;
1764   AtomFTYP *ftyp = NULL;
1765
1766   GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1767
1768   /* init and send context and ftyp based on current property state */
1769   gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1770       &version, &comp, qtmux->moov, qtmux->longest_chunk,
1771       qtmux->fast_start_file != NULL);
1772   ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1773   if (comp)
1774     g_list_free (comp);
1775   if (prefix) {
1776     if (p_prefix)
1777       *p_prefix = prefix;
1778     else
1779       gst_buffer_unref (prefix);
1780   }
1781   *p_ftyp = ftyp;
1782 }
1783
1784 static GstFlowReturn
1785 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1786 {
1787   GstFlowReturn ret = GST_FLOW_OK;
1788   GstBuffer *prefix = NULL;
1789
1790   GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1791
1792   /* init and send context and ftyp based on current property state */
1793   if (qtmux->ftyp) {
1794     atom_ftyp_free (qtmux->ftyp);
1795     qtmux->ftyp = NULL;
1796   }
1797   gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1798   if (prefix) {
1799     ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1800     if (ret != GST_FLOW_OK)
1801       return ret;
1802   }
1803   return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1804 }
1805
1806 static void
1807 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1808 {
1809   GstStructure *structure;
1810   GValue array = { 0 };
1811   GValue value = { 0 };
1812   GstCaps *caps, *tcaps;
1813
1814   tcaps = gst_pad_get_current_caps (mux->srcpad);
1815   caps = gst_caps_copy (tcaps);
1816   gst_caps_unref (tcaps);
1817
1818   structure = gst_caps_get_structure (caps, 0);
1819
1820   g_value_init (&array, GST_TYPE_ARRAY);
1821
1822   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1823   g_value_init (&value, GST_TYPE_BUFFER);
1824   gst_value_take_buffer (&value, gst_buffer_ref (buf));
1825   gst_value_array_append_value (&array, &value);
1826   g_value_unset (&value);
1827
1828   gst_structure_set_value (structure, "streamheader", &array);
1829   g_value_unset (&array);
1830   gst_pad_set_caps (mux->srcpad, caps);
1831   gst_caps_unref (caps);
1832 }
1833
1834 /*
1835  * Write out a free space atom. The offset is adjusted by the full
1836  * size, but a smaller buffer is sent
1837  */
1838 static GstFlowReturn
1839 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1840     gboolean fsync_after)
1841 {
1842   Atom *node_header;
1843   GstBuffer *buf;
1844   guint8 *data = NULL;
1845   guint64 offset = 0, bsize = 0;
1846   GstFlowReturn ret;
1847
1848   GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1849
1850   /* We can't make a free space atom smaller than the header */
1851   if (size < 8)
1852     goto too_small;
1853
1854   node_header = g_malloc0 (sizeof (Atom));
1855   node_header->type = FOURCC_free;
1856   node_header->size = size;
1857
1858   bsize = offset = 0;
1859   if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
1860     goto serialize_error;
1861
1862   buf = _gst_buffer_new_take_data (data, offset);
1863   g_free (node_header);
1864
1865   if (fsync_after)
1866     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1867
1868   GST_LOG_OBJECT (qtmux, "Pushing free atom");
1869   ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1870
1871   if (off) {
1872     GstSegment segment;
1873
1874     *off += size - 8;
1875
1876     /* Make sure downstream position ends up at the end of this free box */
1877     gst_segment_init (&segment, GST_FORMAT_BYTES);
1878     segment.start = *off;
1879     gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1880   }
1881
1882   return ret;
1883
1884   /* ERRORS */
1885 too_small:
1886   {
1887     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1888         ("Not enough free reserved space"));
1889     return GST_FLOW_ERROR;
1890   }
1891 serialize_error:
1892   {
1893     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1894         ("Failed to serialize mdat"));
1895     g_free (node_header);
1896     return GST_FLOW_ERROR;
1897   }
1898 }
1899
1900 static void
1901 gst_qt_mux_configure_moov (GstQTMux * qtmux)
1902 {
1903   gboolean fragmented = FALSE;
1904   guint32 timescale;
1905
1906   GST_OBJECT_LOCK (qtmux);
1907   timescale = qtmux->timescale;
1908   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
1909       qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
1910     fragmented = TRUE;
1911   GST_OBJECT_UNLOCK (qtmux);
1912
1913   /* inform lower layers of our property wishes, and determine duration.
1914    * Let moov take care of this using its list of traks;
1915    * so that released pads are also included */
1916   GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1917       timescale);
1918   atom_moov_update_timescale (qtmux->moov, timescale);
1919   atom_moov_set_fragmented (qtmux->moov, fragmented);
1920
1921   atom_moov_update_duration (qtmux->moov);
1922 }
1923
1924 static GstFlowReturn
1925 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
1926     guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
1927 {
1928   guint64 offset = 0, size = 0;
1929   guint8 *data;
1930   GstBuffer *buf;
1931   GstFlowReturn ret = GST_FLOW_OK;
1932   GSList *walk;
1933   guint64 current_time = atoms_get_current_qt_time ();
1934
1935   /* update modification times */
1936   qtmux->moov->mvhd.time_info.modification_time = current_time;
1937   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1938     GstCollectData *cdata = (GstCollectData *) walk->data;
1939     GstQTPad *qtpad = (GstQTPad *) cdata;
1940
1941     qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
1942     qtpad->trak->tkhd.modification_time = current_time;
1943   }
1944
1945   /* serialize moov */
1946   offset = size = 0;
1947   data = NULL;
1948   GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1949   if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1950     goto serialize_error;
1951   qtmux->last_moov_size = offset;
1952
1953   /* Check we have enough reserved space for this and a Free atom */
1954   if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
1955     goto too_small_reserved;
1956   buf = _gst_buffer_new_take_data (data, offset);
1957   GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1958
1959   /* If at EOS, this is the final moov, put in the streamheader
1960    * (apparently used by a flumotion util) */
1961   if (qtmux->state == GST_QT_MUX_STATE_EOS)
1962     gst_qt_mux_set_header_on_caps (qtmux, buf);
1963
1964   if (fsync_after)
1965     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1966   ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1967
1968   /* Write out a free atom if needed */
1969   if (ret == GST_FLOW_OK && offset < padded_moov_size) {
1970     GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
1971         (guint32) (padded_moov_size - offset));
1972     ret =
1973         gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
1974         fsync_after);
1975   }
1976
1977   return ret;
1978 too_small_reserved:
1979   {
1980     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
1981         ("Not enough free reserved header space"),
1982         ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
1983             offset, padded_moov_size));
1984     return GST_FLOW_ERROR;
1985   }
1986 serialize_error:
1987   {
1988     g_free (data);
1989     return GST_FLOW_ERROR;
1990   }
1991 }
1992
1993 /* either calculates size of extra atoms or pushes them */
1994 static GstFlowReturn
1995 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1996     gboolean mind_fast)
1997 {
1998   GSList *walk;
1999   guint64 loffset = 0, size = 0;
2000   guint8 *data;
2001   GstFlowReturn ret = GST_FLOW_OK;
2002
2003   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2004     AtomInfo *ainfo = (AtomInfo *) walk->data;
2005
2006     loffset = size = 0;
2007     data = NULL;
2008     if (!ainfo->copy_data_func (ainfo->atom,
2009             send ? &data : NULL, &size, &loffset))
2010       goto serialize_error;
2011
2012     if (send) {
2013       GstBuffer *buf;
2014
2015       GST_DEBUG_OBJECT (qtmux,
2016           "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2017           GST_FOURCC_ARGS (ainfo->atom->type));
2018       buf = _gst_buffer_new_take_data (data, loffset);
2019       ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2020       if (ret != GST_FLOW_OK)
2021         break;
2022     } else {
2023       if (offset)
2024         *offset += loffset;
2025     }
2026   }
2027
2028   return ret;
2029
2030 serialize_error:
2031   {
2032     g_free (data);
2033     return GST_FLOW_ERROR;
2034   }
2035 }
2036
2037 static gboolean
2038 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2039 {
2040   gboolean seekable = FALSE;
2041   GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2042
2043   if (gst_pad_peer_query (qtmux->srcpad, query)) {
2044     gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2045     GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2046   } else {
2047     /* have to assume seeking is not supported if query not handled downstream */
2048     GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2049     seekable = FALSE;
2050   }
2051   gst_query_unref (query);
2052
2053   return seekable;
2054 }
2055
2056 static void
2057 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2058 {
2059   GSList *walk;
2060   gboolean fail = FALSE;
2061   AtomFTYP *ftyp = NULL;
2062   GstBuffer *prefix = NULL;
2063
2064   GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2065       qtmux->moov_recov_file_path);
2066
2067   qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2068   if (qtmux->moov_recov_file == NULL) {
2069     GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2070         qtmux->moov_recov_file_path);
2071     return;
2072   }
2073
2074   gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2075
2076   if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2077           qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2078     GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2079     goto fail;
2080   }
2081
2082   atom_ftyp_free (ftyp);
2083   if (prefix)
2084     gst_buffer_unref (prefix);
2085
2086   for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2087     GstCollectData *cdata = (GstCollectData *) walk->data;
2088     GstQTPad *qpad = (GstQTPad *) cdata;
2089     /* write info for each stream */
2090     fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2091     if (fail) {
2092       GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2093           "file");
2094       break;
2095     }
2096   }
2097
2098   return;
2099
2100 fail:
2101   /* cleanup */
2102   fclose (qtmux->moov_recov_file);
2103   qtmux->moov_recov_file = NULL;
2104 }
2105
2106 static GstFlowReturn
2107 gst_qt_mux_start_file (GstQTMux * qtmux)
2108 {
2109   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2110   GstFlowReturn ret = GST_FLOW_OK;
2111   GstCaps *caps;
2112   GstSegment segment;
2113   gchar s_id[32];
2114   GstClockTime reserved_max_duration;
2115   guint reserved_bytes_per_sec_per_trak;
2116
2117   GST_DEBUG_OBJECT (qtmux, "starting file");
2118
2119   GST_OBJECT_LOCK (qtmux);
2120   reserved_max_duration = qtmux->reserved_max_duration;
2121   reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2122   GST_OBJECT_UNLOCK (qtmux);
2123
2124   /* stream-start (FIXME: create id based on input ids) */
2125   g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2126   gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2127
2128   caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2129   /* qtmux has structure with and without variant, remove all but the first */
2130   while (gst_caps_get_size (caps) > 1)
2131     gst_caps_remove_structure (caps, 1);
2132   gst_pad_set_caps (qtmux->srcpad, caps);
2133   gst_caps_unref (caps);
2134
2135   /* Default is 'normal' mode */
2136   qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2137
2138   /* Require a sensible fragment duration when muxing
2139    * using the ISML muxer */
2140   if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2141       qtmux->fragment_duration == 0)
2142     goto invalid_isml;
2143
2144   if (qtmux->fragment_duration > 0) {
2145     if (qtmux->streamable)
2146       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2147     else
2148       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2149   } else if (qtmux->fast_start) {
2150     qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2151   } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2152     qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2153   }
2154
2155   switch (qtmux->mux_mode) {
2156     case GST_QT_MUX_MODE_MOOV_AT_END:
2157     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2158       /* We have to be able to seek to rewrite the mdat header, or any
2159        * moov atom we write will not be visible in the file, because an
2160        * MDAT with 0 as the size covers the rest of the file. A file
2161        * with no moov is not playable, so error out now. */
2162       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2163         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2164             ("Downstream is not seekable - will not be able to create a playable file"),
2165             (NULL));
2166         return GST_FLOW_ERROR;
2167       }
2168       break;
2169     case GST_QT_MUX_MODE_FAST_START:
2170     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2171       break;                    /* Don't need seekability, ignore */
2172     case GST_QT_MUX_MODE_FRAGMENTED:
2173       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2174         GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2175             "streamable=false. Will ignore that and create streamable output "
2176             "instead");
2177         qtmux->streamable = TRUE;
2178         g_object_notify (G_OBJECT (qtmux), "streamable");
2179       }
2180       break;
2181   }
2182
2183   /* let downstream know we think in BYTES and expect to do seeking later on */
2184   gst_segment_init (&segment, GST_FORMAT_BYTES);
2185   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2186
2187   GST_OBJECT_LOCK (qtmux);
2188
2189   if (qtmux->timescale == 0) {
2190     guint32 suggested_timescale = 0;
2191     GSList *walk;
2192
2193     /* Calculate a reasonable timescale for the moov:
2194      * If there is video, it is the biggest video track timescale or an even
2195      * multiple of it if it's smaller than 1800.
2196      * Otherwise it is 1800 */
2197     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2198       GstCollectData *cdata = (GstCollectData *) walk->data;
2199       GstQTPad *qpad = (GstQTPad *) cdata;
2200
2201       if (!qpad->trak)
2202         continue;
2203
2204       /* not video */
2205       if (!qpad->trak->mdia.minf.vmhd)
2206         continue;
2207
2208       suggested_timescale =
2209           MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
2210     }
2211
2212     if (suggested_timescale == 0)
2213       suggested_timescale = 1800;
2214
2215     while (suggested_timescale < 1800)
2216       suggested_timescale *= 2;
2217
2218     qtmux->timescale = suggested_timescale;
2219   }
2220
2221   /* initialize our moov recovery file */
2222   if (qtmux->moov_recov_file_path) {
2223     gst_qt_mux_prepare_moov_recovery (qtmux);
2224   }
2225
2226   /* Make sure the first time we update the moov, we'll
2227    * include any tagsetter tags */
2228   qtmux->tags_changed = TRUE;
2229
2230   GST_OBJECT_UNLOCK (qtmux);
2231
2232   /*
2233    * send mdat header if already needed, and mark position for later update.
2234    * We don't send ftyp now if we are on fast start mode, because we can
2235    * better fine tune using the information we gather to create the whole moov
2236    * atom.
2237    */
2238   switch (qtmux->mux_mode) {
2239     case GST_QT_MUX_MODE_MOOV_AT_END:
2240       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2241       if (ret != GST_FLOW_OK)
2242         break;
2243
2244       /* Store this as the mdat offset for later updating
2245        * when we write the moov */
2246       qtmux->mdat_pos = qtmux->header_size;
2247       /* extended atom in case we go over 4GB while writing and need
2248        * the full 64-bit atom */
2249       ret =
2250           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2251           FALSE);
2252       break;
2253     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2254
2255       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2256       if (ret != GST_FLOW_OK)
2257         break;
2258
2259       /* Pad ftyp out to an 8-byte boundary before starting the moov
2260        * ping pong region. It should be well less than 1 disk sector,
2261        * unless there's a bajillion compatible types listed,
2262        * but let's be sure the free atom doesn't cross a sector
2263        * boundary anyway */
2264       if (qtmux->header_size % 8) {
2265         /* Extra 8 bytes for the padding free atom header */
2266         guint padding = (guint) (16 - (qtmux->header_size % 8));
2267         GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2268         ret =
2269             gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2270             FALSE);
2271         if (ret != GST_FLOW_OK)
2272           return ret;
2273       }
2274
2275       /* Store this as the moov offset for later updating.
2276        * We record mdat position below */
2277       qtmux->moov_pos = qtmux->header_size;
2278
2279       /* Set up the initial 'ping' state of the ping-pong buffers */
2280       qtmux->reserved_moov_first_active = TRUE;
2281
2282       gst_qt_mux_configure_moov (qtmux);
2283       gst_qt_mux_setup_metadata (qtmux);
2284       /* Empty free atom to begin, starting on an 8-byte boundary */
2285       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2286       if (ret != GST_FLOW_OK)
2287         return ret;
2288       /* Moov header, not padded yet */
2289       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2290       if (ret != GST_FLOW_OK)
2291         return ret;
2292       /* The moov we just sent contains the 'base' size of the moov, before
2293        * we put in any time-dependent per-trak data. Use that to make
2294        * a good estimate of how much extra to reserve */
2295       /* Calculate how much space to reserve for our MOOV atom.
2296        * We actually reserve twice that, for ping-pong buffers */
2297       qtmux->base_moov_size = qtmux->last_moov_size;
2298       GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2299           qtmux->base_moov_size);
2300       qtmux->reserved_moov_size = qtmux->base_moov_size +
2301           gst_util_uint64_scale (reserved_max_duration,
2302           reserved_bytes_per_sec_per_trak *
2303           atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2304
2305       /* Need space for at least 4 atom headers. More really, but
2306        * this as an absolute minimum */
2307       if (qtmux->reserved_moov_size < 4 * 8)
2308         goto reserved_moov_too_small;
2309
2310       GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2311           2 * qtmux->reserved_moov_size + 16);
2312
2313       GST_OBJECT_LOCK (qtmux);
2314       qtmux->reserved_duration_remaining =
2315           gst_util_uint64_scale (qtmux->reserved_moov_size -
2316           qtmux->base_moov_size, GST_SECOND,
2317           reserved_bytes_per_sec_per_trak *
2318           atom_moov_get_trak_count (qtmux->moov));
2319       GST_OBJECT_UNLOCK (qtmux);
2320
2321       /* Now that we know how much reserved space is targetted,
2322        * output a free atom to fill the extra reserved */
2323       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2324           qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2325       if (ret != GST_FLOW_OK)
2326         return ret;
2327
2328       /* Then a free atom containing 'pong' buffer, with an
2329        * extra 8 bytes to account for the free atom header itself */
2330       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2331           qtmux->reserved_moov_size + 8, FALSE);
2332       if (ret != GST_FLOW_OK)
2333         return ret;
2334
2335       /* extra atoms go after the free/moov(s), before the mdat */
2336       ret =
2337           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2338       if (ret != GST_FLOW_OK)
2339         return ret;
2340
2341       qtmux->mdat_pos = qtmux->header_size;
2342       /* extended atom in case we go over 4GB while writing and need
2343        * the full 64-bit atom */
2344       ret =
2345           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2346           FALSE);
2347       break;
2348     case GST_QT_MUX_MODE_FAST_START:
2349       GST_OBJECT_LOCK (qtmux);
2350       qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2351       if (!qtmux->fast_start_file)
2352         goto open_failed;
2353       GST_OBJECT_UNLOCK (qtmux);
2354       /* send a dummy buffer for preroll */
2355       ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2356       break;
2357     case GST_QT_MUX_MODE_FRAGMENTED:
2358     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2359       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2360       if (ret != GST_FLOW_OK)
2361         break;
2362       /* store the moov pos so we can update the duration later
2363        * in non-streamable mode */
2364       qtmux->moov_pos = qtmux->header_size;
2365
2366       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2367           qtmux->fragment_duration);
2368       /* also used as snapshot marker to indicate fragmented file */
2369       qtmux->fragment_sequence = 1;
2370       /* prepare moov and/or tags */
2371       gst_qt_mux_configure_moov (qtmux);
2372       gst_qt_mux_setup_metadata (qtmux);
2373       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2374       if (ret != GST_FLOW_OK)
2375         return ret;
2376       /* extra atoms */
2377       ret =
2378           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2379       if (ret != GST_FLOW_OK)
2380         break;
2381       /* prepare index if not streamable */
2382       if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2383         qtmux->mfra = atom_mfra_new (qtmux->context);
2384       break;
2385   }
2386
2387   return ret;
2388   /* ERRORS */
2389 invalid_isml:
2390   {
2391     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2392         ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2393     return GST_FLOW_ERROR;
2394   }
2395 reserved_moov_too_small:
2396   {
2397     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2398         ("Not enough reserved space for creating headers"), (NULL));
2399     return GST_FLOW_ERROR;
2400   }
2401 open_failed:
2402   {
2403     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2404         (("Could not open temporary file \"%s\""),
2405             qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2406     GST_OBJECT_UNLOCK (qtmux);
2407     return GST_FLOW_ERROR;
2408   }
2409 }
2410
2411 static GstFlowReturn
2412 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2413 {
2414   GstFlowReturn ret = GST_FLOW_OK;
2415   GSList *walk;
2416
2417   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2418     GstCollectData *cdata = (GstCollectData *) walk->data;
2419     GstQTPad *qtpad = (GstQTPad *) cdata;
2420
2421     /* avoid add_buffer complaining if not negotiated
2422      * in which case no buffers either, so skipping */
2423     if (!qtpad->fourcc) {
2424       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2425           GST_PAD_NAME (qtpad->collect.pad));
2426       continue;
2427     }
2428
2429     /* send last buffer; also flushes possibly queued buffers/ts */
2430     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
2431         GST_PAD_NAME (qtpad->collect.pad));
2432     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
2433     if (ret != GST_FLOW_OK) {
2434       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
2435           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
2436           gst_flow_get_name (ret));
2437     }
2438   }
2439
2440   return ret;
2441 }
2442
2443 static void
2444 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
2445 {
2446   GSList *walk;
2447
2448   /* for setting some subtitles fields */
2449   guint max_width = 0;
2450   guint max_height = 0;
2451
2452   qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
2453
2454   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2455     GstCollectData *cdata = (GstCollectData *) walk->data;
2456     GstQTPad *qtpad = (GstQTPad *) cdata;
2457
2458     if (!qtpad->fourcc) {
2459       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2460           GST_PAD_NAME (qtpad->collect.pad));
2461       continue;
2462     }
2463
2464     /* having flushed above, can check for buffers now */
2465     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2466       /* determine max stream duration */
2467       if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
2468           || qtpad->last_dts > qtmux->last_dts) {
2469         qtmux->last_dts = qtpad->last_dts;
2470       }
2471       if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
2472           || qtpad->first_ts < qtmux->first_ts) {
2473         qtmux->first_ts = qtpad->first_ts;
2474       }
2475     }
2476
2477     /* subtitles need to know the video width/height,
2478      * it is stored shifted 16 bits to the left according to the
2479      * spec */
2480     max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
2481     max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
2482
2483     /* update average bitrate of streams if needed */
2484     {
2485       guint32 avgbitrate = 0;
2486       guint32 maxbitrate = qtpad->max_bitrate;
2487
2488       if (qtpad->avg_bitrate)
2489         avgbitrate = qtpad->avg_bitrate;
2490       else if (qtpad->total_duration > 0)
2491         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
2492             8 * GST_SECOND, qtpad->total_duration);
2493
2494       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
2495     }
2496   }
2497
2498   /* need to update values on subtitle traks now that we know the
2499    * max width and height */
2500   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2501     GstCollectData *cdata = (GstCollectData *) walk->data;
2502     GstQTPad *qtpad = (GstQTPad *) cdata;
2503
2504     if (!qtpad->fourcc) {
2505       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2506           GST_PAD_NAME (qtpad->collect.pad));
2507       continue;
2508     }
2509
2510     if (qtpad->fourcc == FOURCC_tx3g) {
2511       atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
2512     }
2513   }
2514 }
2515
2516 /* Called after gst_qt_mux_update_global_statistics() updates the
2517  * first_ts tracking, to create/set edit lists for delayed streams */
2518 static void
2519 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
2520 {
2521   GSList *walk;
2522
2523   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
2524       GST_TIME_ARGS (qtmux->first_ts));
2525   /* add/update EDTSs for late streams. configure_moov will have
2526    * set the trak durations above by summing the sample tables,
2527    * here we extend that if needing to insert an empty segment */
2528   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2529     GstCollectData *cdata = (GstCollectData *) walk->data;
2530     GstQTPad *qtpad = (GstQTPad *) cdata;
2531
2532     atom_trak_edts_clear (qtpad->trak);
2533
2534     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2535       guint32 lateness = 0;
2536       guint32 duration = qtpad->trak->tkhd.duration;
2537       gboolean has_gap;
2538
2539       has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
2540
2541       if (has_gap) {
2542         GstClockTime diff;
2543
2544         diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
2545         lateness = gst_util_uint64_scale_round (diff,
2546             qtmux->timescale, GST_SECOND);
2547
2548         if (lateness > 0) {
2549           GST_DEBUG_OBJECT (qtmux,
2550               "Pad %s is a late stream by %" GST_TIME_FORMAT,
2551               GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (lateness));
2552
2553           atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
2554               (guint32) (1 * 65536.0));
2555         }
2556       }
2557
2558       /* Always write an edit list for the whole track. In general this is not
2559        * necessary except for the case of having a gap or DTS adjustment but
2560        * it allows to give the whole track's duration in the usually more
2561        * accurate media timescale
2562        */
2563       {
2564         GstClockTime ctts = 0;
2565         guint32 media_start;
2566
2567         if (qtpad->first_ts > qtpad->first_dts)
2568           ctts = qtpad->first_ts - qtpad->first_dts;
2569
2570         media_start = gst_util_uint64_scale_round (ctts,
2571             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
2572
2573         /* atom_trak_set_elst_entry() has a quirk - if the edit list
2574          * is empty because there's no gap added above, this call
2575          * will not replace index 1, it will create the entry at index 0.
2576          * Luckily, that's exactly what we want here */
2577         atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
2578             (guint32) (1 * 65536.0));
2579       }
2580
2581       /* need to add the empty time to the trak duration */
2582       duration += lateness;
2583       qtpad->trak->tkhd.duration = duration;
2584       if (qtpad->tc_trak) {
2585         qtpad->tc_trak->tkhd.duration = duration;
2586         qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
2587       }
2588
2589       /* And possibly grow the moov duration */
2590       if (duration > qtmux->moov->mvhd.time_info.duration) {
2591         qtmux->moov->mvhd.time_info.duration = duration;
2592         qtmux->moov->mvex.mehd.fragment_duration = duration;
2593       }
2594     }
2595   }
2596 }
2597
2598 static GstFlowReturn
2599 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
2600 {
2601   GstSegment segment;
2602   GstBuffer *buf;
2603   GstMapInfo map;
2604   guint64 offset = qtpad->tc_pos;
2605
2606   g_assert (qtpad->tc_pos != -1);
2607
2608   gst_segment_init (&segment, GST_FORMAT_BYTES);
2609   segment.start = offset;
2610   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2611
2612   buf = gst_buffer_new_and_alloc (4);
2613   gst_buffer_map (buf, &map, GST_MAP_WRITE);
2614
2615   GST_WRITE_UINT32_BE (map.data,
2616       gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
2617   gst_buffer_unmap (buf, &map);
2618
2619   /* Reset this value, so the timecode won't be re-rewritten */
2620   qtpad->tc_pos = -1;
2621
2622   return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
2623 }
2624
2625 static GstFlowReturn
2626 gst_qt_mux_stop_file (GstQTMux * qtmux)
2627 {
2628   gboolean ret = GST_FLOW_OK;
2629   guint64 offset = 0, size = 0;
2630   gboolean large_file;
2631   GSList *walk;
2632
2633   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
2634
2635   /* pushing last buffers for each pad */
2636   if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
2637     return ret;
2638
2639   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2640     /* Streamable mode; no need to write duration or MFRA */
2641     GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
2642     return GST_FLOW_OK;
2643   }
2644
2645   gst_qt_mux_update_global_statistics (qtmux);
2646   for (walk = qtmux->collect->data; walk; walk = walk->next) {
2647     GstQTPad *qtpad = (GstQTPad *) walk->data;
2648
2649     if (qtpad->tc_pos != -1) {
2650       /* File is being stopped and timecode hasn't been updated. Update it now
2651        * with whatever we have */
2652       ret = gst_qt_mux_update_timecode (qtmux, qtpad);
2653       if (ret != GST_FLOW_OK)
2654         return ret;
2655     }
2656   }
2657
2658   switch (qtmux->mux_mode) {
2659     case GST_QT_MUX_MODE_FRAGMENTED:{
2660       GstSegment segment;
2661       guint8 *data = NULL;
2662       GstBuffer *buf;
2663
2664       size = offset = 0;
2665       GST_DEBUG_OBJECT (qtmux, "adding mfra");
2666       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
2667         goto serialize_error;
2668       buf = _gst_buffer_new_take_data (data, offset);
2669       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
2670       if (ret != GST_FLOW_OK)
2671         return ret;
2672
2673       /* only mvex duration is updated,
2674        * mvhd should be consistent with empty moov
2675        * (but TODO maybe some clients do not handle that well ?) */
2676       qtmux->moov->mvex.mehd.fragment_duration =
2677           gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
2678       GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
2679           GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
2680       /* seek and rewrite the header */
2681       gst_segment_init (&segment, GST_FORMAT_BYTES);
2682       segment.start = qtmux->moov_pos;
2683       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2684       /* no need to seek back */
2685       return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2686     }
2687     case GST_QT_MUX_MODE_ROBUST_RECORDING:{
2688       ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
2689       if (G_UNLIKELY (ret != GST_FLOW_OK))
2690         return ret;
2691       /* Finalise by writing the final size into the mdat. Up until now
2692        * it's been 0, which means 'rest of the file'
2693        * No need to seek back after this, we won't write any more */
2694       return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2695           qtmux->mdat_size, NULL, TRUE);
2696     }
2697     default:
2698       break;
2699   }
2700
2701   /* Moov-at-end or fast-start mode from here down */
2702   gst_qt_mux_configure_moov (qtmux);
2703
2704   gst_qt_mux_update_edit_lists (qtmux);
2705
2706   /* tags into file metadata */
2707   gst_qt_mux_setup_metadata (qtmux);
2708
2709   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
2710
2711   switch (qtmux->mux_mode) {
2712     case GST_QT_MUX_MODE_FAST_START:{
2713       /* if faststart, update the offset of the atoms in the movie with the offset
2714        * that the movie headers before mdat will cause.
2715        * Also, send the ftyp */
2716       offset = size = 0;
2717
2718       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2719       if (ret != GST_FLOW_OK) {
2720         goto ftyp_error;
2721       }
2722       /* copy into NULL to obtain size */
2723       if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
2724         goto serialize_error;
2725       GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
2726           offset);
2727       offset += qtmux->header_size + (large_file ? 16 : 8);
2728
2729       /* sum up with the extra atoms size */
2730       ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
2731       if (ret != GST_FLOW_OK)
2732         return ret;
2733       break;
2734     }
2735     default:
2736       offset = qtmux->header_size;
2737       break;
2738   }
2739
2740   /* Now that we know the size of moov + extra atoms, we can adjust
2741    * the chunk offsets stored into the moov */
2742   atom_moov_chunks_set_offset (qtmux->moov, offset);
2743
2744   /* write out moov and extra atoms */
2745   /* note: as of this point, we no longer care about tracking written data size,
2746    * since there is no more use for it anyway */
2747   ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2748   if (ret != GST_FLOW_OK)
2749     return ret;
2750
2751   /* extra atoms */
2752   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
2753   if (ret != GST_FLOW_OK)
2754     return ret;
2755
2756   switch (qtmux->mux_mode) {
2757     case GST_QT_MUX_MODE_MOOV_AT_END:
2758     {
2759       /* mdat needs update iff not using faststart */
2760       GST_DEBUG_OBJECT (qtmux, "updating mdat size");
2761       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2762           qtmux->mdat_size, NULL, FALSE);
2763       /* note; no seeking back to the end of file is done,
2764        * since we no longer write anything anyway */
2765       break;
2766     }
2767     case GST_QT_MUX_MODE_FAST_START:
2768     {
2769       /* send mdat atom and move buffered data into it */
2770       /* mdat_size = accumulated (buffered data) */
2771       ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
2772           large_file, FALSE);
2773       if (ret != GST_FLOW_OK)
2774         return ret;
2775       ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
2776       if (ret != GST_FLOW_OK)
2777         return ret;
2778       break;
2779     }
2780     default:
2781       g_assert_not_reached ();
2782   }
2783
2784   return ret;
2785
2786   /* ERRORS */
2787 serialize_error:
2788   {
2789     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2790         ("Failed to serialize moov"));
2791     return GST_FLOW_ERROR;
2792   }
2793 ftyp_error:
2794   {
2795     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
2796     return GST_FLOW_ERROR;
2797   }
2798 }
2799
2800 static GstFlowReturn
2801 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2802     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2803     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2804 {
2805   GstFlowReturn ret = GST_FLOW_OK;
2806
2807   /* setup if needed */
2808   if (G_UNLIKELY (!pad->traf || force))
2809     goto init;
2810
2811 flush:
2812   /* flush pad fragment if threshold reached,
2813    * or at new keyframe if we should be minding those in the first place */
2814   if (G_UNLIKELY (force || (sync && pad->sync) ||
2815           pad->fragment_duration < (gint64) delta)) {
2816     AtomMOOF *moof;
2817     guint64 size = 0, offset = 0;
2818     guint8 *data = NULL;
2819     GstBuffer *buffer;
2820     guint i, total_size;
2821
2822     /* now we know where moof ends up, update offset in tfra */
2823     if (pad->tfra)
2824       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2825
2826     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2827     /* takes ownership */
2828     atom_moof_add_traf (moof, pad->traf);
2829     pad->traf = NULL;
2830     atom_moof_copy_data (moof, &data, &size, &offset);
2831     buffer = _gst_buffer_new_take_data (data, offset);
2832     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2833         gst_buffer_get_size (buffer));
2834     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2835
2836     /* and actual data */
2837     total_size = 0;
2838     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2839       total_size +=
2840           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2841     }
2842
2843     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2844         atom_array_get_len (&pad->fragment_buffers), total_size);
2845     if (ret == GST_FLOW_OK)
2846       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2847           FALSE, FALSE);
2848     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2849       if (G_LIKELY (ret == GST_FLOW_OK))
2850         ret = gst_qt_mux_send_buffer (qtmux,
2851             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2852             FALSE);
2853       else
2854         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2855     }
2856
2857     atom_array_clear (&pad->fragment_buffers);
2858     atom_moof_free (moof);
2859     qtmux->fragment_sequence++;
2860     force = FALSE;
2861   }
2862
2863 init:
2864   if (G_UNLIKELY (!pad->traf)) {
2865     GST_LOG_OBJECT (qtmux, "setting up new fragment");
2866     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2867     atom_array_init (&pad->fragment_buffers, 512);
2868     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2869         atom_trak_get_timescale (pad->trak), 1000);
2870
2871     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2872       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2873       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2874     }
2875     atom_traf_set_base_decode_time (pad->traf, dts);
2876   }
2877
2878   /* add buffer and metadata */
2879   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2880       pad->sync && sync);
2881   atom_array_append (&pad->fragment_buffers, buf, 256);
2882   pad->fragment_duration -= delta;
2883
2884   if (pad->tfra) {
2885     guint32 sn = atom_traf_get_sample_num (pad->traf);
2886
2887     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2888       atom_tfra_add_entry (pad->tfra, dts, sn);
2889   }
2890
2891   if (G_UNLIKELY (force))
2892     goto flush;
2893
2894   return ret;
2895 }
2896
2897 /* Here's the clever bit of robust recording: Updating the moov
2898  * header is done using a ping-pong scheme inside 2 blocks of size
2899  * 'reserved_moov_size' at the start of the file, in such a way that the
2900  * file on-disk is always valid if interrupted.
2901  * Inside the reserved space, we have 2 pairs of free + moov atoms
2902  * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
2903  * at offset "reserved_moov_size".
2904  *
2905  * 1. Free-A has 0 size payload, moov-A immediately after is
2906  *    active/current, and is padded with an internal Free atom to
2907  *    end at reserved_space/2. Free-B is at reserved_space/2, sized
2908  *    to cover the remaining free space (including moov-B).
2909  * 2. We write moov-B (which is invisible inside free-B), and pad it to
2910  *    end at the end of free space. Then, we update free-A to size
2911  *    reserved_space/2 + sizeof(free-B), which hides moov-A and the
2912  *    free-B header, and makes moov-B active.
2913  * 3. Rewrite moov-A inside free-A, with padding out to free-B.
2914  *    Change the size of free-A to make moov-A active again.
2915  * 4. Rinse and repeat.
2916  *
2917  */
2918 static GstFlowReturn
2919 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
2920 {
2921   GstSegment segment;
2922   GstFlowReturn ret;
2923   guint64 freeA_offset;
2924   guint32 new_freeA_size;
2925   guint64 new_moov_offset;
2926
2927   /* Update moov info, then seek and rewrite the MOOV atom */
2928   gst_qt_mux_update_global_statistics (qtmux);
2929   gst_qt_mux_configure_moov (qtmux);
2930
2931   gst_qt_mux_update_edit_lists (qtmux);
2932
2933   /* tags into file metadata */
2934   gst_qt_mux_setup_metadata (qtmux);
2935
2936   /* chunks position is set relative to the first byte of the
2937    * MDAT atom payload. Set the overall offset into the file */
2938   atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
2939
2940   /* Calculate which moov to rewrite. qtmux->moov_pos points to
2941    * the start of the free-A header */
2942   freeA_offset = qtmux->moov_pos;
2943   if (qtmux->reserved_moov_first_active) {
2944     GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
2945     /* After this, freeA will include itself, moovA, plus the freeB
2946      * header */
2947     new_freeA_size = qtmux->reserved_moov_size + 16;
2948   } else {
2949     GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
2950     new_freeA_size = 8;
2951   }
2952   /* the moov we update is after free-A, calculate its offset */
2953   new_moov_offset = freeA_offset + new_freeA_size;
2954
2955   /* Swap ping-pong cadence marker */
2956   qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
2957
2958   /* seek and rewrite the MOOV atom */
2959   gst_segment_init (&segment, GST_FORMAT_BYTES);
2960   segment.start = new_moov_offset;
2961   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2962
2963   ret =
2964       gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
2965       TRUE);
2966   if (ret != GST_FLOW_OK)
2967     return ret;
2968
2969   /* Update the estimated recording space remaining, based on amount used so
2970    * far and duration muxed so far */
2971   if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
2972     GstClockTime remain;
2973     GstClockTime time_muxed = qtmux->last_dts;
2974
2975     remain =
2976         gst_util_uint64_scale (qtmux->reserved_moov_size -
2977         qtmux->last_moov_size, time_muxed,
2978         qtmux->last_moov_size - qtmux->base_moov_size);
2979     /* Always under-estimate slightly, so users
2980      * have time to stop muxing before we run out */
2981     if (remain < GST_SECOND / 2)
2982       remain = 0;
2983     else
2984       remain -= GST_SECOND / 2;
2985
2986     GST_INFO_OBJECT (qtmux,
2987         "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
2988         ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
2989         qtmux->reserved_moov_size, qtmux->last_moov_size,
2990         GST_TIME_ARGS (qtmux->last_dts),
2991         qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
2992
2993     GST_OBJECT_LOCK (qtmux);
2994     qtmux->reserved_duration_remaining = remain;
2995     qtmux->muxed_since_last_update = 0;
2996     GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
2997         G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
2998     GST_OBJECT_UNLOCK (qtmux);
2999   }
3000
3001
3002   /* Now update the moov-A size. Don't pass offset, since we don't need
3003    * send_free_atom() to seek for us - all our callers seek back to
3004    * where they need after this, or they don't need it */
3005   gst_segment_init (&segment, GST_FORMAT_BYTES);
3006   segment.start = freeA_offset;
3007   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3008
3009   ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3010
3011   return ret;
3012 }
3013
3014 static GstFlowReturn
3015 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3016 {
3017   GstSegment segment;
3018   GstFlowReturn flow_ret;
3019
3020   guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3021
3022   GST_OBJECT_LOCK (qtmux);
3023   if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3024     GST_OBJECT_UNLOCK (qtmux);
3025     return GST_FLOW_OK;
3026   }
3027
3028   /* Update if position is > the threshold or there's been no update yet */
3029   if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3030       (position <= qtmux->last_moov_update ||
3031           (position - qtmux->last_moov_update) <
3032           qtmux->reserved_moov_update_period)) {
3033     /* Update the offset of how much we've muxed, so the
3034      * report of remaining space keeps counting down */
3035     if (position > qtmux->last_moov_update &&
3036         position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3037       GST_LOG_OBJECT (qtmux,
3038           "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3039           qtmux->muxed_since_last_update);
3040       qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3041     }
3042     GST_OBJECT_UNLOCK (qtmux);
3043     return GST_FLOW_OK;         /* No update needed yet */
3044   }
3045
3046   qtmux->last_moov_update = position;
3047   GST_OBJECT_UNLOCK (qtmux);
3048
3049   GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3050       " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3051       GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3052
3053   flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3054   if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3055     return flow_ret;
3056
3057   /* Seek back to previous position */
3058   gst_segment_init (&segment, GST_FORMAT_BYTES);
3059   segment.start = mdat_offset;
3060   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3061
3062   return flow_ret;
3063 }
3064
3065 static GstFlowReturn
3066 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3067     GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3068     gint64 last_dts, gint64 scaled_duration, guint sample_size,
3069     guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3070 {
3071   GstFlowReturn ret = GST_FLOW_OK;
3072
3073   /* note that a new chunk is started each time (not fancy but works) */
3074   if (qtmux->moov_recov_file) {
3075     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3076             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3077             do_pts, pts_offset)) {
3078       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3079           "recovery file, disabling recovery");
3080       fclose (qtmux->moov_recov_file);
3081       qtmux->moov_recov_file = NULL;
3082     }
3083   }
3084
3085   switch (qtmux->mux_mode) {
3086     case GST_QT_MUX_MODE_MOOV_AT_END:
3087     case GST_QT_MUX_MODE_FAST_START:
3088     case GST_QT_MUX_MODE_ROBUST_RECORDING:
3089       atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3090           sample_size, chunk_offset, sync, pts_offset);
3091       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3092       /* Check if it's time to re-write the headers in robust-recording mode */
3093       if (ret == GST_FLOW_OK
3094           && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3095         ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3096       break;
3097     case GST_QT_MUX_MODE_FRAGMENTED:
3098     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3099       /* ensure that always sync samples are marked as such */
3100       ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3101           is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3102           sample_size, !pad->sync || sync, pts_offset);
3103       break;
3104   }
3105
3106   return ret;
3107 }
3108
3109 static GstFlowReturn
3110 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
3111     GstBuffer * buf, GstFlowReturn ret)
3112 {
3113   if (buf != NULL && (pad->tc_trak == NULL || pad->tc_pos != -1)) {
3114     GstVideoTimeCodeMeta *tc_meta = gst_buffer_get_video_time_code_meta (buf);
3115     if (tc_meta) {
3116       GstVideoTimeCode *tc = &tc_meta->tc;
3117       GstBuffer *tc_buf;
3118       gsize szret;
3119       guint32 frames_since_daily_jam;
3120
3121       /* This means we never got a timecode before */
3122       if (pad->first_tc == NULL) {
3123 #ifndef GST_DISABLE_GST_DEBUG
3124         gchar *tc_str = gst_video_time_code_to_string (tc);
3125         GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
3126         g_free (tc_str);
3127 #endif
3128         g_assert (pad->tc_trak == NULL);
3129         tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3130         pad->first_tc = gst_video_time_code_copy (tc);
3131         /* If frames are out of order, the frame we're currently getting might
3132          * not be the first one. Just write a 0 timecode for now and wait
3133          * until we receive a timecode that's lower than the current one */
3134         if (pad->is_out_of_order) {
3135           pad->first_pts = GST_BUFFER_PTS (buf);
3136           frames_since_daily_jam = 0;
3137           /* Position to rewrite */
3138           pad->tc_pos = qtmux->mdat_size;
3139         } else {
3140           frames_since_daily_jam =
3141               gst_video_time_code_frames_since_daily_jam (pad->first_tc);
3142           frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3143         }
3144         /* Write the timecode trak now */
3145         pad->tc_trak = atom_trak_new (qtmux->context);
3146         atom_moov_add_trak (qtmux->moov, pad->tc_trak);
3147
3148         pad->trak->tref = atom_tref_new (FOURCC_tmcd);
3149         atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
3150
3151         atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
3152             pad->first_tc);
3153
3154         szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3155         g_assert (szret == 4);
3156
3157         atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE,
3158             0);
3159         ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3160
3161         /* Need to reset the current chunk (of the previous pad) here because
3162          * some other data was written now above, and the pad has to start a
3163          * new chunk now */
3164         qtmux->current_chunk_offset = -1;
3165         qtmux->current_chunk_size = 0;
3166         qtmux->current_chunk_duration = 0;
3167       } else if (pad->is_out_of_order) {
3168         /* Check for a lower timecode than the one stored */
3169         g_assert (pad->tc_trak != NULL);
3170         if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
3171           if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
3172             gst_video_time_code_free (pad->first_tc);
3173             pad->first_tc = gst_video_time_code_copy (tc);
3174           }
3175         } else {
3176           guint64 bk_size = qtmux->mdat_size;
3177           GstSegment segment;
3178           /* If this frame's DTS is after the first PTS received, it means
3179            * we've already received the first frame to be presented. Otherwise
3180            * the decoder would need to go back in time */
3181           gst_qt_mux_update_timecode (qtmux, pad);
3182
3183           /* Reset writing position */
3184           gst_segment_init (&segment, GST_FORMAT_BYTES);
3185           segment.start = bk_size;
3186           gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3187         }
3188       }
3189     }
3190   }
3191   return ret;
3192 }
3193
3194 /*
3195  * Here we push the buffer and update the tables in the track atoms
3196  */
3197 static GstFlowReturn
3198 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
3199 {
3200   GstBuffer *last_buf = NULL;
3201   GstClockTime duration;
3202   guint nsamples, sample_size;
3203   guint64 chunk_offset;
3204   gint64 last_dts, scaled_duration;
3205   gint64 pts_offset = 0;
3206   gboolean sync = FALSE;
3207   GstFlowReturn ret = GST_FLOW_OK;
3208
3209   if (!pad->fourcc)
3210     goto not_negotiated;
3211
3212   /* if this pad has a prepare function, call it */
3213   if (pad->prepare_buf_func != NULL) {
3214     buf = pad->prepare_buf_func (pad, buf, qtmux);
3215   }
3216
3217   last_buf = pad->last_buf;
3218
3219   ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
3220
3221   if (last_buf == NULL) {
3222 #ifndef GST_DISABLE_GST_DEBUG
3223     if (buf == NULL) {
3224       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
3225           "received NULL buffer, doing nothing",
3226           GST_PAD_NAME (pad->collect.pad));
3227     } else {
3228       GST_LOG_OBJECT (qtmux,
3229           "Pad %s has no previous buffer stored, storing now",
3230           GST_PAD_NAME (pad->collect.pad));
3231     }
3232 #endif
3233     pad->last_buf = buf;
3234     goto exit;
3235   } else {
3236     gst_buffer_ref (last_buf);
3237   }
3238
3239   if (!GST_BUFFER_PTS_IS_VALID (last_buf))
3240     goto no_pts;
3241
3242   /* if this is the first buffer, store the timestamp */
3243   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
3244     if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3245       pad->first_ts = GST_BUFFER_PTS (last_buf);
3246     } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3247       pad->first_ts = GST_BUFFER_DTS (last_buf);
3248     }
3249
3250     if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3251       pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
3252     } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3253       pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
3254     }
3255
3256     if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
3257       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
3258     } else {
3259       GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
3260           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
3261       pad->first_ts = pad->first_dts = 0;
3262     }
3263     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
3264         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
3265         GST_TIME_ARGS (pad->first_ts));
3266   }
3267
3268   if (last_buf && buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
3269       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
3270       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
3271     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
3272         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
3273         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
3274     buf = gst_buffer_make_writable (buf);
3275     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
3276   }
3277
3278   /* duration actually means time delta between samples, so we calculate
3279    * the duration based on the difference in DTS or PTS, falling back
3280    * to DURATION if the other two don't exist, such as with the last
3281    * sample before EOS. Or use 0 if nothing else is available */
3282   if (GST_BUFFER_DURATION_IS_VALID (last_buf))
3283     duration = GST_BUFFER_DURATION (last_buf);
3284   else
3285     duration = 0;
3286   if (!pad->sparse) {
3287     if (last_buf && buf && GST_BUFFER_DTS_IS_VALID (buf)
3288         && GST_BUFFER_DTS_IS_VALID (last_buf))
3289       duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
3290     else if (last_buf && buf && GST_BUFFER_PTS_IS_VALID (buf)
3291         && GST_BUFFER_PTS_IS_VALID (last_buf))
3292       duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
3293   }
3294
3295   gst_buffer_replace (&pad->last_buf, buf);
3296
3297   if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
3298     GST_DEBUG_OBJECT (qtmux,
3299         "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
3300         ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
3301         GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
3302         qtmux->current_chunk_size,
3303         GST_TIME_ARGS (qtmux->current_chunk_duration));
3304     qtmux->current_pad = pad;
3305     if (qtmux->current_chunk_offset == -1)
3306       qtmux->current_chunk_offset = qtmux->mdat_size;
3307     else
3308       qtmux->current_chunk_offset += qtmux->current_chunk_size;
3309     qtmux->current_chunk_size = 0;
3310     qtmux->current_chunk_duration = 0;
3311   }
3312
3313   last_dts = gst_util_uint64_scale_round (pad->last_dts,
3314       atom_trak_get_timescale (pad->trak), GST_SECOND);
3315
3316   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
3317   if (pad->sample_size && !qtmux->fragment_sequence) {
3318     /* Constant size packets: usually raw audio (with many samples per
3319        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
3320      */
3321     sample_size = pad->sample_size;
3322     if (gst_buffer_get_size (last_buf) % sample_size != 0)
3323       goto fragmented_sample;
3324     /* note: qt raw audio storage warps it implicitly into a timewise
3325      * perfect stream, discarding buffer times */
3326     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
3327       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
3328           atom_trak_get_timescale (pad->trak), GST_SECOND);
3329       duration = GST_BUFFER_DURATION (last_buf);
3330     } else {
3331       nsamples = gst_buffer_get_size (last_buf) / sample_size;
3332       duration =
3333           gst_util_uint64_scale_round (nsamples, GST_SECOND,
3334           atom_trak_get_timescale (pad->trak));
3335     }
3336
3337     /* timescale = samplerate */
3338     scaled_duration = 1;
3339     pad->last_dts += duration * nsamples;
3340   } else {
3341     nsamples = 1;
3342     sample_size = gst_buffer_get_size (last_buf);
3343     if ((buf && GST_BUFFER_DTS_IS_VALID (buf))
3344         || GST_BUFFER_DTS_IS_VALID (last_buf)) {
3345       gint64 scaled_dts;
3346       if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
3347         pad->last_dts = GST_BUFFER_DTS (buf);
3348       } else {
3349         pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
3350       }
3351       if ((gint64) (pad->last_dts) < 0) {
3352         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
3353             atom_trak_get_timescale (pad->trak), GST_SECOND);
3354       } else {
3355         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
3356             atom_trak_get_timescale (pad->trak), GST_SECOND);
3357       }
3358       scaled_duration = scaled_dts - last_dts;
3359       last_dts = scaled_dts;
3360     } else {
3361       /* first convert intended timestamp (in GstClockTime resolution) to
3362        * trak timescale, then derive delta;
3363        * this ensures sums of (scale)delta add up to converted timestamp,
3364        * which only deviates at most 1/scale from timestamp itself */
3365       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
3366           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
3367       pad->last_dts += duration;
3368     }
3369   }
3370
3371   /* for computing the avg bitrate */
3372   if (G_LIKELY (last_buf)) {
3373     pad->total_bytes += gst_buffer_get_size (last_buf);
3374     pad->total_duration += duration;
3375   }
3376   qtmux->current_chunk_size += gst_buffer_get_size (last_buf);
3377   qtmux->current_chunk_duration += duration;
3378
3379   chunk_offset = qtmux->current_chunk_offset;
3380
3381   GST_LOG_OBJECT (qtmux,
3382       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
3383       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
3384   GST_LOG_OBJECT (qtmux,
3385       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
3386       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
3387       nsamples, scaled_duration, sample_size, chunk_offset);
3388
3389   /* might be a sync sample */
3390   if (pad->sync &&
3391       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
3392     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
3393         GST_PAD_NAME (pad->collect.pad));
3394     sync = TRUE;
3395   }
3396
3397   if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3398     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
3399         atom_trak_get_timescale (pad->trak), GST_SECOND);
3400     pts_offset =
3401         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3402             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
3403   } else {
3404     pts_offset = 0;
3405     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3406         atom_trak_get_timescale (pad->trak), GST_SECOND);
3407   }
3408   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
3409       " timebase_dts: %d pts_offset: %d",
3410       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
3411       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
3412       (int) (last_dts), (int) (pts_offset));
3413
3414   if (GST_CLOCK_TIME_IS_VALID (duration)
3415       && (qtmux->current_chunk_duration > qtmux->longest_chunk
3416           || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
3417     GST_DEBUG_OBJECT (qtmux,
3418         "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
3419         GST_TIME_ARGS (qtmux->current_chunk_duration),
3420         GST_PAD_NAME (pad->collect.pad));
3421     qtmux->longest_chunk = qtmux->current_chunk_duration;
3422   }
3423
3424   /* now we go and register this buffer/sample all over */
3425   ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
3426       buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
3427       chunk_offset, sync, TRUE, pts_offset);
3428
3429   /* if this is sparse and we have a next buffer, check if there is any gap
3430    * between them to insert an empty sample */
3431   if (pad->sparse && buf) {
3432     if (pad->create_empty_buffer) {
3433       GstBuffer *empty_buf;
3434       gint64 empty_duration =
3435           GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
3436       gint64 empty_duration_scaled;
3437
3438       empty_buf = pad->create_empty_buffer (pad, empty_duration);
3439
3440       empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
3441           atom_trak_get_timescale (pad->trak), GST_SECOND);
3442
3443       pad->total_bytes += gst_buffer_get_size (empty_buf);
3444       pad->total_duration += duration;
3445
3446       ret =
3447           gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
3448           last_dts + scaled_duration, empty_duration_scaled,
3449           gst_buffer_get_size (empty_buf), chunk_offset, sync, TRUE, 0);
3450     } else {
3451       /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
3452       g_assert_not_reached ();
3453       GST_WARNING_OBJECT (qtmux,
3454           "no empty buffer creation function found for pad %s",
3455           GST_PAD_NAME (pad->collect.pad));
3456     }
3457   }
3458
3459   if (buf)
3460     gst_buffer_unref (buf);
3461
3462 exit:
3463
3464   return ret;
3465
3466   /* ERRORS */
3467 bail:
3468   {
3469     if (buf)
3470       gst_buffer_unref (buf);
3471     gst_buffer_unref (last_buf);
3472     return GST_FLOW_ERROR;
3473   }
3474 fragmented_sample:
3475   {
3476     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3477         ("Audio buffer contains fragmented sample."));
3478     goto bail;
3479   }
3480 no_pts:
3481   {
3482     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
3483     goto bail;
3484   }
3485 not_negotiated:
3486   {
3487     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
3488         ("format wasn't negotiated before buffer flow on pad %s",
3489             GST_PAD_NAME (pad->collect.pad)));
3490     if (buf)
3491       gst_buffer_unref (buf);
3492     return GST_FLOW_NOT_NEGOTIATED;
3493   }
3494 }
3495
3496 /*
3497  * DTS running time can be negative. There is no way to represent that in
3498  * MP4 however, thus we need to offset DTS so that it starts from 0.
3499  */
3500 static void
3501 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
3502     GstCollectData * cdata, GstBuffer ** buf)
3503 {
3504   GstClockTime pts;
3505   gint64 dts;
3506
3507   pts = GST_BUFFER_PTS (*buf);
3508   dts = GST_COLLECT_PADS_DTS (cdata);
3509
3510   GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
3511       " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
3512       GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
3513
3514   if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
3515     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
3516       pad->dts_adjustment = -dts;
3517     else
3518       pad->dts_adjustment = 0;
3519   }
3520
3521   if (pad->dts_adjustment > 0) {
3522     *buf = gst_buffer_make_writable (*buf);
3523
3524     dts += pad->dts_adjustment;
3525
3526     if (GST_CLOCK_TIME_IS_VALID (pts))
3527       pts += pad->dts_adjustment;
3528
3529     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
3530       GST_WARNING_OBJECT (pad, "Decreasing DTS.");
3531       dts = 0;
3532     }
3533
3534     if (pts < dts) {
3535       GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
3536       pts = dts;
3537     }
3538
3539     GST_BUFFER_PTS (*buf) = pts;
3540     GST_BUFFER_DTS (*buf) = dts;
3541
3542     GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
3543         " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
3544   }
3545 }
3546
3547 static GstQTPad *
3548 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
3549 {
3550   GSList *walk;
3551   GstQTPad *best_pad = NULL;
3552
3553   if (qtmux->current_pad &&
3554       (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
3555       (qtmux->interleave_bytes == 0
3556           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
3557       && (qtmux->interleave_time == 0
3558           || qtmux->current_chunk_duration <= qtmux->interleave_time)
3559       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
3560       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3561     GstBuffer *tmp_buf =
3562         gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
3563
3564     if (tmp_buf || qtmux->current_pad->last_buf) {
3565       best_pad = qtmux->current_pad;
3566       if (tmp_buf)
3567         gst_buffer_unref (tmp_buf);
3568       GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
3569           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
3570     }
3571   } else if (qtmux->collect->data->next) {
3572     /* Only switch pads if we have more than one, otherwise
3573      * we can just put everything into a single chunk and save
3574      * a few bytes of offsets
3575      */
3576     if (qtmux->current_pad)
3577       GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
3578           GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
3579     best_pad = qtmux->current_pad = NULL;
3580   }
3581
3582   if (!best_pad) {
3583     GstClockTime best_time = GST_CLOCK_TIME_NONE;
3584
3585     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3586       GstCollectData *cdata = (GstCollectData *) walk->data;
3587       GstQTPad *qtpad = (GstQTPad *) cdata;
3588       GstBuffer *tmp_buf;
3589       GstClockTime timestamp;
3590
3591       tmp_buf = gst_collect_pads_peek (pads, cdata);
3592       if (!tmp_buf) {
3593         /* This one is newly EOS now, finish it for real */
3594         if (qtpad->last_buf) {
3595           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
3596         } else {
3597           continue;
3598         }
3599       } else {
3600         timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
3601       }
3602
3603       if (best_pad == NULL ||
3604           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
3605         best_pad = qtpad;
3606         best_time = timestamp;
3607       }
3608
3609       if (tmp_buf)
3610         gst_buffer_unref (tmp_buf);
3611     }
3612
3613     if (best_pad) {
3614       GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
3615           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
3616     } else {
3617       GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
3618     }
3619   }
3620
3621   return best_pad;
3622 }
3623
3624 static GstFlowReturn
3625 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
3626 {
3627   GstFlowReturn ret = GST_FLOW_OK;
3628   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
3629   GstQTPad *best_pad = NULL;
3630
3631   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
3632     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
3633       return ret;
3634
3635     qtmux->state = GST_QT_MUX_STATE_DATA;
3636   }
3637
3638   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
3639     return GST_FLOW_EOS;
3640
3641   best_pad = find_best_pad (qtmux, pads);
3642
3643   /* clipping already converted to running time */
3644   if (best_pad != NULL) {
3645     GstBuffer *buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
3646
3647     g_assert (buf || best_pad->last_buf);
3648     if (buf)
3649       gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
3650           (GstCollectData *) best_pad, &buf);
3651
3652     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
3653   } else {
3654     qtmux->state = GST_QT_MUX_STATE_EOS;
3655     ret = gst_qt_mux_stop_file (qtmux);
3656     if (ret == GST_FLOW_OK) {
3657       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
3658       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
3659       ret = GST_FLOW_EOS;
3660     } else {
3661       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
3662           gst_flow_get_name (ret));
3663     }
3664   }
3665
3666   return ret;
3667 }
3668
3669 static gboolean
3670 check_field (GQuark field_id, const GValue * value, gpointer user_data)
3671 {
3672   GstStructure *structure = (GstStructure *) user_data;
3673   const GValue *other = gst_structure_id_get_value (structure, field_id);
3674   if (other == NULL)
3675     return FALSE;
3676   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
3677 }
3678
3679 static gboolean
3680 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
3681     GstCaps * superset)
3682 {
3683   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
3684   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
3685
3686   return gst_structure_foreach (sub_s, check_field, sup_s);
3687 }
3688
3689 static gboolean
3690 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3691 {
3692   GstPad *pad = qtpad->collect.pad;
3693   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3694   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3695   GstStructure *structure;
3696   const gchar *mimetype;
3697   gint rate, channels;
3698   const GValue *value = NULL;
3699   const GstBuffer *codec_data = NULL;
3700   GstQTMuxFormat format;
3701   AudioSampleEntry entry = { 0, };
3702   AtomInfo *ext_atom = NULL;
3703   gint constant_size = 0;
3704   const gchar *stream_format;
3705
3706   qtpad->prepare_buf_func = NULL;
3707
3708   /* does not go well to renegotiate stream mid-way, unless
3709    * the old caps are a subset of the new one (this means upstream
3710    * added more info to the caps, as both should be 'fixed' caps) */
3711   if (qtpad->fourcc) {
3712     GstCaps *current_caps;
3713
3714     current_caps = gst_pad_get_current_caps (pad);
3715     g_assert (caps != NULL);
3716
3717     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3718       gst_caps_unref (current_caps);
3719       goto refuse_renegotiation;
3720     }
3721     GST_DEBUG_OBJECT (qtmux,
3722         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
3723         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
3724     gst_caps_unref (current_caps);
3725   }
3726
3727   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
3728       GST_DEBUG_PAD_NAME (pad), caps);
3729
3730   format = qtmux_klass->format;
3731   structure = gst_caps_get_structure (caps, 0);
3732   mimetype = gst_structure_get_name (structure);
3733
3734   /* common info */
3735   if (!gst_structure_get_int (structure, "channels", &channels) ||
3736       !gst_structure_get_int (structure, "rate", &rate)) {
3737     goto refuse_caps;
3738   }
3739
3740   /* optional */
3741   value = gst_structure_get_value (structure, "codec_data");
3742   if (value != NULL)
3743     codec_data = gst_value_get_buffer (value);
3744
3745   qtpad->is_out_of_order = FALSE;
3746
3747   /* set common properties */
3748   entry.sample_rate = rate;
3749   entry.channels = channels;
3750   /* default */
3751   entry.sample_size = 16;
3752   /* this is the typical compressed case */
3753   if (format == GST_QT_MUX_FORMAT_QT) {
3754     entry.version = 1;
3755     entry.compression_id = -2;
3756   }
3757
3758   /* now map onto a fourcc, and some extra properties */
3759   if (strcmp (mimetype, "audio/mpeg") == 0) {
3760     gint mpegversion = 0, mpegaudioversion = 0;
3761     gint layer = -1;
3762
3763     gst_structure_get_int (structure, "mpegversion", &mpegversion);
3764     switch (mpegversion) {
3765       case 1:
3766         gst_structure_get_int (structure, "layer", &layer);
3767         gst_structure_get_int (structure, "mpegaudioversion",
3768             &mpegaudioversion);
3769
3770         /* mp1/2/3 */
3771         /* note: QuickTime player does not like mp3 either way in iso/mp4 */
3772         if (format == GST_QT_MUX_FORMAT_QT)
3773           entry.fourcc = FOURCC__mp3;
3774         else {
3775           entry.fourcc = FOURCC_mp4a;
3776           ext_atom =
3777               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
3778               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3779               qtpad->max_bitrate);
3780         }
3781         if (layer == 1) {
3782           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3783           entry.samples_per_packet = 384;
3784         } else if (layer == 2) {
3785           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3786           entry.samples_per_packet = 1152;
3787         } else {
3788           g_warn_if_fail (layer == 3);
3789           entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
3790         }
3791         entry.bytes_per_sample = 2;
3792         break;
3793       case 4:
3794
3795         /* check stream-format */
3796         stream_format = gst_structure_get_string (structure, "stream-format");
3797         if (stream_format) {
3798           if (strcmp (stream_format, "raw") != 0) {
3799             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
3800                 "please use 'raw'", stream_format);
3801             goto refuse_caps;
3802           }
3803         } else {
3804           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
3805               "assuming 'raw'");
3806         }
3807
3808         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
3809           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
3810           goto refuse_caps;
3811         } else {
3812           guint8 profile;
3813
3814           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
3815           /* warn if not Low Complexity profile */
3816           profile >>= 3;
3817           if (profile != 2)
3818             GST_WARNING_OBJECT (qtmux,
3819                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
3820         }
3821
3822         /* AAC */
3823         entry.fourcc = FOURCC_mp4a;
3824
3825         if (format == GST_QT_MUX_FORMAT_QT)
3826           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
3827               qtpad->avg_bitrate, qtpad->max_bitrate);
3828         else
3829           ext_atom =
3830               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
3831               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3832               qtpad->max_bitrate);
3833         break;
3834       default:
3835         break;
3836     }
3837   } else if (strcmp (mimetype, "audio/AMR") == 0) {
3838     entry.fourcc = FOURCC_samr;
3839     entry.sample_size = 16;
3840     entry.samples_per_packet = 160;
3841     entry.bytes_per_sample = 2;
3842     ext_atom = build_amr_extension ();
3843   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
3844     entry.fourcc = FOURCC_sawb;
3845     entry.sample_size = 16;
3846     entry.samples_per_packet = 320;
3847     entry.bytes_per_sample = 2;
3848     ext_atom = build_amr_extension ();
3849   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
3850     GstAudioInfo info;
3851
3852     gst_audio_info_init (&info);
3853     if (!gst_audio_info_from_caps (&info, caps))
3854       goto refuse_caps;
3855
3856     /* spec has no place for a distinction in these */
3857     if (info.finfo->width != info.finfo->depth) {
3858       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
3859       goto refuse_caps;
3860     }
3861
3862     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
3863       if (info.finfo->endianness == G_LITTLE_ENDIAN)
3864         entry.fourcc = FOURCC_sowt;
3865       else if (info.finfo->endianness == G_BIG_ENDIAN)
3866         entry.fourcc = FOURCC_twos;
3867       else
3868         entry.fourcc = FOURCC_sowt;
3869       /* maximum backward compatibility; only new version for > 16 bit */
3870       if (info.finfo->depth <= 16)
3871         entry.version = 0;
3872       /* not compressed in any case */
3873       entry.compression_id = 0;
3874       /* QT spec says: max at 16 bit even if sample size were actually larger,
3875        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
3876       entry.sample_size = info.finfo->depth;
3877       entry.bytes_per_sample = info.finfo->depth / 8;
3878       entry.samples_per_packet = 1;
3879       entry.bytes_per_packet = info.finfo->depth / 8;
3880       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
3881     } else {
3882       if (info.finfo->width == 8 && info.finfo->depth == 8) {
3883         /* fall back to old 8-bit version */
3884         entry.fourcc = FOURCC_raw_;
3885         entry.version = 0;
3886         entry.compression_id = 0;
3887         entry.sample_size = 8;
3888       } else {
3889         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
3890         goto refuse_caps;
3891       }
3892     }
3893     constant_size = (info.finfo->depth / 8) * info.channels;
3894   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
3895     entry.fourcc = FOURCC_alaw;
3896     entry.samples_per_packet = 1023;
3897     entry.bytes_per_sample = 2;
3898   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
3899     entry.fourcc = FOURCC_ulaw;
3900     entry.samples_per_packet = 1023;
3901     entry.bytes_per_sample = 2;
3902   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
3903     gint blocksize;
3904     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
3905       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
3906       goto refuse_caps;
3907     }
3908     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
3909        0x11 */
3910     entry.fourcc = MS_WAVE_FOURCC (0x11);
3911     /* 4 byte header per channel (including one sample). 2 samples per byte
3912        remaining. Simplifying gives the following (samples per block per
3913        channel) */
3914     entry.samples_per_packet = 2 * blocksize / channels - 7;
3915     entry.bytes_per_sample = 2;
3916
3917     entry.bytes_per_frame = blocksize;
3918     entry.bytes_per_packet = blocksize / channels;
3919     /* ADPCM has constant size packets */
3920     constant_size = 1;
3921     /* TODO: I don't really understand why this helps, but it does! Constant
3922      * size and compression_id of -2 seem to be incompatible, and other files
3923      * in the wild use this too. */
3924     entry.compression_id = -1;
3925
3926     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
3927   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
3928     GstBuffer *codec_config;
3929     gint len;
3930     GstMapInfo map;
3931
3932     entry.fourcc = FOURCC_alac;
3933     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
3934     /* let's check if codec data already comes with 'alac' atom prefix */
3935     if (!codec_data || (len = map.size) < 28) {
3936       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
3937       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3938       goto refuse_caps;
3939     }
3940     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
3941       len -= 8;
3942       codec_config =
3943           gst_buffer_copy_region ((GstBuffer *) codec_data,
3944           GST_BUFFER_COPY_MEMORY, 8, len);
3945     } else {
3946       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
3947     }
3948     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3949     if (len != 28) {
3950       /* does not look good, but perhaps some trailing unneeded stuff */
3951       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
3952     }
3953     if (format == GST_QT_MUX_FORMAT_QT)
3954       ext_atom = build_mov_alac_extension (codec_config);
3955     else
3956       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
3957     /* set some more info */
3958     gst_buffer_map (codec_config, &map, GST_MAP_READ);
3959     entry.bytes_per_sample = 2;
3960     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
3961     gst_buffer_unmap (codec_config, &map);
3962     gst_buffer_unref (codec_config);
3963   } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
3964     entry.fourcc = FOURCC_ac_3;
3965
3966     /* Fixed values according to TS 102 366 but it also mentions that
3967      * they should be ignored */
3968     entry.channels = 2;
3969     entry.sample_size = 16;
3970
3971     /* AC-3 needs an extension atom but its data can only be obtained from
3972      * the stream itself. Abuse the prepare_buf_func so we parse a frame
3973      * and get the needed data */
3974     qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
3975   } else if (strcmp (mimetype, "audio/x-opus") == 0) {
3976     /* Based on the specification defined in:
3977      * https://www.opus-codec.org/docs/opus_in_isobmff.html */
3978     guint8 channels, mapping_family, stream_count, coupled_count;
3979     guint16 pre_skip;
3980     gint16 output_gain;
3981     guint32 rate;
3982     guint8 channel_mapping[256];
3983     const GValue *streamheader;
3984     const GValue *first_element;
3985     GstBuffer *header;
3986
3987     entry.fourcc = FOURCC_opus;
3988     entry.sample_size = 16;
3989
3990     streamheader = gst_structure_get_value (structure, "streamheader");
3991     if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
3992         gst_value_array_get_size (streamheader) != 0) {
3993       first_element = gst_value_array_get_value (streamheader, 0);
3994       header = gst_value_get_buffer (first_element);
3995       if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
3996               &mapping_family, &stream_count, &coupled_count, channel_mapping,
3997               &pre_skip, &output_gain)) {
3998         GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
3999         goto refuse_caps;
4000       }
4001     } else {
4002       GST_WARNING_OBJECT (qtmux,
4003           "no streamheader field in caps %" GST_PTR_FORMAT, caps);
4004
4005       if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
4006               &mapping_family, &stream_count, &coupled_count,
4007               channel_mapping)) {
4008         GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
4009         goto refuse_caps;
4010       }
4011       pre_skip = 0;
4012       output_gain = 0;
4013     }
4014
4015     entry.channels = channels;
4016     ext_atom = build_opus_extension (rate, channels, mapping_family,
4017         stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
4018   }
4019
4020   if (!entry.fourcc)
4021     goto refuse_caps;
4022
4023   /* ok, set the pad info accordingly */
4024   qtpad->fourcc = entry.fourcc;
4025   qtpad->sample_size = constant_size;
4026   qtpad->trak_ste =
4027       (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
4028       qtmux->context, &entry,
4029       qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
4030       ext_atom, constant_size);
4031
4032   gst_object_unref (qtmux);
4033   return TRUE;
4034
4035   /* ERRORS */
4036 refuse_caps:
4037   {
4038     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4039         GST_PAD_NAME (pad), caps);
4040     gst_object_unref (qtmux);
4041     return FALSE;
4042   }
4043 refuse_renegotiation:
4044   {
4045     GST_WARNING_OBJECT (qtmux,
4046         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
4047         GST_PAD_NAME (pad), caps);
4048     gst_object_unref (qtmux);
4049     return FALSE;
4050   }
4051 }
4052
4053 /* return number of centiframes per second */
4054 static guint
4055 adjust_rate (gint n, gint d)
4056 {
4057   if (n == 0)
4058     return 10000;
4059
4060   if (d != 1 && d != 1001) {
4061     /* otherwise there are probably rounding errors and we should rather guess
4062      * if it's close enough to a well known framerate */
4063     gst_video_guess_framerate (gst_util_uint64_scale (d, GST_SECOND, n), &n,
4064         &d);
4065   }
4066
4067   return gst_util_uint64_scale (n, 100, d);
4068 }
4069
4070 static gboolean
4071 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4072 {
4073   GstPad *pad = qtpad->collect.pad;
4074   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4075   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4076   GstStructure *structure;
4077   const gchar *mimetype;
4078   gint width, height, depth = -1;
4079   gint framerate_num, framerate_den;
4080   guint32 rate;
4081   const GValue *value = NULL;
4082   const GstBuffer *codec_data = NULL;
4083   VisualSampleEntry entry = { 0, };
4084   GstQTMuxFormat format;
4085   AtomInfo *ext_atom = NULL;
4086   GList *ext_atom_list = NULL;
4087   gboolean sync = FALSE;
4088   int par_num, par_den;
4089
4090   qtpad->prepare_buf_func = NULL;
4091
4092   /* does not go well to renegotiate stream mid-way, unless
4093    * the old caps are a subset of the new one (this means upstream
4094    * added more info to the caps, as both should be 'fixed' caps) */
4095   if (qtpad->fourcc) {
4096     GstCaps *current_caps;
4097
4098     current_caps = gst_pad_get_current_caps (pad);
4099     g_assert (caps != NULL);
4100
4101     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4102       gst_caps_unref (current_caps);
4103       goto refuse_renegotiation;
4104     }
4105     GST_DEBUG_OBJECT (qtmux,
4106         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4107         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4108     gst_caps_unref (current_caps);
4109   }
4110
4111   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4112       GST_DEBUG_PAD_NAME (pad), caps);
4113
4114   format = qtmux_klass->format;
4115   structure = gst_caps_get_structure (caps, 0);
4116   mimetype = gst_structure_get_name (structure);
4117
4118   /* required parts */
4119   if (!gst_structure_get_int (structure, "width", &width) ||
4120       !gst_structure_get_int (structure, "height", &height))
4121     goto refuse_caps;
4122
4123   /* optional */
4124   depth = -1;
4125   /* works as a default timebase */
4126   framerate_num = 10000;
4127   framerate_den = 1;
4128   gst_structure_get_fraction (structure, "framerate", &framerate_num,
4129       &framerate_den);
4130   gst_structure_get_int (structure, "depth", &depth);
4131   value = gst_structure_get_value (structure, "codec_data");
4132   if (value != NULL)
4133     codec_data = gst_value_get_buffer (value);
4134
4135   par_num = 1;
4136   par_den = 1;
4137   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
4138       &par_den);
4139
4140   qtpad->is_out_of_order = FALSE;
4141
4142   /* bring frame numerator into a range that ensures both reasonable resolution
4143    * as well as a fair duration */
4144   rate = qtmux->trak_timescale ?
4145       qtmux->trak_timescale : adjust_rate (framerate_num, framerate_den);
4146   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
4147       rate);
4148
4149   /* set common properties */
4150   entry.width = width;
4151   entry.height = height;
4152   entry.par_n = par_num;
4153   entry.par_d = par_den;
4154   /* should be OK according to qt and iso spec, override if really needed */
4155   entry.color_table_id = -1;
4156   entry.frame_count = 1;
4157   entry.depth = 24;
4158
4159   /* sync entries by default */
4160   sync = TRUE;
4161
4162   /* now map onto a fourcc, and some extra properties */
4163   if (strcmp (mimetype, "video/x-raw") == 0) {
4164     const gchar *format;
4165     GstVideoFormat fmt;
4166     const GstVideoFormatInfo *vinfo;
4167
4168     format = gst_structure_get_string (structure, "format");
4169     fmt = gst_video_format_from_string (format);
4170     vinfo = gst_video_format_get_info (fmt);
4171
4172     switch (fmt) {
4173       case GST_VIDEO_FORMAT_UYVY:
4174         if (depth == -1)
4175           depth = 24;
4176         entry.fourcc = FOURCC_2vuy;
4177         entry.depth = depth;
4178         sync = FALSE;
4179         break;
4180       case GST_VIDEO_FORMAT_v210:
4181         if (depth == -1)
4182           depth = 24;
4183         entry.fourcc = FOURCC_v210;
4184         entry.depth = depth;
4185         sync = FALSE;
4186         break;
4187       default:
4188         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
4189           entry.fourcc = FOURCC_raw_;
4190           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
4191           sync = FALSE;
4192         }
4193         break;
4194     }
4195   } else if (strcmp (mimetype, "video/x-h263") == 0) {
4196     ext_atom = NULL;
4197     if (format == GST_QT_MUX_FORMAT_QT)
4198       entry.fourcc = FOURCC_h263;
4199     else
4200       entry.fourcc = FOURCC_s263;
4201     ext_atom = build_h263_extension ();
4202     if (ext_atom != NULL)
4203       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4204   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
4205       strcmp (mimetype, "video/mpeg") == 0) {
4206     gint version = 0;
4207
4208     if (strcmp (mimetype, "video/x-divx") == 0) {
4209       gst_structure_get_int (structure, "divxversion", &version);
4210       version = version == 5 ? 1 : 0;
4211     } else {
4212       gst_structure_get_int (structure, "mpegversion", &version);
4213       version = version == 4 ? 1 : 0;
4214     }
4215     if (version) {
4216       entry.fourcc = FOURCC_mp4v;
4217       ext_atom =
4218           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
4219           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
4220           qtpad->max_bitrate);
4221       if (ext_atom != NULL)
4222         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4223       if (!codec_data)
4224         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
4225             "output might not play in Apple QuickTime (try global-headers?)");
4226     }
4227   } else if (strcmp (mimetype, "video/x-h264") == 0) {
4228     if (!codec_data) {
4229       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
4230       goto refuse_caps;
4231     }
4232
4233     entry.fourcc = FOURCC_avc1;
4234
4235     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4236     if (ext_atom != NULL)
4237       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4238     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
4239     if (ext_atom != NULL)
4240       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4241   } else if (strcmp (mimetype, "video/x-h265") == 0) {
4242     const gchar *format;
4243
4244     if (!codec_data) {
4245       GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
4246       goto refuse_caps;
4247     }
4248
4249     format = gst_structure_get_string (structure, "stream-format");
4250     if (strcmp (format, "hvc1") == 0)
4251       entry.fourcc = FOURCC_hvc1;
4252     else if (strcmp (format, "hev1") == 0)
4253       entry.fourcc = FOURCC_hev1;
4254
4255     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4256     if (ext_atom != NULL)
4257       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4258
4259     ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
4260     if (ext_atom != NULL)
4261       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4262
4263   } else if (strcmp (mimetype, "video/x-svq") == 0) {
4264     gint version = 0;
4265     const GstBuffer *seqh = NULL;
4266     const GValue *seqh_value;
4267     gdouble gamma = 0;
4268
4269     gst_structure_get_int (structure, "svqversion", &version);
4270     if (version == 3) {
4271       entry.fourcc = FOURCC_SVQ3;
4272       entry.version = 3;
4273       entry.depth = 32;
4274
4275       seqh_value = gst_structure_get_value (structure, "seqh");
4276       if (seqh_value) {
4277         seqh = gst_value_get_buffer (seqh_value);
4278         ext_atom = build_SMI_atom (seqh);
4279         if (ext_atom)
4280           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4281       }
4282
4283       /* we need to add the gamma anyway because quicktime might crash
4284        * when it doesn't find it */
4285       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
4286         /* it seems that using 0 here makes it ignored */
4287         gamma = 0.0;
4288       }
4289       ext_atom = build_gama_atom (gamma);
4290       if (ext_atom)
4291         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4292     } else {
4293       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
4294           "a bug at http://bugzilla.gnome.org", version);
4295     }
4296   } else if (strcmp (mimetype, "video/x-dv") == 0) {
4297     gint version = 0;
4298     gboolean pal = TRUE;
4299
4300     sync = FALSE;
4301     if (framerate_num != 25 || framerate_den != 1)
4302       pal = FALSE;
4303     gst_structure_get_int (structure, "dvversion", &version);
4304     /* fall back to typical one */
4305     if (!version)
4306       version = 25;
4307     switch (version) {
4308       case 25:
4309         if (pal)
4310           entry.fourcc = FOURCC_dvcp;
4311         else
4312           entry.fourcc = FOURCC_dvc_;
4313         break;
4314       case 50:
4315         if (pal)
4316           entry.fourcc = FOURCC_dv5p;
4317         else
4318           entry.fourcc = FOURCC_dv5n;
4319         break;
4320       default:
4321         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
4322         break;
4323     }
4324   } else if (strcmp (mimetype, "image/jpeg") == 0) {
4325     entry.fourcc = FOURCC_jpeg;
4326     sync = FALSE;
4327   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
4328       strcmp (mimetype, "image/x-jpc") == 0) {
4329     const gchar *colorspace;
4330     const GValue *cmap_array;
4331     const GValue *cdef_array;
4332     gint ncomp = 0;
4333
4334     if (strcmp (mimetype, "image/x-jpc") == 0) {
4335       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
4336     }
4337
4338     gst_structure_get_int (structure, "num-components", &ncomp);
4339     cmap_array = gst_structure_get_value (structure, "component-map");
4340     cdef_array = gst_structure_get_value (structure, "channel-definitions");
4341
4342     ext_atom = NULL;
4343     entry.fourcc = FOURCC_mjp2;
4344     sync = FALSE;
4345
4346     colorspace = gst_structure_get_string (structure, "colorspace");
4347     if (colorspace &&
4348         (ext_atom =
4349             build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
4350                 cdef_array)) != NULL) {
4351       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4352
4353       ext_atom = build_jp2x_extension (codec_data);
4354       if (ext_atom)
4355         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4356     } else {
4357       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
4358       goto refuse_caps;
4359     }
4360   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
4361     entry.fourcc = FOURCC_VP80;
4362     sync = FALSE;
4363   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
4364     entry.fourcc = FOURCC_drac;
4365   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
4366     guint32 fourcc = 0;
4367
4368     gst_structure_get_uint (structure, "format", &fourcc);
4369     entry.fourcc = fourcc;
4370   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
4371     guint32 fourcc = 0;
4372
4373     gst_structure_get_uint (structure, "format", &fourcc);
4374     entry.fourcc = fourcc;
4375   } else if (strcmp (mimetype, "video/x-prores") == 0) {
4376     const gchar *variant;
4377
4378     variant = gst_structure_get_string (structure, "variant");
4379     if (!variant || !g_strcmp0 (variant, "standard"))
4380       entry.fourcc = FOURCC_apcn;
4381     else if (!g_strcmp0 (variant, "lt"))
4382       entry.fourcc = FOURCC_apcs;
4383     else if (!g_strcmp0 (variant, "hq"))
4384       entry.fourcc = FOURCC_apch;
4385     else if (!g_strcmp0 (variant, "proxy"))
4386       entry.fourcc = FOURCC_apco;
4387     else if (!g_strcmp0 (variant, "4444"))
4388       entry.fourcc = FOURCC_ap4h;
4389     else if (!g_strcmp0 (variant, "4444xq"))
4390       entry.fourcc = FOURCC_ap4x;
4391
4392     sync = FALSE;
4393
4394     if (!qtmux->interleave_time_set)
4395       qtmux->interleave_time = 500 * GST_MSECOND;
4396     if (!qtmux->interleave_bytes_set)
4397       qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
4398   } else if (strcmp (mimetype, "video/x-cineform") == 0) {
4399     entry.fourcc = FOURCC_cfhd;
4400     sync = FALSE;
4401   }
4402
4403   if (!entry.fourcc)
4404     goto refuse_caps;
4405
4406   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
4407       qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
4408     const gchar *s;
4409     GstVideoColorimetry colorimetry;
4410
4411     s = gst_structure_get_string (structure, "colorimetry");
4412     if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
4413       ext_atom =
4414           build_colr_extension (&colorimetry,
4415           qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
4416       if (ext_atom)
4417         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4418     }
4419   }
4420
4421   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
4422       || strcmp (mimetype, "image/x-j2c") == 0
4423       || strcmp (mimetype, "image/x-jpc") == 0) {
4424     const gchar *s;
4425     GstVideoInterlaceMode interlace_mode;
4426     GstVideoFieldOrder field_order;
4427     gint fields = -1;
4428
4429     if (strcmp (mimetype, "image/x-j2c") == 0 ||
4430         strcmp (mimetype, "image/x-jpc") == 0) {
4431
4432       fields = 1;
4433       gst_structure_get_int (structure, "fields", &fields);
4434     }
4435
4436     s = gst_structure_get_string (structure, "interlace-mode");
4437     if (s)
4438       interlace_mode = gst_video_interlace_mode_from_string (s);
4439     else
4440       interlace_mode =
4441           (fields <=
4442           1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
4443           GST_VIDEO_INTERLACE_MODE_MIXED;
4444
4445     field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
4446     if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
4447       s = gst_structure_get_string (structure, "field-order");
4448       if (s)
4449         field_order = gst_video_field_order_from_string (s);
4450     }
4451
4452     ext_atom = build_fiel_extension (interlace_mode, field_order);
4453     if (ext_atom)
4454       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4455   }
4456
4457
4458   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
4459       width > 640 && width <= 1052 && height >= 480 && height <= 576) {
4460     /* The 'clap' extension is also defined for MP4 but inventing values in
4461      * general seems a bit tricky for this one. We only write it for
4462      * SD resolution in MOV, where it is a requirement.
4463      * The same goes for the 'tapt' extension, just that it is not defined for
4464      * MP4 and only for MOV
4465      */
4466     gint dar_num, dar_den;
4467     gint clef_width, clef_height, prof_width;
4468     gint clap_width_n, clap_width_d, clap_height;
4469     gint cdiv;
4470     double approx_dar;
4471
4472     /* First, guess display aspect ratio based on pixel aspect ratio,
4473      * width and height. We assume that display aspect ratio is either
4474      * 4:3 or 16:9
4475      */
4476     approx_dar = (gdouble) (width * par_num) / (height * par_den);
4477     if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
4478       dar_num = 4;
4479       dar_den = 3;
4480     } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
4481       dar_num = 16;
4482       dar_den = 9;
4483     } else {
4484       dar_num = width * par_num;
4485       dar_den = height * par_den;
4486       cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
4487       dar_num /= cdiv;
4488       dar_den /= cdiv;
4489     }
4490
4491     /* Then, calculate clean-aperture values (clap and clef)
4492      * using the guessed DAR.
4493      */
4494     clef_height = clap_height = (height == 486 ? 480 : height);
4495     clef_width = gst_util_uint64_scale (clef_height,
4496         dar_num * G_GUINT64_CONSTANT (65536), dar_den);
4497     prof_width = gst_util_uint64_scale (width,
4498         par_num * G_GUINT64_CONSTANT (65536), par_den);
4499     clap_width_n = clap_height * dar_num * par_den;
4500     clap_width_d = dar_den * par_num;
4501     cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
4502     clap_width_n /= cdiv;
4503     clap_width_d /= cdiv;
4504
4505     ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
4506         height << 16, width << 16, height << 16);
4507     qtpad->trak->tapt = ext_atom;
4508
4509     ext_atom = build_clap_extension (clap_width_n, clap_width_d,
4510         clap_height, 1, 0, 1, 0, 1);
4511     if (ext_atom)
4512       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4513   }
4514
4515   /* ok, set the pad info accordingly */
4516   qtpad->fourcc = entry.fourcc;
4517   qtpad->sync = sync;
4518   qtpad->trak_ste =
4519       (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
4520       qtmux->context, &entry, rate, ext_atom_list);
4521   if (strcmp (mimetype, "video/x-prores") == 0) {
4522     SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
4523     const gchar *compressor = NULL;
4524     mp4v->spatial_quality = 0x3FF;
4525     mp4v->temporal_quality = 0;
4526     mp4v->vendor = FOURCC_appl;
4527     mp4v->horizontal_resolution = 72 << 16;
4528     mp4v->vertical_resolution = 72 << 16;
4529     mp4v->depth = (entry.fourcc == FOURCC_ap4h
4530         || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
4531
4532     /* Set compressor name, required by some software */
4533     switch (entry.fourcc) {
4534       case FOURCC_apcn:
4535         compressor = "Apple ProRes 422";
4536         break;
4537       case FOURCC_apcs:
4538         compressor = "Apple ProRes 422 LT";
4539         break;
4540       case FOURCC_apch:
4541         compressor = "Apple ProRes 422 HQ";
4542         break;
4543       case FOURCC_apco:
4544         compressor = "Apple ProRes 422 Proxy";
4545         break;
4546       case FOURCC_ap4h:
4547         compressor = "Apple ProRes 4444";
4548         break;
4549       case FOURCC_ap4x:
4550         compressor = "Apple ProRes 4444 XQ";
4551         break;
4552     }
4553     if (compressor) {
4554       strcpy ((gchar *) mp4v->compressor + 1, compressor);
4555       mp4v->compressor[0] = strlen (compressor);
4556     }
4557   }
4558
4559   gst_object_unref (qtmux);
4560   return TRUE;
4561
4562   /* ERRORS */
4563 refuse_caps:
4564   {
4565     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4566         GST_PAD_NAME (pad), caps);
4567     gst_object_unref (qtmux);
4568     return FALSE;
4569   }
4570 refuse_renegotiation:
4571   {
4572     GST_WARNING_OBJECT (qtmux,
4573         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4574         caps);
4575     gst_object_unref (qtmux);
4576     return FALSE;
4577   }
4578 }
4579
4580 static gboolean
4581 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4582 {
4583   GstPad *pad = qtpad->collect.pad;
4584   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4585   GstStructure *structure;
4586   SubtitleSampleEntry entry = { 0, };
4587
4588   /* does not go well to renegotiate stream mid-way, unless
4589    * the old caps are a subset of the new one (this means upstream
4590    * added more info to the caps, as both should be 'fixed' caps) */
4591   if (qtpad->fourcc) {
4592     GstCaps *current_caps;
4593
4594     current_caps = gst_pad_get_current_caps (pad);
4595     g_assert (caps != NULL);
4596
4597     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4598       gst_caps_unref (current_caps);
4599       goto refuse_renegotiation;
4600     }
4601     GST_DEBUG_OBJECT (qtmux,
4602         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4603         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4604     gst_caps_unref (current_caps);
4605   }
4606
4607   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4608       GST_DEBUG_PAD_NAME (pad), caps);
4609
4610   /* subtitles default */
4611   subtitle_sample_entry_init (&entry);
4612   qtpad->is_out_of_order = FALSE;
4613   qtpad->sync = FALSE;
4614   qtpad->sparse = TRUE;
4615   qtpad->prepare_buf_func = NULL;
4616
4617   structure = gst_caps_get_structure (caps, 0);
4618
4619   if (gst_structure_has_name (structure, "text/x-raw")) {
4620     const gchar *format = gst_structure_get_string (structure, "format");
4621     if (format && strcmp (format, "utf8") == 0) {
4622       entry.fourcc = FOURCC_tx3g;
4623       qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
4624       qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
4625     }
4626   }
4627
4628   if (!entry.fourcc)
4629     goto refuse_caps;
4630
4631   qtpad->fourcc = entry.fourcc;
4632   qtpad->trak_ste =
4633       (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
4634       qtmux->context, &entry);
4635
4636   gst_object_unref (qtmux);
4637   return TRUE;
4638
4639   /* ERRORS */
4640 refuse_caps:
4641   {
4642     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4643         GST_PAD_NAME (pad), caps);
4644     gst_object_unref (qtmux);
4645     return FALSE;
4646   }
4647 refuse_renegotiation:
4648   {
4649     GST_WARNING_OBJECT (qtmux,
4650         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4651         caps);
4652     gst_object_unref (qtmux);
4653     return FALSE;
4654   }
4655 }
4656
4657 static gboolean
4658 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
4659     GstEvent * event, gpointer user_data)
4660 {
4661   GstQTMux *qtmux;
4662   guint32 avg_bitrate = 0, max_bitrate = 0;
4663   GstPad *pad = data->pad;
4664   gboolean ret = TRUE;
4665
4666   qtmux = GST_QT_MUX_CAST (user_data);
4667   switch (GST_EVENT_TYPE (event)) {
4668     case GST_EVENT_CAPS:
4669     {
4670       GstCaps *caps;
4671       GstQTPad *collect_pad;
4672
4673       gst_event_parse_caps (event, &caps);
4674
4675       /* find stream data */
4676       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4677       g_assert (collect_pad);
4678       g_assert (collect_pad->set_caps);
4679
4680       ret = collect_pad->set_caps (collect_pad, caps);
4681       gst_event_unref (event);
4682       event = NULL;
4683       break;
4684     }
4685     case GST_EVENT_TAG:{
4686       GstTagList *list;
4687       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
4688       GstTagMergeMode mode;
4689       gchar *code;
4690       GstQTPad *collect_pad;
4691
4692       GST_OBJECT_LOCK (qtmux);
4693       mode = gst_tag_setter_get_tag_merge_mode (setter);
4694       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4695
4696       gst_event_parse_tag (event, &list);
4697       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
4698           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
4699
4700       if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
4701         gst_tag_setter_merge_tags (setter, list, mode);
4702         qtmux->tags_changed = TRUE;
4703       } else {
4704         if (!collect_pad->tags)
4705           collect_pad->tags = gst_tag_list_new_empty ();
4706         gst_tag_list_insert (collect_pad->tags, list, mode);
4707         collect_pad->tags_changed = TRUE;
4708       }
4709       GST_OBJECT_UNLOCK (qtmux);
4710
4711       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
4712           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
4713         GstQTPad *qtpad = gst_pad_get_element_private (pad);
4714         g_assert (qtpad);
4715
4716         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
4717           qtpad->avg_bitrate = avg_bitrate;
4718         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
4719           qtpad->max_bitrate = max_bitrate;
4720       }
4721
4722       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
4723         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
4724         if (iso_code) {
4725           GstQTPad *qtpad = gst_pad_get_element_private (pad);
4726           g_assert (qtpad);
4727           if (qtpad->trak) {
4728             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
4729             qtpad->trak->mdia.mdhd.language_code =
4730                 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
4731                 (iso_code[2] - 0x60);
4732           }
4733         }
4734         g_free (code);
4735       }
4736
4737       gst_event_unref (event);
4738       event = NULL;
4739       ret = TRUE;
4740       break;
4741     }
4742     default:
4743       break;
4744   }
4745
4746   if (event != NULL)
4747     return gst_collect_pads_event_default (pads, data, event, FALSE);
4748
4749   return ret;
4750 }
4751
4752 static void
4753 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
4754 {
4755   GstQTMux *mux = GST_QT_MUX_CAST (element);
4756   GSList *walk;
4757
4758   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
4759
4760   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
4761     GstQTPad *qtpad = (GstQTPad *) walk->data;
4762     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
4763     if (qtpad->collect.pad == pad) {
4764       /* this is it, remove */
4765       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
4766       gst_element_remove_pad (element, pad);
4767       break;
4768     }
4769   }
4770
4771   if (mux->current_pad && mux->current_pad->collect.pad == pad) {
4772     mux->current_pad = NULL;
4773     mux->current_chunk_size = 0;
4774     mux->current_chunk_duration = 0;
4775   }
4776
4777   gst_collect_pads_remove_pad (mux->collect, pad);
4778
4779   if (mux->sinkpads == NULL) {
4780     /* No more outstanding request pads, reset our counters */
4781     mux->video_pads = 0;
4782     mux->audio_pads = 0;
4783     mux->subtitle_pads = 0;
4784   }
4785 }
4786
4787 static GstPad *
4788 gst_qt_mux_request_new_pad (GstElement * element,
4789     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
4790 {
4791   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
4792   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4793   GstQTPad *collect_pad;
4794   GstPad *newpad;
4795   GstQTPadSetCapsFunc setcaps_func;
4796   gchar *name;
4797   gint pad_id;
4798   gboolean lock = TRUE;
4799
4800   if (templ->direction != GST_PAD_SINK)
4801     goto wrong_direction;
4802
4803   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
4804     goto too_late;
4805
4806   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
4807     setcaps_func = gst_qt_mux_audio_sink_set_caps;
4808     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
4809       name = g_strdup (req_name);
4810     } else {
4811       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
4812     }
4813   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
4814     setcaps_func = gst_qt_mux_video_sink_set_caps;
4815     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
4816       name = g_strdup (req_name);
4817     } else {
4818       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
4819     }
4820   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
4821     setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
4822     if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
4823       name = g_strdup (req_name);
4824     } else {
4825       name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
4826     }
4827     lock = FALSE;
4828   } else
4829     goto wrong_template;
4830
4831   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
4832
4833   /* create pad and add to collections */
4834   newpad = gst_pad_new_from_template (templ, name);
4835   g_free (name);
4836   collect_pad = (GstQTPad *)
4837       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
4838       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
4839   /* set up pad */
4840   gst_qt_mux_pad_reset (collect_pad);
4841   collect_pad->trak = atom_trak_new (qtmux->context);
4842   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
4843
4844   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
4845
4846   /* set up pad functions */
4847   collect_pad->set_caps = setcaps_func;
4848
4849   gst_pad_set_active (newpad, TRUE);
4850   gst_element_add_pad (element, newpad);
4851
4852   return newpad;
4853
4854   /* ERRORS */
4855 wrong_direction:
4856   {
4857     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
4858     return NULL;
4859   }
4860 too_late:
4861   {
4862     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
4863     return NULL;
4864   }
4865 wrong_template:
4866   {
4867     GST_WARNING_OBJECT (qtmux, "This is not our template!");
4868     return NULL;
4869   }
4870 }
4871
4872 static void
4873 gst_qt_mux_get_property (GObject * object,
4874     guint prop_id, GValue * value, GParamSpec * pspec)
4875 {
4876   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4877
4878   GST_OBJECT_LOCK (qtmux);
4879   switch (prop_id) {
4880     case PROP_MOVIE_TIMESCALE:
4881       g_value_set_uint (value, qtmux->timescale);
4882       break;
4883     case PROP_TRAK_TIMESCALE:
4884       g_value_set_uint (value, qtmux->trak_timescale);
4885       break;
4886     case PROP_DO_CTTS:
4887       g_value_set_boolean (value, qtmux->guess_pts);
4888       break;
4889 #ifndef GST_REMOVE_DEPRECATED
4890     case PROP_DTS_METHOD:
4891       g_value_set_enum (value, qtmux->dts_method);
4892       break;
4893 #endif
4894     case PROP_FAST_START:
4895       g_value_set_boolean (value, qtmux->fast_start);
4896       break;
4897     case PROP_FAST_START_TEMP_FILE:
4898       g_value_set_string (value, qtmux->fast_start_file_path);
4899       break;
4900     case PROP_MOOV_RECOV_FILE:
4901       g_value_set_string (value, qtmux->moov_recov_file_path);
4902       break;
4903     case PROP_FRAGMENT_DURATION:
4904       g_value_set_uint (value, qtmux->fragment_duration);
4905       break;
4906     case PROP_STREAMABLE:
4907       g_value_set_boolean (value, qtmux->streamable);
4908       break;
4909     case PROP_RESERVED_MAX_DURATION:
4910       g_value_set_uint64 (value, qtmux->reserved_max_duration);
4911       break;
4912     case PROP_RESERVED_DURATION_REMAINING:
4913       if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
4914         g_value_set_uint64 (value, qtmux->reserved_max_duration);
4915       else {
4916         GstClockTime remaining = qtmux->reserved_duration_remaining;
4917
4918         /* Report the remaining space as the calculated remaining, minus
4919          * however much we've muxed since the last update */
4920         if (remaining > qtmux->muxed_since_last_update)
4921           remaining -= qtmux->muxed_since_last_update;
4922         else
4923           remaining = 0;
4924         GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
4925             G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
4926             remaining, qtmux->reserved_duration_remaining,
4927             qtmux->muxed_since_last_update);
4928         g_value_set_uint64 (value, remaining);
4929       }
4930       break;
4931     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4932       g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
4933       break;
4934     case PROP_RESERVED_BYTES_PER_SEC:
4935       g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
4936       break;
4937     case PROP_INTERLEAVE_BYTES:
4938       g_value_set_uint64 (value, qtmux->interleave_bytes);
4939       break;
4940     case PROP_INTERLEAVE_TIME:
4941       g_value_set_uint64 (value, qtmux->interleave_time);
4942       break;
4943     default:
4944       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4945       break;
4946   }
4947   GST_OBJECT_UNLOCK (qtmux);
4948 }
4949
4950 static void
4951 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
4952 {
4953   gchar *tmp;
4954
4955   g_free (qtmux->fast_start_file_path);
4956   qtmux->fast_start_file_path = NULL;
4957
4958   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
4959   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
4960   g_free (tmp);
4961 }
4962
4963 static void
4964 gst_qt_mux_set_property (GObject * object,
4965     guint prop_id, const GValue * value, GParamSpec * pspec)
4966 {
4967   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4968
4969   GST_OBJECT_LOCK (qtmux);
4970   switch (prop_id) {
4971     case PROP_MOVIE_TIMESCALE:
4972       qtmux->timescale = g_value_get_uint (value);
4973       break;
4974     case PROP_TRAK_TIMESCALE:
4975       qtmux->trak_timescale = g_value_get_uint (value);
4976       break;
4977     case PROP_DO_CTTS:
4978       qtmux->guess_pts = g_value_get_boolean (value);
4979       break;
4980 #ifndef GST_REMOVE_DEPRECATED
4981     case PROP_DTS_METHOD:
4982       qtmux->dts_method = g_value_get_enum (value);
4983       break;
4984 #endif
4985     case PROP_FAST_START:
4986       qtmux->fast_start = g_value_get_boolean (value);
4987       break;
4988     case PROP_FAST_START_TEMP_FILE:
4989       g_free (qtmux->fast_start_file_path);
4990       qtmux->fast_start_file_path = g_value_dup_string (value);
4991       /* NULL means to generate a random one */
4992       if (!qtmux->fast_start_file_path) {
4993         gst_qt_mux_generate_fast_start_file_path (qtmux);
4994       }
4995       break;
4996     case PROP_MOOV_RECOV_FILE:
4997       g_free (qtmux->moov_recov_file_path);
4998       qtmux->moov_recov_file_path = g_value_dup_string (value);
4999       break;
5000     case PROP_FRAGMENT_DURATION:
5001       qtmux->fragment_duration = g_value_get_uint (value);
5002       break;
5003     case PROP_STREAMABLE:{
5004       GstQTMuxClass *qtmux_klass =
5005           (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5006       if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
5007         qtmux->streamable = g_value_get_boolean (value);
5008       }
5009       break;
5010     }
5011     case PROP_RESERVED_MAX_DURATION:
5012       qtmux->reserved_max_duration = g_value_get_uint64 (value);
5013       break;
5014     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
5015       qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
5016       break;
5017     case PROP_RESERVED_BYTES_PER_SEC:
5018       qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
5019       break;
5020     case PROP_INTERLEAVE_BYTES:
5021       qtmux->interleave_bytes = g_value_get_uint64 (value);
5022       qtmux->interleave_bytes_set = TRUE;
5023       break;
5024     case PROP_INTERLEAVE_TIME:
5025       qtmux->interleave_time = g_value_get_uint64 (value);
5026       qtmux->interleave_time_set = TRUE;
5027       break;
5028     default:
5029       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5030       break;
5031   }
5032   GST_OBJECT_UNLOCK (qtmux);
5033 }
5034
5035 static GstStateChangeReturn
5036 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
5037 {
5038   GstStateChangeReturn ret;
5039   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
5040
5041   switch (transition) {
5042     case GST_STATE_CHANGE_NULL_TO_READY:
5043       break;
5044     case GST_STATE_CHANGE_READY_TO_PAUSED:
5045       gst_collect_pads_start (qtmux->collect);
5046       qtmux->state = GST_QT_MUX_STATE_STARTED;
5047       break;
5048     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5049       break;
5050     case GST_STATE_CHANGE_PAUSED_TO_READY:
5051       gst_collect_pads_stop (qtmux->collect);
5052       break;
5053     default:
5054       break;
5055   }
5056
5057   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5058
5059   switch (transition) {
5060     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
5061       break;
5062     case GST_STATE_CHANGE_PAUSED_TO_READY:
5063       gst_qt_mux_reset (qtmux, TRUE);
5064       break;
5065     case GST_STATE_CHANGE_READY_TO_NULL:
5066       break;
5067     default:
5068       break;
5069   }
5070
5071   return ret;
5072 }
5073
5074 gboolean
5075 gst_qt_mux_register (GstPlugin * plugin)
5076 {
5077   GTypeInfo typeinfo = {
5078     sizeof (GstQTMuxClass),
5079     (GBaseInitFunc) gst_qt_mux_base_init,
5080     NULL,
5081     (GClassInitFunc) gst_qt_mux_class_init,
5082     NULL,
5083     NULL,
5084     sizeof (GstQTMux),
5085     0,
5086     (GInstanceInitFunc) gst_qt_mux_init,
5087   };
5088   static const GInterfaceInfo tag_setter_info = {
5089     NULL, NULL, NULL
5090   };
5091   static const GInterfaceInfo tag_xmp_writer_info = {
5092     NULL, NULL, NULL
5093   };
5094   static const GInterfaceInfo preset_info = {
5095     NULL, NULL, NULL
5096   };
5097   GType type;
5098   GstQTMuxFormat format;
5099   GstQTMuxClassParams *params;
5100   guint i = 0;
5101
5102   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
5103
5104   GST_LOG ("Registering muxers");
5105
5106   while (TRUE) {
5107     GstQTMuxFormatProp *prop;
5108     GstCaps *subtitle_caps;
5109
5110     prop = &gst_qt_mux_format_list[i];
5111     format = prop->format;
5112     if (format == GST_QT_MUX_FORMAT_NONE)
5113       break;
5114
5115     /* create a cache for these properties */
5116     params = g_new0 (GstQTMuxClassParams, 1);
5117     params->prop = prop;
5118     params->src_caps = gst_static_caps_get (&prop->src_caps);
5119     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
5120     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
5121     subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
5122     if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
5123       params->subtitle_sink_caps = subtitle_caps;
5124     } else {
5125       gst_caps_unref (subtitle_caps);
5126     }
5127
5128     /* create the type now */
5129     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
5130         0);
5131     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
5132     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
5133     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
5134         &tag_xmp_writer_info);
5135     g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
5136
5137     if (!gst_element_register (plugin, prop->name, prop->rank, type))
5138       return FALSE;
5139
5140     i++;
5141   }
5142
5143   GST_LOG ("Finished registering muxers");
5144
5145   /* FIXME: ideally classification tag should be added and
5146      registered in gstreamer core gsttaglist
5147    */
5148
5149   GST_LOG ("Registering tags");
5150
5151   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
5152       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
5153       gst_tag_merge_use_first);
5154
5155   GST_LOG ("Finished registering tags");
5156
5157   return TRUE;
5158 }