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