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