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