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