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