qtmux: correctly track chunk size of subtitle stream
[platform/upstream/gstreamer.git] / gst / isomp4 / gstqtmux.c
1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4  * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5  * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6  * Contact: Stefan Kost <stefan.kost@nokia.com>
7
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /*
24  * Unless otherwise indicated, Source Code is licensed under MIT license.
25  * See further explanation attached in License Statement (distributed in the file
26  * LICENSE).
27  *
28  * Permission is hereby granted, free of charge, to any person obtaining a copy of
29  * this software and associated documentation files (the "Software"), to deal in
30  * the Software without restriction, including without limitation the rights to
31  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32  * of the Software, and to permit persons to whom the Software is furnished to do
33  * so, subject to the following conditions:
34  *
35  * The above copyright notice and this permission notice shall be included in all
36  * copies or substantial portions of the Software.
37  *
38  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44  * SOFTWARE.
45  */
46
47
48 /**
49  * SECTION:element-qtmux
50  * @short_description: Muxer for quicktime(.mov) files
51  *
52  * This element merges streams (audio and video) into QuickTime(.mov) files.
53  *
54  * The following background intends to explain why various similar muxers
55  * are present in this plugin.
56  *
57  * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58  * QuickTime file format specification</ulink> served as basis for the MP4 file
59  * format specification (mp4mux), and as such the QuickTime file structure is
60  * nearly identical to the so-called ISO Base Media file format defined in
61  * ISO 14496-12 (except for some media specific parts).
62  * In turn, the latter ISO Base Media format was further specialized as a
63  * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64  * and in various 3GPP(2) specs (gppmux).
65  * The fragmented file features defined (only) in ISO Base Media are used by
66  * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
67  *
68  * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale) allow
69  * adjusting some technical parameters, which might be useful in (rare) cases to
70  * resolve compatibility issues in some situations.
71  *
72  * Some other properties influence the result more fundamentally.
73  * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
74  * file, somewhat contrary to this usually being called "the header".
75  * However, a #GstQTMux:faststart file will (with some effort) arrange this to
76  * be located near start of the file, which then allows it e.g. to be played
77  * while downloading. Alternatively, rather than having one chunk of metadata at
78  * start (or end), there can be some metadata at start and most of the other
79  * data can be spread out into fragments of #GstQTMux:fragment-duration.
80  * If such fragmented layout is intended for streaming purposes, then
81  * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
82  * file).
83  *
84  * When the maximum duration to be recorded can be known in advance, #GstQTMux
85  * also supports a 'Robust Muxing' mode. In robust muxing mode,  space for the
86  * headers are reserved at the start of muxing, and rewritten at a configurable
87  * interval, so that the output file is always playable, even if the recording
88  * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
89  * output, such as filesink, because it needs to rewrite the start of the file.
90  *
91  * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
92  * and #GstQTMux::reserved-max-duration property. Also present is the
93  * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
94  * for some reason the default is not large enough and the initial reserved
95  * space for headers is too small. Applications can monitor the
96  * #GstQTMux::reserved-duration-remaining property to see how close to full
97  * the reserved space is becoming.
98  *
99  * <refsect2>
100  * <title>Example pipelines</title>
101  * |[
102  * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
103  * ]|
104  * Records a video stream captured from a v4l2 device and muxes it into a qt file.
105  * </refsect2>
106  */
107
108 /*
109  * Based on avimux
110  */
111
112 #ifdef HAVE_CONFIG_H
113 #include "config.h"
114 #endif
115
116 #include <glib/gstdio.h>
117
118 #include <gst/gst.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/base/gstbytereader.h>
121 #include <gst/base/gstbitreader.h>
122 #include <gst/audio/audio.h>
123 #include <gst/video/video.h>
124 #include <gst/tag/tag.h>
125 #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 #ifndef ABSDIFF
150 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
151 #endif
152
153 /* Hacker notes.
154  *
155  * The basic building blocks of MP4 files are:
156  *  - an 'ftyp' box at the very start
157  *  - an 'mdat' box which contains the raw audio/video/subtitle data;
158  *    this is just a bunch of bytes, completely unframed and possibly
159  *    unordered with no additional meta-information
160  *  - a 'moov' box that contains information about the different streams
161  *    and what they contain, as well as sample tables for each stream
162  *    that tell the demuxer where in the mdat box each buffer/sample is
163  *    and what its duration/timestamp etc. is, and whether it's a
164  *    keyframe etc.
165  * Additionally, fragmented MP4 works by writing chunks of data in
166  * pairs of 'moof' and 'mdat' boxes:
167  *  - 'moof' boxes, header preceding each mdat fragment describing the
168  *    contents, like a moov but only for that fragment.
169  *  - a 'mfra' box for Fragmented MP4, which is written at the end and
170  *    contains a summary of all fragments and seek tables.
171  *
172  * Currently mp4mux can work in 4 different modes / generate 4 types
173  * of output files/streams:
174  *
175  * - Normal mp4: mp4mux will write a little ftyp identifier at the
176  *   beginning, then start an mdat box into which it will write all the
177  *   sample data. At EOS it will then write the moov header with track
178  *   headers and sample tables at the end of the file, and rewrite the
179  *   start of the file to fix up the mdat box size at the beginning.
180  *   It has to wait for EOS to write the moov (which includes the
181  *   sample tables) because it doesn't know how much space those
182  *   tables will be. The output downstream must be seekable to rewrite
183  *   the mdat box at EOS.
184  *
185  * - Fragmented mp4: moov header with track headers at start
186  *   but no sample table, followed by N fragments, each containing
187  *   track headers with sample tables followed by some data. Downstream
188  *   does not need to be seekable if the 'streamable' flag is TRUE,
189  *   as the final mfra and total duration will be omitted.
190  *
191  * - Fast-start mp4: the goal here is to create a file where the moov
192  *   headers are at the beginning; what mp4mux will do is write all
193  *   sample data into a temp file and build moov header plus sample
194  *   tables in memory and then when EOS comes, it will push out the
195  *   moov header plus sample tables at the beginning, followed by the
196  *   mdat sample data at the end which is read in from the temp file
197  *   Files created in this mode are better for streaming over the
198  *   network, since the client doesn't have to seek to the end of the
199  *   file to get the headers, but it requires copying all sample data
200  *   out of the temp file at EOS, which can be expensive. Downstream does
201  *   not need to be seekable, because of the use of the temp file.
202  *
203  * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
204  *   and reserved-moov-update-period properties to reserve free space
205  *   at the start of the file and periodically write the MOOV atom out
206  *   to it. That means that killing the muxing at any point still
207  *   results in a playable file, at the cost of wasting some amount of
208  *   free space at the start of file. The approximate recording duration
209  *   has to be known in advance to estimate how much free space to reserve
210  *   for the moov, and the downstream must be seekable.
211  *   If the moov header grows larger than the reserved space, an error
212  *   is generated - so it's better to over-estimate the amount of space
213  *   to reserve. To ensure the file is playable at any point, the moov
214  *   is updated using a 'ping-pong' strategy, so the output is never in
215  *   an invalid state.
216  */
217
218 #ifndef GST_REMOVE_DEPRECATED
219 enum
220 {
221   DTS_METHOD_DD,
222   DTS_METHOD_REORDER,
223   DTS_METHOD_ASC
224 };
225
226 static GType
227 gst_qt_mux_dts_method_get_type (void)
228 {
229   static GType gst_qt_mux_dts_method = 0;
230
231   if (!gst_qt_mux_dts_method) {
232     static const GEnumValue dts_methods[] = {
233       {DTS_METHOD_DD, "delta/duration", "dd"},
234       {DTS_METHOD_REORDER, "reorder", "reorder"},
235       {DTS_METHOD_ASC, "ascending", "asc"},
236       {0, NULL, NULL},
237     };
238
239     gst_qt_mux_dts_method =
240         g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
241   }
242
243   return gst_qt_mux_dts_method;
244 }
245
246 #define GST_TYPE_QT_MUX_DTS_METHOD \
247   (gst_qt_mux_dts_method_get_type ())
248 #endif
249
250 /* QTMux signals and args */
251 enum
252 {
253   /* FILL ME */
254   LAST_SIGNAL
255 };
256
257 enum
258 {
259   PROP_0,
260   PROP_MOVIE_TIMESCALE,
261   PROP_TRAK_TIMESCALE,
262   PROP_FAST_START,
263   PROP_FAST_START_TEMP_FILE,
264   PROP_MOOV_RECOV_FILE,
265   PROP_FRAGMENT_DURATION,
266   PROP_STREAMABLE,
267   PROP_RESERVED_MAX_DURATION,
268   PROP_RESERVED_DURATION_REMAINING,
269   PROP_RESERVED_MOOV_UPDATE_PERIOD,
270   PROP_RESERVED_BYTES_PER_SEC,
271   PROP_RESERVED_PREFILL,
272 #ifndef GST_REMOVE_DEPRECATED
273   PROP_DTS_METHOD,
274 #endif
275   PROP_DO_CTTS,
276   PROP_INTERLEAVE_BYTES,
277   PROP_INTERLEAVE_TIME,
278   PROP_MAX_RAW_AUDIO_DRIFT,
279 };
280
281 /* some spare for header size as well */
282 #define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)
283
284 #define DEFAULT_MOVIE_TIMESCALE         0
285 #define DEFAULT_TRAK_TIMESCALE          0
286 #define DEFAULT_DO_CTTS                 TRUE
287 #define DEFAULT_FAST_START              FALSE
288 #define DEFAULT_FAST_START_TEMP_FILE    NULL
289 #define DEFAULT_MOOV_RECOV_FILE         NULL
290 #define DEFAULT_FRAGMENT_DURATION       0
291 #define DEFAULT_STREAMABLE              TRUE
292 #ifndef GST_REMOVE_DEPRECATED
293 #define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
294 #endif
295 #define DEFAULT_RESERVED_MAX_DURATION   GST_CLOCK_TIME_NONE
296 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD   GST_CLOCK_TIME_NONE
297 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
298 #define DEFAULT_RESERVED_PREFILL FALSE
299 #define DEFAULT_INTERLEAVE_BYTES 0
300 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
301 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
302
303 static void gst_qt_mux_finalize (GObject * object);
304
305 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
306     GstStateChange transition);
307
308 /* property functions */
309 static void gst_qt_mux_set_property (GObject * object,
310     guint prop_id, const GValue * value, GParamSpec * pspec);
311 static void gst_qt_mux_get_property (GObject * object,
312     guint prop_id, GValue * value, GParamSpec * pspec);
313
314 /* pad functions */
315 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
316     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
317 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
318
319 /* event */
320 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
321     GstCollectData * data, GstEvent * event, gpointer user_data);
322
323 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
324     gpointer user_data);
325 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
326     GstBuffer * buf);
327
328 static GstFlowReturn
329 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
330
331 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
332 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
333
334 static GstElementClass *parent_class = NULL;
335
336 static void
337 gst_qt_mux_base_init (gpointer g_class)
338 {
339   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
340   GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
341   GstQTMuxClassParams *params;
342   GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
343   GstPadTemplate *srctempl;
344   gchar *longname, *description;
345
346   params =
347       (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
348       GST_QT_MUX_PARAMS_QDATA);
349   g_assert (params != NULL);
350
351   /* construct the element details struct */
352   longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
353   description = g_strdup_printf ("Multiplex audio and video into a %s file",
354       params->prop->long_name);
355   gst_element_class_set_static_metadata (element_class, longname,
356       "Codec/Muxer", description,
357       "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
358   g_free (longname);
359   g_free (description);
360
361   /* pad templates */
362   srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
363       GST_PAD_ALWAYS, params->src_caps);
364   gst_element_class_add_pad_template (element_class, srctempl);
365
366   if (params->audio_sink_caps) {
367     audiosinktempl = gst_pad_template_new ("audio_%u",
368         GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
369     gst_element_class_add_pad_template (element_class, audiosinktempl);
370   }
371
372   if (params->video_sink_caps) {
373     videosinktempl = gst_pad_template_new ("video_%u",
374         GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
375     gst_element_class_add_pad_template (element_class, videosinktempl);
376   }
377
378   if (params->subtitle_sink_caps) {
379     subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
380         GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
381     gst_element_class_add_pad_template (element_class, subtitlesinktempl);
382   }
383
384   klass->format = params->prop->format;
385 }
386
387 static void
388 gst_qt_mux_class_init (GstQTMuxClass * klass)
389 {
390   GObjectClass *gobject_class;
391   GstElementClass *gstelement_class;
392   GParamFlags streamable_flags;
393   const gchar *streamable_desc;
394   gboolean streamable;
395 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
396   "be streamed and hence no indexes written or duration written."
397
398   gobject_class = (GObjectClass *) klass;
399   gstelement_class = (GstElementClass *) klass;
400
401   parent_class = g_type_class_peek_parent (klass);
402
403   gobject_class->finalize = gst_qt_mux_finalize;
404   gobject_class->get_property = gst_qt_mux_get_property;
405   gobject_class->set_property = gst_qt_mux_set_property;
406
407   streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
408   if (klass->format == GST_QT_MUX_FORMAT_ISML) {
409     streamable_desc = STREAMABLE_DESC;
410     streamable = DEFAULT_STREAMABLE;
411   } else {
412     streamable_desc =
413         STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
414     streamable_flags |= G_PARAM_DEPRECATED;
415     streamable = FALSE;
416   }
417
418   g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
419       g_param_spec_uint ("movie-timescale", "Movie timescale",
420           "Timescale to use in the movie (units per second, 0 == default)",
421           0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
422           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
423   g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
424       g_param_spec_uint ("trak-timescale", "Track timescale",
425           "Timescale to use for the tracks (units per second, 0 is automatic)",
426           0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
427           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
428   g_object_class_install_property (gobject_class, PROP_DO_CTTS,
429       g_param_spec_boolean ("presentation-time",
430           "Include presentation-time info",
431           "Calculate and include presentation/composition time "
432           "(in addition to decoding time)", DEFAULT_DO_CTTS,
433           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
434 #ifndef GST_REMOVE_DEPRECATED
435   g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
436       g_param_spec_enum ("dts-method", "dts-method",
437           "Method to determine DTS time (DEPRECATED)",
438           GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
439           G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
440           G_PARAM_STATIC_STRINGS));
441 #endif
442   g_object_class_install_property (gobject_class, PROP_FAST_START,
443       g_param_spec_boolean ("faststart", "Format file to faststart",
444           "If the file should be formatted for faststart (headers first)",
445           DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446   g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
447       g_param_spec_string ("faststart-file", "File to use for storing buffers",
448           "File that will be used temporarily to store data from the stream "
449           "when creating a faststart file. If null a filepath will be "
450           "created automatically", DEFAULT_FAST_START_TEMP_FILE,
451           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
452   g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
453       g_param_spec_string ("moov-recovery-file",
454           "File to store data for posterior moov atom recovery",
455           "File to be used to store "
456           "data for moov atom making movie file recovery possible in case "
457           "of a crash during muxing. Null for disabled. (Experimental)",
458           DEFAULT_MOOV_RECOV_FILE,
459           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
460   g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
461       g_param_spec_uint ("fragment-duration", "Fragment duration",
462           "Fragment durations in ms (produce a fragmented file if > 0)",
463           0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
464           2000 : DEFAULT_FRAGMENT_DURATION,
465           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
466   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
467       g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
468           streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
469   g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
470       g_param_spec_uint64 ("reserved-max-duration",
471           "Reserved maximum file duration (ns)",
472           "When set to a value > 0, reserves space for index tables at the "
473           "beginning of the file.",
474           0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
475           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
476   g_object_class_install_property (gobject_class,
477       PROP_RESERVED_DURATION_REMAINING,
478       g_param_spec_uint64 ("reserved-duration-remaining",
479           "Report the approximate amount of remaining recording space (ns)",
480           "Reports the approximate amount of remaining moov header space "
481           "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
482           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
483   g_object_class_install_property (gobject_class,
484       PROP_RESERVED_MOOV_UPDATE_PERIOD,
485       g_param_spec_uint64 ("reserved-moov-update-period",
486           "Interval at which to update index tables (ns)",
487           "When used with reserved-max-duration, periodically updates the "
488           "index tables with information muxed so far.", 0, G_MAXUINT64,
489           DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
490           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491   g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
492       g_param_spec_uint ("reserved-bytes-per-sec",
493           "Reserved MOOV bytes per second, per track",
494           "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
495           0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
496           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
497   g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
498       g_param_spec_boolean ("reserved-prefill",
499           "Reserved Prefill Samples Table",
500           "Prefill samples table of reserved duration",
501           DEFAULT_RESERVED_PREFILL,
502           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
503   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
504       g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
505           "Interleave between streams in bytes",
506           0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
507           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
508   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
509       g_param_spec_uint64 ("interleave-time", "Interleave (time)",
510           "Interleave between streams in nanoseconds",
511           0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
512           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
513   g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
514       g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
515           "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
516           0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
517           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
518
519   gstelement_class->request_new_pad =
520       GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
521   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
522   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
523 }
524
525 static void
526 gst_qt_mux_pad_reset (GstQTPad * qtpad)
527 {
528   qtpad->fourcc = 0;
529   qtpad->is_out_of_order = FALSE;
530   qtpad->sample_size = 0;
531   qtpad->sync = FALSE;
532   qtpad->last_dts = 0;
533   qtpad->sample_offset = 0;
534   qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
535   qtpad->first_ts = GST_CLOCK_TIME_NONE;
536   qtpad->first_dts = GST_CLOCK_TIME_NONE;
537   qtpad->prepare_buf_func = NULL;
538   qtpad->create_empty_buffer = NULL;
539   qtpad->avg_bitrate = 0;
540   qtpad->max_bitrate = 0;
541   qtpad->total_duration = 0;
542   qtpad->total_bytes = 0;
543   qtpad->sparse = FALSE;
544
545   gst_buffer_replace (&qtpad->last_buf, NULL);
546
547   if (qtpad->tags) {
548     gst_tag_list_unref (qtpad->tags);
549     qtpad->tags = NULL;
550   }
551
552   /* reference owned elsewhere */
553   qtpad->trak = NULL;
554   qtpad->tc_trak = NULL;
555
556   if (qtpad->traf) {
557     atom_traf_free (qtpad->traf);
558     qtpad->traf = NULL;
559   }
560   atom_array_clear (&qtpad->fragment_buffers);
561   if (qtpad->samples)
562     g_array_unref (qtpad->samples);
563   qtpad->samples = NULL;
564
565   /* reference owned elsewhere */
566   qtpad->tfra = NULL;
567
568   qtpad->first_pts = GST_CLOCK_TIME_NONE;
569   qtpad->tc_pos = -1;
570   if (qtpad->first_tc)
571     gst_video_time_code_free (qtpad->first_tc);
572   qtpad->first_tc = NULL;
573
574   if (qtpad->raw_audio_adapter)
575     gst_object_unref (qtpad->raw_audio_adapter);
576   qtpad->raw_audio_adapter = NULL;
577 }
578
579 /*
580  * Takes GstQTMux back to its initial state
581  */
582 static void
583 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
584 {
585   GSList *walk;
586
587   qtmux->state = GST_QT_MUX_STATE_NONE;
588   qtmux->header_size = 0;
589   qtmux->mdat_size = 0;
590   qtmux->moov_pos = 0;
591   qtmux->mdat_pos = 0;
592   qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
593   qtmux->fragment_sequence = 0;
594
595   if (qtmux->ftyp) {
596     atom_ftyp_free (qtmux->ftyp);
597     qtmux->ftyp = NULL;
598   }
599   if (qtmux->moov) {
600     atom_moov_free (qtmux->moov);
601     qtmux->moov = NULL;
602   }
603   if (qtmux->mfra) {
604     atom_mfra_free (qtmux->mfra);
605     qtmux->mfra = NULL;
606   }
607   if (qtmux->fast_start_file) {
608     fclose (qtmux->fast_start_file);
609     g_remove (qtmux->fast_start_file_path);
610     qtmux->fast_start_file = NULL;
611   }
612   if (qtmux->moov_recov_file) {
613     fclose (qtmux->moov_recov_file);
614     qtmux->moov_recov_file = NULL;
615   }
616   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
617     AtomInfo *ainfo = (AtomInfo *) walk->data;
618     ainfo->free_func (ainfo->atom);
619     g_free (ainfo);
620   }
621   g_slist_free (qtmux->extra_atoms);
622   qtmux->extra_atoms = NULL;
623
624   GST_OBJECT_LOCK (qtmux);
625   gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
626   GST_OBJECT_UNLOCK (qtmux);
627
628   /* reset pad data */
629   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
630     GstQTPad *qtpad = (GstQTPad *) walk->data;
631     gst_qt_mux_pad_reset (qtpad);
632
633     /* hm, moov_free above yanked the traks away from us,
634      * so do not free, but do clear */
635     qtpad->trak = NULL;
636   }
637
638   if (alloc) {
639     qtmux->moov = atom_moov_new (qtmux->context);
640     /* ensure all is as nice and fresh as request_new_pad would provide it */
641     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
642       GstQTPad *qtpad = (GstQTPad *) walk->data;
643
644       qtpad->trak = atom_trak_new (qtmux->context);
645       atom_moov_add_trak (qtmux->moov, qtpad->trak);
646     }
647   }
648
649   qtmux->current_pad = NULL;
650   qtmux->current_chunk_size = 0;
651   qtmux->current_chunk_duration = 0;
652   qtmux->current_chunk_offset = -1;
653
654   qtmux->reserved_moov_size = 0;
655   qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
656   qtmux->muxed_since_last_update = 0;
657   qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
658 }
659
660 static void
661 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
662 {
663   GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
664   GstPadTemplate *templ;
665
666   templ = gst_element_class_get_pad_template (klass, "src");
667   qtmux->srcpad = gst_pad_new_from_template (templ, "src");
668   gst_pad_use_fixed_caps (qtmux->srcpad);
669   gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
670
671   qtmux->sinkpads = NULL;
672   qtmux->collect = gst_collect_pads_new ();
673   gst_collect_pads_set_event_function (qtmux->collect,
674       GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
675   gst_collect_pads_set_clip_function (qtmux->collect,
676       GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
677   gst_collect_pads_set_function (qtmux->collect,
678       GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
679
680   /* properties set to default upon construction */
681
682   qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
683   qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
684   qtmux->reserved_bytes_per_sec_per_trak =
685       DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
686   qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
687   qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
688   qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
689
690   /* always need this */
691   qtmux->context =
692       atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
693
694   /* internals to initial state */
695   gst_qt_mux_reset (qtmux, TRUE);
696 }
697
698
699 static void
700 gst_qt_mux_finalize (GObject * object)
701 {
702   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
703
704   gst_qt_mux_reset (qtmux, FALSE);
705
706   g_free (qtmux->fast_start_file_path);
707   g_free (qtmux->moov_recov_file_path);
708
709   atoms_context_free (qtmux->context);
710   gst_object_unref (qtmux->collect);
711
712   g_slist_free (qtmux->sinkpads);
713
714   G_OBJECT_CLASS (parent_class)->finalize (object);
715 }
716
717 static GstBuffer *
718 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
719     GstQTMux * qtmux)
720 {
721   GstBuffer *newbuf;
722   GstMapInfo map;
723   gsize size;
724
725   GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
726
727   if (buf == NULL)
728     return NULL;
729
730   size = gst_buffer_get_size (buf);
731   newbuf = gst_buffer_new_and_alloc (size + 8);
732   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
733
734   gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
735   GST_WRITE_UINT32_BE (map.data, map.size);
736   GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
737
738   gst_buffer_unmap (buf, &map);
739   gst_buffer_unref (buf);
740
741   return newbuf;
742 }
743
744 static GstBuffer *
745 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
746     GstQTMux * qtmux)
747 {
748   GstBuffer *newbuf;
749   GstMapInfo frommap;
750   GstMapInfo tomap;
751   gsize size;
752   const guint8 *dataend;
753
754   GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
755
756   if (buf == NULL)
757     return NULL;
758
759   gst_buffer_map (buf, &frommap, GST_MAP_READ);
760
761   dataend = memchr (frommap.data, 0, frommap.size);
762   size = dataend ? dataend - frommap.data : frommap.size;
763   newbuf = gst_buffer_new_and_alloc (size + 2);
764
765   gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
766
767   GST_WRITE_UINT16_BE (tomap.data, size);
768   memcpy (tomap.data + 2, frommap.data, size);
769
770   gst_buffer_unmap (newbuf, &tomap);
771   gst_buffer_unmap (buf, &frommap);
772
773   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
774
775   /* gst_buffer_copy_into is trying to be too clever and
776    * won't copy duration when size is different */
777   GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
778
779   gst_buffer_unref (buf);
780
781   return newbuf;
782 }
783
784 static void
785 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
786     guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
787     guint8 lfe_on)
788 {
789   AtomInfo *ext;
790
791   g_return_if_fail (qtpad->trak_ste);
792
793   ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1);        /* bitrate_code is inside frmsizcod */
794
795   sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
796 }
797
798 static GstBuffer *
799 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
800     GstQTMux * qtmux)
801 {
802   GstMapInfo map;
803   GstByteReader reader;
804   guint off;
805
806   if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
807     GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
808     return buf;
809   }
810
811   if (G_UNLIKELY (map.size < 8))
812     goto done;
813
814   gst_byte_reader_init (&reader, map.data, map.size);
815   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
816       0, map.size);
817
818   if (off != -1) {
819     GstBitReader bits;
820     guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
821
822     GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
823         off);
824
825     gst_bit_reader_init (&bits, map.data, map.size);
826
827     /* off + sync + crc */
828     gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
829
830     fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
831     frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
832     bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
833     bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
834     acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
835
836     if ((acmod & 0x1) && (acmod != 0x1))        /* 3 front channels */
837       gst_bit_reader_skip_unchecked (&bits, 2);
838     if ((acmod & 0x4))          /* if a surround channel exists */
839       gst_bit_reader_skip_unchecked (&bits, 2);
840     if (acmod == 0x2)           /* if in 2/0 mode */
841       gst_bit_reader_skip_unchecked (&bits, 2);
842
843     lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
844
845     gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
846         bsmod, acmod, lfe_on);
847
848     /* AC-3 spec says that those values should be constant for the
849      * whole stream when muxed in mp4. We trust the input follows it */
850     GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
851         "prepare buffer function");
852     qtpad->prepare_buf_func = NULL;
853   }
854
855 done:
856   gst_buffer_unmap (buf, &map);
857   return buf;
858 }
859
860 static GstBuffer *
861 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
862 {
863   guint8 *data;
864
865   data = g_malloc (2);
866   GST_WRITE_UINT16_BE (data, 0);
867
868   return gst_buffer_new_wrapped (data, 2);
869 }
870
871 static void
872 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
873     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
874 {
875   switch (gst_tag_get_type (tag)) {
876       /* strings */
877     case G_TYPE_STRING:
878     {
879       gchar *str = NULL;
880
881       if (!gst_tag_list_get_string (list, tag, &str) || !str)
882         break;
883       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
884           GST_FOURCC_ARGS (fourcc), str);
885       atom_udta_add_str_tag (udta, fourcc, str);
886       g_free (str);
887       break;
888     }
889       /* double */
890     case G_TYPE_DOUBLE:
891     {
892       gdouble value;
893
894       if (!gst_tag_list_get_double (list, tag, &value))
895         break;
896       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
897           GST_FOURCC_ARGS (fourcc), (gint) value);
898       atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
899       break;
900     }
901     case G_TYPE_UINT:
902     {
903       guint value = 0;
904       if (tag2) {
905         /* paired unsigned integers */
906         guint count = 0;
907         gboolean got_tag;
908
909         got_tag = gst_tag_list_get_uint (list, tag, &value);
910         got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
911         if (!got_tag)
912           break;
913         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
914             GST_FOURCC_ARGS (fourcc), value, count);
915         atom_udta_add_uint_tag (udta, fourcc, 0,
916             value << 16 | (count & 0xFFFF));
917       } else {
918         /* unpaired unsigned integers */
919         if (!gst_tag_list_get_uint (list, tag, &value))
920           break;
921         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
922             GST_FOURCC_ARGS (fourcc), value);
923         atom_udta_add_uint_tag (udta, fourcc, 1, value);
924       }
925       break;
926     }
927     default:
928       g_assert_not_reached ();
929       break;
930   }
931 }
932
933 static void
934 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
935     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
936 {
937   GDate *date = NULL;
938   GDateYear year;
939   GDateMonth month;
940   GDateDay day;
941   gchar *str;
942
943   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
944
945   if (!gst_tag_list_get_date (list, tag, &date) || !date)
946     return;
947
948   year = g_date_get_year (date);
949   month = g_date_get_month (date);
950   day = g_date_get_day (date);
951
952   g_date_free (date);
953
954   if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
955       day == G_DATE_BAD_DAY) {
956     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
957     return;
958   }
959
960   str = g_strdup_printf ("%u-%u-%u", year, month, day);
961   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
962       GST_FOURCC_ARGS (fourcc), str);
963   atom_udta_add_str_tag (udta, fourcc, str);
964   g_free (str);
965 }
966
967 static void
968 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
969     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
970 {
971   GValue value = { 0, };
972   GstBuffer *buf;
973   GstSample *sample;
974   GstCaps *caps;
975   GstStructure *structure;
976   gint flags = 0;
977   GstMapInfo map;
978
979   g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
980
981   if (!gst_tag_list_copy_value (&value, list, tag))
982     return;
983
984   sample = gst_value_get_sample (&value);
985
986   if (!sample)
987     goto done;
988
989   buf = gst_sample_get_buffer (sample);
990   if (!buf)
991     goto done;
992
993   caps = gst_sample_get_caps (sample);
994   if (!caps) {
995     GST_WARNING_OBJECT (qtmux, "preview image without caps");
996     goto done;
997   }
998
999   GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1000
1001   structure = gst_caps_get_structure (caps, 0);
1002   if (gst_structure_has_name (structure, "image/jpeg"))
1003     flags = 13;
1004   else if (gst_structure_has_name (structure, "image/png"))
1005     flags = 14;
1006
1007   if (!flags) {
1008     GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1009     goto done;
1010   }
1011
1012   gst_buffer_map (buf, &map, GST_MAP_READ);
1013   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1014       " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1015   atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1016   gst_buffer_unmap (buf, &map);
1017 done:
1018   g_value_unset (&value);
1019 }
1020
1021 static void
1022 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1023     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1024 {
1025   gchar *str = NULL;
1026   guint number;
1027
1028   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1029   g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1030
1031   if (!gst_tag_list_get_string (list, tag, &str) || !str)
1032     return;
1033
1034   if (tag2)
1035     if (!gst_tag_list_get_uint (list, tag2, &number))
1036       tag2 = NULL;
1037
1038   if (!tag2) {
1039     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1040         GST_FOURCC_ARGS (fourcc), str);
1041     atom_udta_add_3gp_str_tag (udta, fourcc, str);
1042   } else {
1043     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1044         GST_FOURCC_ARGS (fourcc), str, number);
1045     atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1046   }
1047
1048   g_free (str);
1049 }
1050
1051 static void
1052 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1053     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1054 {
1055   GDate *date = NULL;
1056   GDateYear year;
1057
1058   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1059
1060   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1061     return;
1062
1063   year = g_date_get_year (date);
1064   g_date_free (date);
1065
1066   if (year == G_DATE_BAD_YEAR) {
1067     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1068     return;
1069   }
1070
1071   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1072       GST_FOURCC_ARGS (fourcc), year);
1073   atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1074 }
1075
1076 static void
1077 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1078     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1079 {
1080   gdouble latitude = -360, longitude = -360, altitude = 0;
1081   gchar *location = NULL;
1082   guint8 *data, *ddata;
1083   gint size = 0, len = 0;
1084   gboolean ret = FALSE;
1085
1086   g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1087
1088   ret = gst_tag_list_get_string (list, tag, &location);
1089   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1090       &longitude);
1091   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1092       &latitude);
1093   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1094       &altitude);
1095
1096   if (!ret)
1097     return;
1098
1099   if (location)
1100     len = strlen (location);
1101   size += len + 1 + 2;
1102
1103   /* role + (long, lat, alt) + body + notes */
1104   size += 1 + 3 * 4 + 1 + 1;
1105
1106   data = ddata = g_malloc (size);
1107
1108   /* language tag */
1109   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1110   /* location */
1111   if (location)
1112     memcpy (data + 2, location, len);
1113   GST_WRITE_UINT8 (data + 2 + len, 0);
1114   data += len + 1 + 2;
1115   /* role */
1116   GST_WRITE_UINT8 (data, 0);
1117   /* long, lat, alt */
1118 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1119   QT_WRITE_SFP32 (data + 1, longitude);
1120   QT_WRITE_SFP32 (data + 5, latitude);
1121   QT_WRITE_SFP32 (data + 9, altitude);
1122   /* neither astronomical body nor notes */
1123   GST_WRITE_UINT16_BE (data + 13, 0);
1124
1125   GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1126   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1127   g_free (ddata);
1128 }
1129
1130 static void
1131 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1132     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1133 {
1134   gchar *keywords = NULL;
1135   guint8 *data, *ddata;
1136   gint size = 0, i;
1137   gchar **kwds;
1138
1139   g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1140
1141   if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1142     return;
1143
1144   kwds = g_strsplit (keywords, ",", 0);
1145   g_free (keywords);
1146
1147   size = 0;
1148   for (i = 0; kwds[i]; i++) {
1149     /* size byte + null-terminator */
1150     size += strlen (kwds[i]) + 1 + 1;
1151   }
1152
1153   /* language tag + count + keywords */
1154   size += 2 + 1;
1155
1156   data = ddata = g_malloc (size);
1157
1158   /* language tag */
1159   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1160   /* count */
1161   GST_WRITE_UINT8 (data + 2, i);
1162   data += 3;
1163   /* keywords */
1164   for (i = 0; kwds[i]; ++i) {
1165     gint len = strlen (kwds[i]);
1166
1167     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1168         GST_FOURCC_ARGS (fourcc), kwds[i]);
1169     /* size */
1170     GST_WRITE_UINT8 (data, len + 1);
1171     memcpy (data + 1, kwds[i], len + 1);
1172     data += len + 2;
1173   }
1174
1175   g_strfreev (kwds);
1176
1177   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1178   g_free (ddata);
1179 }
1180
1181 static gboolean
1182 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1183     guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1184 {
1185   guint32 fourcc;
1186   gint table;
1187   gint size;
1188   const gchar *data;
1189
1190   data = input;
1191   size = strlen (input);
1192
1193   if (size < 4 + 3 + 1 + 1 + 1) {
1194     /* at least the minimum xxxx://y/z */
1195     GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1196         "ignoring", input);
1197     return FALSE;
1198   }
1199
1200   /* read the fourcc */
1201   memcpy (&fourcc, data, 4);
1202   size -= 4;
1203   data += 4;
1204
1205   if (strncmp (data, "://", 3) != 0) {
1206     goto mismatch;
1207   }
1208   data += 3;
1209   size -= 3;
1210
1211   /* read the table number */
1212   if (sscanf (data, "%d", &table) != 1) {
1213     goto mismatch;
1214   }
1215   if (table < 0) {
1216     GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1217         ", table numbers should be positive, ignoring tag", table);
1218     return FALSE;
1219   }
1220
1221   /* find the next / */
1222   while (size > 0 && data[0] != '/') {
1223     data += 1;
1224     size -= 1;
1225   }
1226   if (size == 0) {
1227     goto mismatch;
1228   }
1229   g_assert (data[0] == '/');
1230
1231   /* skip the '/' */
1232   data += 1;
1233   size -= 1;
1234   if (size == 0) {
1235     goto mismatch;
1236   }
1237
1238   /* read up the rest of the string */
1239   *p_content = g_strdup (data);
1240   *p_table = (guint16) table;
1241   *p_fourcc = fourcc;
1242   return TRUE;
1243
1244 mismatch:
1245   {
1246     GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1247         "input (%s) didn't match the expected entitycode://table/content",
1248         input);
1249     return FALSE;
1250   }
1251 }
1252
1253 static void
1254 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1255     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1256 {
1257   gchar *clsf_data = NULL;
1258   gint size = 0;
1259   guint32 entity = 0;
1260   guint16 table = 0;
1261   gchar *content = NULL;
1262   guint8 *data;
1263
1264   g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1265
1266   if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1267     return;
1268
1269   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1270       GST_FOURCC_ARGS (fourcc), clsf_data);
1271
1272   /* parse the string, format is:
1273    * entityfourcc://table/content
1274    */
1275   gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1276       &content);
1277   g_free (clsf_data);
1278   /* +1 for the \0 */
1279   size = strlen (content) + 1;
1280
1281   /* now we have everything, build the atom
1282    * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1283   data = g_malloc (4 + 2 + 2 + size);
1284   GST_WRITE_UINT32_LE (data, entity);
1285   GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1286   GST_WRITE_UINT16_BE (data + 6, 0);
1287   memcpy (data + 8, content, size);
1288   g_free (content);
1289
1290   atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1291   g_free (data);
1292 }
1293
1294 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1295     const GstTagList * list, AtomUDTA * udta, const char *tag,
1296     const char *tag2, guint32 fourcc);
1297
1298 /*
1299  * Struct to record mappings from gstreamer tags to fourcc codes
1300  */
1301 typedef struct _GstTagToFourcc
1302 {
1303   guint32 fourcc;
1304   const gchar *gsttag;
1305   const gchar *gsttag2;
1306   const GstQTMuxAddUdtaTagFunc func;
1307 } GstTagToFourcc;
1308
1309 /* tag list tags to fourcc matching */
1310 static const GstTagToFourcc tag_matches_mp4[] = {
1311   {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1312   {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1313   {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1314   {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1315   {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1316   {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1317   {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1318   {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1319   {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1320   {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1321   {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1322   {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1323   {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1324   {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1325   {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1326   {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1327   {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1328   {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1329   {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1330   {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1331   {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1332   {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1333   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1334   {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1335   {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1336   {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1337   {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1338       gst_qt_mux_add_mp4_tag},
1339   {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1340       gst_qt_mux_add_mp4_tag},
1341   {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1342   {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1343   {0, NULL,}
1344 };
1345
1346 static const GstTagToFourcc tag_matches_3gp[] = {
1347   {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1348   {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1349   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1350   {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1351   {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1352   {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1353   {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1354   {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1355   {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1356   {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1357   {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1358       gst_qt_mux_add_3gp_classification},
1359   {0, NULL,}
1360 };
1361
1362 /* qtdemux produces these for atoms it cannot parse */
1363 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1364
1365 static void
1366 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1367 {
1368   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1369   GstBuffer *xmp = NULL;
1370
1371   /* adobe specs only have 'quicktime' and 'mp4',
1372    * but I guess we can extrapolate to gpp.
1373    * Keep mj2 out for now as we don't add any tags for it yet.
1374    * If you have further info about xmp on these formats, please share */
1375   if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1376     return;
1377
1378   GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1379
1380   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1381     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1382         list, TRUE);
1383     if (xmp)
1384       atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1385   } else {
1386     AtomInfo *ainfo;
1387     /* for isom/mp4, it is a top level uuid atom */
1388     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1389         list, TRUE);
1390     if (xmp) {
1391       ainfo = build_uuid_xmp_atom (xmp);
1392       if (ainfo) {
1393         qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1394       }
1395     }
1396   }
1397   if (xmp)
1398     gst_buffer_unref (xmp);
1399 }
1400
1401 static void
1402 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1403     AtomUDTA * udta)
1404 {
1405   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1406   guint32 fourcc;
1407   gint i;
1408   const gchar *tag, *tag2;
1409   const GstTagToFourcc *tag_matches;
1410
1411   switch (qtmux_klass->format) {
1412     case GST_QT_MUX_FORMAT_3GP:
1413       tag_matches = tag_matches_3gp;
1414       break;
1415     case GST_QT_MUX_FORMAT_MJ2:
1416       tag_matches = NULL;
1417       break;
1418     default:
1419       /* sort of iTunes style for mp4 and QT (?) */
1420       tag_matches = tag_matches_mp4;
1421       break;
1422   }
1423
1424   if (!tag_matches)
1425     return;
1426
1427   /* Clear existing tags so we don't add them over and over */
1428   atom_udta_clear_tags (udta);
1429
1430   for (i = 0; tag_matches[i].fourcc; i++) {
1431     fourcc = tag_matches[i].fourcc;
1432     tag = tag_matches[i].gsttag;
1433     tag2 = tag_matches[i].gsttag2;
1434
1435     g_assert (tag_matches[i].func);
1436     tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1437   }
1438
1439   /* add unparsed blobs if present */
1440   if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1441     guint num_tags;
1442
1443     num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1444     for (i = 0; i < num_tags; ++i) {
1445       GstSample *sample = NULL;
1446       GstBuffer *buf;
1447       const GstStructure *s;
1448
1449       if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1450               &sample))
1451         continue;
1452       buf = gst_sample_get_buffer (sample);
1453
1454       if (buf && (s = gst_sample_get_info (sample))) {
1455         const gchar *style = NULL;
1456         GstMapInfo map;
1457
1458         gst_buffer_map (buf, &map, GST_MAP_READ);
1459         GST_DEBUG_OBJECT (qtmux,
1460             "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1461             GST_PTR_FORMAT, i, num_tags, map.size, s);
1462         if (s && (style = gst_structure_get_string (s, "style"))) {
1463           /* try to prevent some style tag ending up into another variant
1464            * (todo: make into a list if more cases) */
1465           if ((strcmp (style, "itunes") == 0 &&
1466                   qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1467               (strcmp (style, "iso") == 0 &&
1468                   qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1469             GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1470             atom_udta_add_blob_tag (udta, map.data, map.size);
1471           }
1472         }
1473         gst_buffer_unmap (buf, &map);
1474       }
1475       gst_sample_unref (sample);
1476     }
1477   }
1478
1479   return;
1480 }
1481
1482 /*
1483  * Gets the tagsetter iface taglist and puts the known tags
1484  * into the output stream
1485  */
1486 static void
1487 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1488 {
1489   const GstTagList *tags = NULL;
1490   GSList *walk;
1491
1492   GST_OBJECT_LOCK (qtmux);
1493   if (qtmux->tags_changed) {
1494     tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1495     qtmux->tags_changed = FALSE;
1496   }
1497   GST_OBJECT_UNLOCK (qtmux);
1498
1499   GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1500
1501   if (tags && !gst_tag_list_is_empty (tags)) {
1502     GstTagList *copy = gst_tag_list_copy (tags);
1503
1504     GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1505     gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1506     gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1507     gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1508
1509     GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1510     gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1511     gst_qt_mux_add_xmp_tags (qtmux, copy);
1512     gst_tag_list_unref (copy);
1513   } else {
1514     GST_DEBUG_OBJECT (qtmux, "No new tags received");
1515   }
1516
1517   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1518     GstCollectData *cdata = (GstCollectData *) walk->data;
1519     GstQTPad *qpad = (GstQTPad *) cdata;
1520     GstPad *pad = qpad->collect.pad;
1521
1522     if (qpad->tags_changed && qpad->tags) {
1523       GST_DEBUG_OBJECT (pad, "Adding tags");
1524       gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1525       gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1526       qpad->tags_changed = FALSE;
1527       GST_DEBUG_OBJECT (pad, "Tags added");
1528     } else {
1529       GST_DEBUG_OBJECT (pad, "No new tags received");
1530     }
1531   }
1532 }
1533
1534 static inline GstBuffer *
1535 _gst_buffer_new_take_data (guint8 * data, guint size)
1536 {
1537   GstBuffer *buf;
1538
1539   buf = gst_buffer_new ();
1540   gst_buffer_append_memory (buf,
1541       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1542
1543   return buf;
1544 }
1545
1546 static GstFlowReturn
1547 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1548     gboolean mind_fast)
1549 {
1550   GstFlowReturn res;
1551   gsize size;
1552
1553   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1554
1555   size = gst_buffer_get_size (buf);
1556   GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1557
1558   if (mind_fast && qtmux->fast_start_file) {
1559     GstMapInfo map;
1560     gint ret;
1561
1562     GST_LOG_OBJECT (qtmux, "to temporary file");
1563     gst_buffer_map (buf, &map, GST_MAP_READ);
1564     ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1565     gst_buffer_unmap (buf, &map);
1566     gst_buffer_unref (buf);
1567     if (ret != size)
1568       goto write_error;
1569     else
1570       res = GST_FLOW_OK;
1571   } else {
1572     GST_LOG_OBJECT (qtmux, "downstream");
1573     res = gst_pad_push (qtmux->srcpad, buf);
1574   }
1575
1576   if (G_LIKELY (offset))
1577     *offset += size;
1578
1579   return res;
1580
1581   /* ERRORS */
1582 write_error:
1583   {
1584     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1585         ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1586     return GST_FLOW_ERROR;
1587   }
1588 }
1589
1590 static gboolean
1591 gst_qt_mux_seek_to_beginning (FILE * f)
1592 {
1593 #ifdef HAVE_FSEEKO
1594   if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1595     return FALSE;
1596 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1597   if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1598     return FALSE;
1599 #else
1600   if (fseek (f, (long) 0, SEEK_SET) != 0)
1601     return FALSE;
1602 #endif
1603   return TRUE;
1604 }
1605
1606 static GstFlowReturn
1607 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1608 {
1609   GstFlowReturn ret = GST_FLOW_OK;
1610   GstBuffer *buf = NULL;
1611
1612   if (fflush (qtmux->fast_start_file))
1613     goto flush_failed;
1614
1615   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1616     goto seek_failed;
1617
1618   /* hm, this could all take a really really long time,
1619    * but there may not be another way to get moov atom first
1620    * (somehow optimize copy?) */
1621   GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1622   while (ret == GST_FLOW_OK) {
1623     const int bufsize = 4096;
1624     GstMapInfo map;
1625     gsize size;
1626
1627     buf = gst_buffer_new_and_alloc (bufsize);
1628     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1629     size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1630     if (size == 0) {
1631       gst_buffer_unmap (buf, &map);
1632       break;
1633     }
1634     GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1635     gst_buffer_unmap (buf, &map);
1636     if (size != bufsize)
1637       gst_buffer_set_size (buf, size);
1638     ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1639     buf = NULL;
1640   }
1641   if (buf)
1642     gst_buffer_unref (buf);
1643
1644   if (ftruncate (fileno (qtmux->fast_start_file), 0))
1645     goto seek_failed;
1646   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1647     goto seek_failed;
1648
1649   return ret;
1650
1651   /* ERRORS */
1652 flush_failed:
1653   {
1654     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1655         ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1656     ret = GST_FLOW_ERROR;
1657     goto fail;
1658   }
1659 seek_failed:
1660   {
1661     GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1662         ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1663     ret = GST_FLOW_ERROR;
1664     goto fail;
1665   }
1666 fail:
1667   {
1668     /* clear descriptor so we don't remove temp file later on,
1669      * might be possible to recover */
1670     fclose (qtmux->fast_start_file);
1671     qtmux->fast_start_file = NULL;
1672     return ret;
1673   }
1674 }
1675
1676 /*
1677  * Sends the initial mdat atom fields (size fields and fourcc type),
1678  * the subsequent buffers are considered part of it's data.
1679  * As we can't predict the amount of data that we are going to place in mdat
1680  * we need to record the position of the size field in the stream so we can
1681  * seek back to it later and update when the streams have finished.
1682  */
1683 static GstFlowReturn
1684 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1685     gboolean extended, gboolean fsync_after)
1686 {
1687   GstBuffer *buf;
1688   GstMapInfo map;
1689
1690   GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1691       "size %" G_GUINT64_FORMAT, size);
1692
1693   /* if the qtmux state is EOS, really write the mdat, otherwise
1694    * allow size == 0 for a placeholder atom */
1695   if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1696     size += 8;
1697
1698   if (extended) {
1699     gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1700     /* Always write 16-bytes, but put a free atom first
1701      * if the size is < 4GB. */
1702     buf = gst_buffer_new_and_alloc (16);
1703     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1704
1705     if (large_file) {
1706       /* Write extended mdat header and large_size field */
1707       GST_WRITE_UINT32_BE (map.data, 1);
1708       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1709       GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1710     } else {
1711       /* Write an empty free atom, then standard 32-bit mdat */
1712       GST_WRITE_UINT32_BE (map.data, 8);
1713       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1714       GST_WRITE_UINT32_BE (map.data + 8, size);
1715       GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1716     }
1717     gst_buffer_unmap (buf, &map);
1718   } else {
1719     buf = gst_buffer_new_and_alloc (8);
1720     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1721
1722     /* Vanilla 32-bit mdat */
1723     GST_WRITE_UINT32_BE (map.data, size);
1724     GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1725     gst_buffer_unmap (buf, &map);
1726   }
1727
1728   GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1729   if (fsync_after)
1730     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1731
1732   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1733
1734 }
1735
1736 /*
1737  * We get the position of the mdat size field, seek back to it
1738  * and overwrite with the real value
1739  */
1740 static GstFlowReturn
1741 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1742     guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1743 {
1744   GstSegment segment;
1745
1746   /* We must have recorded the mdat position for this to work */
1747   g_assert (mdat_pos != 0);
1748
1749   /* seek and rewrite the header */
1750   gst_segment_init (&segment, GST_FORMAT_BYTES);
1751   segment.start = mdat_pos;
1752   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1753
1754   return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1755       fsync_after);
1756 }
1757
1758 static GstFlowReturn
1759 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1760 {
1761   GstBuffer *buf;
1762   guint64 size = 0, offset = 0;
1763   guint8 *data = NULL;
1764
1765   GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1766
1767   if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1768     goto serialize_error;
1769
1770   buf = _gst_buffer_new_take_data (data, offset);
1771
1772   GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1773   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1774
1775   /* ERRORS */
1776 serialize_error:
1777   {
1778     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1779         ("Failed to serialize ftyp"));
1780     return GST_FLOW_ERROR;
1781   }
1782 }
1783
1784 static void
1785 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1786     GstBuffer ** p_prefix)
1787 {
1788   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1789   guint32 major, version;
1790   GList *comp;
1791   GstBuffer *prefix = NULL;
1792   AtomFTYP *ftyp = NULL;
1793
1794   GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1795
1796   /* init and send context and ftyp based on current property state */
1797   gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1798       &version, &comp, qtmux->moov, qtmux->longest_chunk,
1799       qtmux->fast_start_file != NULL);
1800   ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1801   if (comp)
1802     g_list_free (comp);
1803   if (prefix) {
1804     if (p_prefix)
1805       *p_prefix = prefix;
1806     else
1807       gst_buffer_unref (prefix);
1808   }
1809   *p_ftyp = ftyp;
1810 }
1811
1812 static GstFlowReturn
1813 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1814 {
1815   GstFlowReturn ret = GST_FLOW_OK;
1816   GstBuffer *prefix = NULL;
1817
1818   GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1819
1820   /* init and send context and ftyp based on current property state */
1821   if (qtmux->ftyp) {
1822     atom_ftyp_free (qtmux->ftyp);
1823     qtmux->ftyp = NULL;
1824   }
1825   gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1826   if (prefix) {
1827     ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1828     if (ret != GST_FLOW_OK)
1829       return ret;
1830   }
1831   return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1832 }
1833
1834 static void
1835 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1836 {
1837   GstStructure *structure;
1838   GValue array = { 0 };
1839   GValue value = { 0 };
1840   GstCaps *caps, *tcaps;
1841
1842   tcaps = gst_pad_get_current_caps (mux->srcpad);
1843   caps = gst_caps_copy (tcaps);
1844   gst_caps_unref (tcaps);
1845
1846   structure = gst_caps_get_structure (caps, 0);
1847
1848   g_value_init (&array, GST_TYPE_ARRAY);
1849
1850   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1851   g_value_init (&value, GST_TYPE_BUFFER);
1852   gst_value_take_buffer (&value, gst_buffer_ref (buf));
1853   gst_value_array_append_value (&array, &value);
1854   g_value_unset (&value);
1855
1856   gst_structure_set_value (structure, "streamheader", &array);
1857   g_value_unset (&array);
1858   gst_pad_set_caps (mux->srcpad, caps);
1859   gst_caps_unref (caps);
1860 }
1861
1862 /*
1863  * Write out a free space atom. The offset is adjusted by the full
1864  * size, but a smaller buffer is sent
1865  */
1866 static GstFlowReturn
1867 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1868     gboolean fsync_after)
1869 {
1870   Atom *node_header;
1871   GstBuffer *buf;
1872   guint8 *data = NULL;
1873   guint64 offset = 0, bsize = 0;
1874   GstFlowReturn ret;
1875
1876   GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1877
1878   /* We can't make a free space atom smaller than the header */
1879   if (size < 8)
1880     goto too_small;
1881
1882   node_header = g_malloc0 (sizeof (Atom));
1883   node_header->type = FOURCC_free;
1884   node_header->size = size;
1885
1886   bsize = offset = 0;
1887   if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
1888     goto serialize_error;
1889
1890   buf = _gst_buffer_new_take_data (data, offset);
1891   g_free (node_header);
1892
1893   if (fsync_after)
1894     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1895
1896   GST_LOG_OBJECT (qtmux, "Pushing free atom");
1897   ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1898
1899   if (off) {
1900     GstSegment segment;
1901
1902     *off += size - 8;
1903
1904     /* Make sure downstream position ends up at the end of this free box */
1905     gst_segment_init (&segment, GST_FORMAT_BYTES);
1906     segment.start = *off;
1907     gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1908   }
1909
1910   return ret;
1911
1912   /* ERRORS */
1913 too_small:
1914   {
1915     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1916         ("Not enough free reserved space"));
1917     return GST_FLOW_ERROR;
1918   }
1919 serialize_error:
1920   {
1921     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1922         ("Failed to serialize mdat"));
1923     g_free (node_header);
1924     return GST_FLOW_ERROR;
1925   }
1926 }
1927
1928 static void
1929 gst_qt_mux_configure_moov (GstQTMux * qtmux)
1930 {
1931   gboolean fragmented = FALSE;
1932   guint32 timescale;
1933
1934   GST_OBJECT_LOCK (qtmux);
1935   timescale = qtmux->timescale;
1936   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
1937       qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
1938     fragmented = TRUE;
1939   GST_OBJECT_UNLOCK (qtmux);
1940
1941   /* inform lower layers of our property wishes, and determine duration.
1942    * Let moov take care of this using its list of traks;
1943    * so that released pads are also included */
1944   GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1945       timescale);
1946   atom_moov_update_timescale (qtmux->moov, timescale);
1947   atom_moov_set_fragmented (qtmux->moov, fragmented);
1948
1949   atom_moov_update_duration (qtmux->moov);
1950 }
1951
1952 static GstFlowReturn
1953 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
1954     guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
1955 {
1956   guint64 offset = 0, size = 0;
1957   guint8 *data;
1958   GstBuffer *buf;
1959   GstFlowReturn ret = GST_FLOW_OK;
1960   GSList *walk;
1961   guint64 current_time = atoms_get_current_qt_time ();
1962
1963   /* update modification times */
1964   qtmux->moov->mvhd.time_info.modification_time = current_time;
1965   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1966     GstCollectData *cdata = (GstCollectData *) walk->data;
1967     GstQTPad *qtpad = (GstQTPad *) cdata;
1968
1969     qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
1970     qtpad->trak->tkhd.modification_time = current_time;
1971   }
1972
1973   /* serialize moov */
1974   offset = size = 0;
1975   data = NULL;
1976   GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1977   if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1978     goto serialize_error;
1979   qtmux->last_moov_size = offset;
1980
1981   /* Check we have enough reserved space for this and a Free atom */
1982   if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
1983     goto too_small_reserved;
1984   buf = _gst_buffer_new_take_data (data, offset);
1985   GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1986
1987   /* If at EOS, this is the final moov, put in the streamheader
1988    * (apparently used by a flumotion util) */
1989   if (qtmux->state == GST_QT_MUX_STATE_EOS)
1990     gst_qt_mux_set_header_on_caps (qtmux, buf);
1991
1992   if (fsync_after)
1993     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1994   ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1995
1996   /* Write out a free atom if needed */
1997   if (ret == GST_FLOW_OK && offset < padded_moov_size) {
1998     GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
1999         (guint32) (padded_moov_size - offset));
2000     ret =
2001         gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2002         fsync_after);
2003   }
2004
2005   return ret;
2006 too_small_reserved:
2007   {
2008     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2009         ("Not enough free reserved header space"),
2010         ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2011             offset, padded_moov_size));
2012     return GST_FLOW_ERROR;
2013   }
2014 serialize_error:
2015   {
2016     g_free (data);
2017     return GST_FLOW_ERROR;
2018   }
2019 }
2020
2021 /* either calculates size of extra atoms or pushes them */
2022 static GstFlowReturn
2023 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2024     gboolean mind_fast)
2025 {
2026   GSList *walk;
2027   guint64 loffset = 0, size = 0;
2028   guint8 *data;
2029   GstFlowReturn ret = GST_FLOW_OK;
2030
2031   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2032     AtomInfo *ainfo = (AtomInfo *) walk->data;
2033
2034     loffset = size = 0;
2035     data = NULL;
2036     if (!ainfo->copy_data_func (ainfo->atom,
2037             send ? &data : NULL, &size, &loffset))
2038       goto serialize_error;
2039
2040     if (send) {
2041       GstBuffer *buf;
2042
2043       GST_DEBUG_OBJECT (qtmux,
2044           "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2045           GST_FOURCC_ARGS (ainfo->atom->type));
2046       buf = _gst_buffer_new_take_data (data, loffset);
2047       ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2048       if (ret != GST_FLOW_OK)
2049         break;
2050     } else {
2051       if (offset)
2052         *offset += loffset;
2053     }
2054   }
2055
2056   return ret;
2057
2058 serialize_error:
2059   {
2060     g_free (data);
2061     return GST_FLOW_ERROR;
2062   }
2063 }
2064
2065 static gboolean
2066 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2067 {
2068   gboolean seekable = FALSE;
2069   GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2070
2071   if (gst_pad_peer_query (qtmux->srcpad, query)) {
2072     gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2073     GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2074   } else {
2075     /* have to assume seeking is not supported if query not handled downstream */
2076     GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2077     seekable = FALSE;
2078   }
2079   gst_query_unref (query);
2080
2081   return seekable;
2082 }
2083
2084 static void
2085 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2086 {
2087   GSList *walk;
2088   gboolean fail = FALSE;
2089   AtomFTYP *ftyp = NULL;
2090   GstBuffer *prefix = NULL;
2091
2092   GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2093       qtmux->moov_recov_file_path);
2094
2095   qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2096   if (qtmux->moov_recov_file == NULL) {
2097     GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2098         qtmux->moov_recov_file_path);
2099     return;
2100   }
2101
2102   gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2103
2104   if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2105           qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2106     GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2107     goto fail;
2108   }
2109
2110   atom_ftyp_free (ftyp);
2111   if (prefix)
2112     gst_buffer_unref (prefix);
2113
2114   for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2115     GstCollectData *cdata = (GstCollectData *) walk->data;
2116     GstQTPad *qpad = (GstQTPad *) cdata;
2117     /* write info for each stream */
2118     fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2119     if (fail) {
2120       GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2121           "file");
2122       break;
2123     }
2124   }
2125
2126   return;
2127
2128 fail:
2129   /* cleanup */
2130   fclose (qtmux->moov_recov_file);
2131   qtmux->moov_recov_file = NULL;
2132 }
2133
2134 static guint64
2135 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2136 {
2137   switch (qpad->fourcc) {
2138     case FOURCC_apch:
2139     case FOURCC_apcn:
2140     case FOURCC_apcs:
2141     case FOURCC_apco:
2142     case FOURCC_ap4h:
2143     case FOURCC_ap4x:
2144       return qpad->sample_offset;
2145     case FOURCC_sowt:
2146     case FOURCC_twos:
2147       return gst_util_uint64_scale_ceil (qpad->sample_offset,
2148           qpad->expected_sample_duration_n,
2149           qpad->expected_sample_duration_d *
2150           atom_trak_get_timescale (qpad->trak));
2151     default:
2152       return -1;
2153   }
2154 }
2155
2156 static guint
2157 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2158 {
2159   switch (qpad->fourcc) {
2160     case FOURCC_apch:
2161       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2162         return 300000;
2163       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2164         return 350000;
2165       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2166         return 525000;
2167       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2168         return 1050000;
2169       } else {
2170         return 4150000;
2171       }
2172       break;
2173     case FOURCC_apcn:
2174       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2175         return 200000;
2176       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2177         return 250000;
2178       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2179         return 350000;
2180       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2181         return 700000;
2182       } else {
2183         return 2800000;
2184       }
2185       break;
2186     case FOURCC_apcs:
2187       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2188         return 150000;
2189       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2190         return 200000;
2191       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2192         return 250000;
2193       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2194         return 500000;
2195       } else {
2196         return 2800000;
2197       }
2198       break;
2199     case FOURCC_apco:
2200       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2201         return 80000;
2202       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2203         return 100000;
2204       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2205         return 150000;
2206       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2207         return 250000;
2208       } else {
2209         return 900000;
2210       }
2211       break;
2212     case FOURCC_sowt:
2213     case FOURCC_twos:{
2214       guint64 block_idx;
2215       guint64 next_sample_offset;
2216
2217       block_idx = prefill_get_block_index (qtmux, qpad);
2218       next_sample_offset =
2219           gst_util_uint64_scale (block_idx + 1,
2220           qpad->expected_sample_duration_d *
2221           atom_trak_get_timescale (qpad->trak),
2222           qpad->expected_sample_duration_n);
2223
2224       return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2225     }
2226     case FOURCC_ap4h:
2227     case FOURCC_ap4x:
2228     default:
2229       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2230       return -1;
2231   }
2232
2233   return -1;
2234 }
2235
2236 static GstClockTime
2237 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2238 {
2239   switch (qpad->fourcc) {
2240     case FOURCC_apch:
2241     case FOURCC_apcn:
2242     case FOURCC_apcs:
2243     case FOURCC_apco:
2244     case FOURCC_ap4h:
2245     case FOURCC_ap4x:
2246       return gst_util_uint64_scale (qpad->sample_offset + 1,
2247           qpad->expected_sample_duration_d * GST_SECOND,
2248           qpad->expected_sample_duration_n);
2249     case FOURCC_sowt:
2250     case FOURCC_twos:{
2251       guint64 block_idx;
2252       guint64 next_sample_offset;
2253
2254       block_idx = prefill_get_block_index (qtmux, qpad);
2255       next_sample_offset =
2256           gst_util_uint64_scale (block_idx + 1,
2257           qpad->expected_sample_duration_d *
2258           atom_trak_get_timescale (qpad->trak),
2259           qpad->expected_sample_duration_n);
2260
2261       return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2262           atom_trak_get_timescale (qpad->trak));
2263     }
2264     default:
2265       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2266       return -1;
2267   }
2268
2269   return -1;
2270 }
2271
2272 static GstBuffer *
2273 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2274     GstQTMux * qtmux)
2275 {
2276   guint64 block_idx;
2277   guint64 nsamples;
2278   GstClockTime input_timestamp;
2279   guint64 input_timestamp_distance;
2280
2281   if (buf)
2282     gst_adapter_push (qtpad->raw_audio_adapter, buf);
2283
2284   block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2285       qtpad->expected_sample_duration_n,
2286       qtpad->expected_sample_duration_d *
2287       atom_trak_get_timescale (qtpad->trak));
2288   nsamples =
2289       gst_util_uint64_scale (block_idx + 1,
2290       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2291       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2292
2293   if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2294               GST_COLLECT_PADS_STATE_EOS)
2295           && gst_adapter_available (qtpad->raw_audio_adapter) <
2296           nsamples * qtpad->sample_size)
2297       || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2298     return NULL;
2299   }
2300
2301   input_timestamp =
2302       gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2303       &input_timestamp_distance);
2304   if (input_timestamp != GST_CLOCK_TIME_NONE)
2305     input_timestamp +=
2306         gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2307         qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2308
2309   buf =
2310       gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2311       !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2312           GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2313       qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2314   GST_BUFFER_PTS (buf) = input_timestamp;
2315   GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2316   GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2317
2318   qtpad->raw_audio_adapter_offset += nsamples;
2319
2320   /* Check if we have yet another block of raw audio in the adapter */
2321   nsamples =
2322       gst_util_uint64_scale (block_idx + 2,
2323       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2324       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2325   if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2326       nsamples * qtpad->sample_size) {
2327     input_timestamp =
2328         gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2329         &input_timestamp_distance);
2330     if (input_timestamp != GST_CLOCK_TIME_NONE)
2331       input_timestamp +=
2332           gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2333           qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2334     qtpad->raw_audio_adapter_pts = input_timestamp;
2335   } else {
2336     qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2337   }
2338
2339   return buf;
2340 }
2341
2342 static gboolean
2343 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2344 {
2345   switch (qpad->fourcc) {
2346     case FOURCC_apch:
2347     case FOURCC_apcn:
2348     case FOURCC_apcs:
2349     case FOURCC_apco:
2350     case FOURCC_ap4h:
2351     case FOURCC_ap4x:{
2352       guint sample_size = prefill_get_sample_size (qtmux, qpad);
2353       atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2354       return TRUE;
2355     }
2356     case FOURCC_sowt:
2357     case FOURCC_twos:{
2358       GSList *walk;
2359
2360       /* Find the (first) video track and assume that we have to output
2361        * in that size */
2362       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2363         GstCollectData *cdata = (GstCollectData *) walk->data;
2364         GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2365
2366         if (tmp_qpad->trak->is_video) {
2367           qpad->expected_sample_duration_n =
2368               tmp_qpad->expected_sample_duration_n;
2369           qpad->expected_sample_duration_d =
2370               tmp_qpad->expected_sample_duration_d;
2371           break;
2372         }
2373       }
2374
2375       if (walk == NULL) {
2376         GST_INFO_OBJECT (qpad->collect.pad,
2377             "Found no video framerate, using 40ms audio buffers");
2378         qpad->expected_sample_duration_n = 25;
2379         qpad->expected_sample_duration_d = 1;
2380       }
2381
2382       /* Set a prepare_buf_func that ensures this */
2383       qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2384       qpad->raw_audio_adapter = gst_adapter_new ();
2385       qpad->raw_audio_adapter_offset = 0;
2386       qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2387
2388       return TRUE;
2389     }
2390     default:
2391       return TRUE;
2392   }
2393 }
2394
2395 static GstQTPad *
2396 find_best_pad_prefill (GstQTMux * qtmux)
2397 {
2398   GSList *walk;
2399   GstQTPad *best_pad = NULL;
2400
2401   if (qtmux->current_pad &&
2402       (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2403       (qtmux->interleave_bytes == 0
2404           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2405       && (qtmux->interleave_time == 0
2406           || qtmux->current_chunk_duration <= qtmux->interleave_time)
2407       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2408       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2409
2410     if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2411       best_pad = qtmux->current_pad;
2412     }
2413   } else if (qtmux->collect->data->next) {
2414     best_pad = qtmux->current_pad = NULL;
2415   }
2416
2417   if (!best_pad) {
2418     GstClockTime best_time = GST_CLOCK_TIME_NONE;
2419
2420     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2421       GstCollectData *cdata = (GstCollectData *) walk->data;
2422       GstQTPad *qtpad = (GstQTPad *) cdata;
2423       GstClockTime timestamp;
2424
2425       if (qtpad->total_duration >= qtmux->reserved_max_duration)
2426         continue;
2427
2428       timestamp = qtpad->total_duration;
2429
2430       if (best_pad == NULL ||
2431           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2432         best_pad = qtpad;
2433         best_time = timestamp;
2434       }
2435     }
2436   }
2437
2438   return best_pad;
2439 }
2440
2441 static gboolean
2442 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2443 {
2444   GstQTPad *qpad;
2445   GSList *walk;
2446   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2447
2448   /* Update expected sample sizes/durations as needed, this is for raw
2449    * audio where samples are actual audio samples. */
2450   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2451     GstCollectData *cdata = (GstCollectData *) walk->data;
2452     GstQTPad *qpad = (GstQTPad *) cdata;
2453
2454     if (!prefill_update_sample_size (qtmux, qpad))
2455       return FALSE;
2456   }
2457
2458   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2459     /* For the first sample check/update timecode as needed. We do that before
2460      * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2461      * initial buffer directly, not with last_buf */
2462     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2463       GstCollectData *cdata = (GstCollectData *) walk->data;
2464       GstQTPad *qpad = (GstQTPad *) cdata;
2465       GstBuffer *buffer =
2466           gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2467       GstVideoTimeCodeMeta *tc_meta;
2468
2469       if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2470         GstVideoTimeCode *tc = &tc_meta->tc;
2471
2472         qpad->tc_trak = atom_trak_new (qtmux->context);
2473         atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2474
2475         qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2476         atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2477
2478         atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context, tc);
2479
2480         atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2481             qtmux->mdat_size, FALSE, 0);
2482
2483         qpad->tc_pos = qtmux->mdat_size;
2484         qpad->first_tc = gst_video_time_code_copy (tc);
2485         qpad->first_pts = GST_BUFFER_PTS (buffer);
2486
2487         qtmux->current_chunk_offset = -1;
2488         qtmux->current_chunk_size = 0;
2489         qtmux->current_chunk_duration = 0;
2490         qtmux->mdat_size += 4;
2491       }
2492       if (buffer)
2493         gst_buffer_unref (buffer);
2494     }
2495   }
2496
2497   while ((qpad = find_best_pad_prefill (qtmux))) {
2498     GstClockTime timestamp, next_timestamp, duration;
2499     guint nsamples, sample_size;
2500     guint64 chunk_offset;
2501     gint64 scaled_duration;
2502     gint64 pts_offset = 0;
2503     gboolean sync = FALSE;
2504     TrakBufferEntryInfo sample_entry;
2505
2506     sample_size = prefill_get_sample_size (qtmux, qpad);
2507
2508     if (sample_size == -1) {
2509       return FALSE;
2510     }
2511
2512     if (!qpad->samples)
2513       qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2514
2515     timestamp = qpad->total_duration;
2516     next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2517     duration = next_timestamp - timestamp;
2518
2519     if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2520       qpad->first_ts = timestamp;
2521     if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2522       qpad->first_dts = timestamp;
2523
2524     if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2525       qtmux->current_pad = qpad;
2526       if (qtmux->current_chunk_offset == -1)
2527         qtmux->current_chunk_offset = qtmux->mdat_size;
2528       else
2529         qtmux->current_chunk_offset += qtmux->current_chunk_size;
2530       qtmux->current_chunk_size = 0;
2531       qtmux->current_chunk_duration = 0;
2532     }
2533     if (qpad->sample_size)
2534       nsamples = sample_size / qpad->sample_size;
2535     else
2536       nsamples = 1;
2537     qpad->last_dts = timestamp;
2538     scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2539         atom_trak_get_timescale (qpad->trak),
2540         GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2541         atom_trak_get_timescale (qpad->trak), GST_SECOND);
2542
2543     qtmux->current_chunk_size += sample_size;
2544     qtmux->current_chunk_duration += duration;
2545     qpad->total_bytes += sample_size;
2546
2547     chunk_offset = qtmux->current_chunk_offset;
2548
2549     /* I-frame only, no frame reordering */
2550     sync = FALSE;
2551     pts_offset = 0;
2552
2553     if (qtmux->current_chunk_duration > qtmux->longest_chunk
2554         || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2555       qtmux->longest_chunk = qtmux->current_chunk_duration;
2556     }
2557
2558     sample_entry.track_id = qpad->trak->tkhd.track_ID;
2559     sample_entry.nsamples = nsamples;
2560     sample_entry.delta = scaled_duration / nsamples;
2561     sample_entry.size = sample_size / nsamples;
2562     sample_entry.chunk_offset = chunk_offset;
2563     sample_entry.pts_offset = pts_offset;
2564     sample_entry.sync = sync;
2565     sample_entry.do_pts = TRUE;
2566     g_array_append_val (qpad->samples, sample_entry);
2567     atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2568         sample_size / nsamples, chunk_offset, sync, pts_offset);
2569
2570     qpad->total_duration = next_timestamp;
2571     qtmux->mdat_size += sample_size;
2572     qpad->sample_offset += nsamples;
2573   }
2574
2575   return TRUE;
2576 }
2577
2578 static GstFlowReturn
2579 gst_qt_mux_start_file (GstQTMux * qtmux)
2580 {
2581   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2582   GstFlowReturn ret = GST_FLOW_OK;
2583   GstCaps *caps;
2584   GstSegment segment;
2585   gchar s_id[32];
2586   GstClockTime reserved_max_duration;
2587   guint reserved_bytes_per_sec_per_trak;
2588   GSList *walk;
2589
2590   GST_DEBUG_OBJECT (qtmux, "starting file");
2591
2592   GST_OBJECT_LOCK (qtmux);
2593   reserved_max_duration = qtmux->reserved_max_duration;
2594   reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2595   GST_OBJECT_UNLOCK (qtmux);
2596
2597   /* stream-start (FIXME: create id based on input ids) */
2598   g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2599   gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2600
2601   caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2602   /* qtmux has structure with and without variant, remove all but the first */
2603   while (gst_caps_get_size (caps) > 1)
2604     gst_caps_remove_structure (caps, 1);
2605   gst_pad_set_caps (qtmux->srcpad, caps);
2606   gst_caps_unref (caps);
2607
2608   /* Default is 'normal' mode */
2609   qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2610
2611   /* Require a sensible fragment duration when muxing
2612    * using the ISML muxer */
2613   if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2614       qtmux->fragment_duration == 0)
2615     goto invalid_isml;
2616
2617   if (qtmux->fragment_duration > 0) {
2618     if (qtmux->streamable)
2619       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2620     else
2621       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2622   } else if (qtmux->fast_start) {
2623     qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2624   } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2625     if (qtmux->reserved_prefill)
2626       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2627     else
2628       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2629   }
2630
2631   switch (qtmux->mux_mode) {
2632     case GST_QT_MUX_MODE_MOOV_AT_END:
2633     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2634       /* We have to be able to seek to rewrite the mdat header, or any
2635        * moov atom we write will not be visible in the file, because an
2636        * MDAT with 0 as the size covers the rest of the file. A file
2637        * with no moov is not playable, so error out now. */
2638       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2639         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2640             ("Downstream is not seekable - will not be able to create a playable file"),
2641             (NULL));
2642         return GST_FLOW_ERROR;
2643       }
2644       break;
2645     case GST_QT_MUX_MODE_FAST_START:
2646     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2647       break;                    /* Don't need seekability, ignore */
2648     case GST_QT_MUX_MODE_FRAGMENTED:
2649       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2650         GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2651             "streamable=false. Will ignore that and create streamable output "
2652             "instead");
2653         qtmux->streamable = TRUE;
2654         g_object_notify (G_OBJECT (qtmux), "streamable");
2655       }
2656       break;
2657     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2658       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2659         GST_WARNING_OBJECT (qtmux,
2660             "downstream is not seekable, will not be able "
2661             "to trim samples table at the end if less than reserved-duration is "
2662             "recorded");
2663       }
2664       break;
2665   }
2666
2667   /* let downstream know we think in BYTES and expect to do seeking later on */
2668   gst_segment_init (&segment, GST_FORMAT_BYTES);
2669   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2670
2671   GST_OBJECT_LOCK (qtmux);
2672
2673   if (qtmux->timescale == 0) {
2674     guint32 suggested_timescale = 0;
2675     GSList *walk;
2676
2677     /* Calculate a reasonable timescale for the moov:
2678      * If there is video, it is the biggest video track timescale or an even
2679      * multiple of it if it's smaller than 1800.
2680      * Otherwise it is 1800 */
2681     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2682       GstCollectData *cdata = (GstCollectData *) walk->data;
2683       GstQTPad *qpad = (GstQTPad *) cdata;
2684
2685       if (!qpad->trak)
2686         continue;
2687
2688       /* not video */
2689       if (!qpad->trak->mdia.minf.vmhd)
2690         continue;
2691
2692       suggested_timescale =
2693           MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
2694     }
2695
2696     if (suggested_timescale == 0)
2697       suggested_timescale = 1800;
2698
2699     while (suggested_timescale < 1800)
2700       suggested_timescale *= 2;
2701
2702     qtmux->timescale = suggested_timescale;
2703   }
2704
2705   /* initialize our moov recovery file */
2706   if (qtmux->moov_recov_file_path) {
2707     gst_qt_mux_prepare_moov_recovery (qtmux);
2708   }
2709
2710   /* Make sure the first time we update the moov, we'll
2711    * include any tagsetter tags */
2712   qtmux->tags_changed = TRUE;
2713
2714   GST_OBJECT_UNLOCK (qtmux);
2715
2716   /*
2717    * send mdat header if already needed, and mark position for later update.
2718    * We don't send ftyp now if we are on fast start mode, because we can
2719    * better fine tune using the information we gather to create the whole moov
2720    * atom.
2721    */
2722   switch (qtmux->mux_mode) {
2723     case GST_QT_MUX_MODE_MOOV_AT_END:
2724       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2725       if (ret != GST_FLOW_OK)
2726         break;
2727
2728       /* Store this as the mdat offset for later updating
2729        * when we write the moov */
2730       qtmux->mdat_pos = qtmux->header_size;
2731       /* extended atom in case we go over 4GB while writing and need
2732        * the full 64-bit atom */
2733       ret =
2734           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2735           FALSE);
2736       break;
2737     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2738       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2739       if (ret != GST_FLOW_OK)
2740         break;
2741
2742       /* Pad ftyp out to an 8-byte boundary before starting the moov
2743        * ping pong region. It should be well less than 1 disk sector,
2744        * unless there's a bajillion compatible types listed,
2745        * but let's be sure the free atom doesn't cross a sector
2746        * boundary anyway */
2747       if (qtmux->header_size % 8) {
2748         /* Extra 8 bytes for the padding free atom header */
2749         guint padding = (guint) (16 - (qtmux->header_size % 8));
2750         GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2751         ret =
2752             gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2753             FALSE);
2754         if (ret != GST_FLOW_OK)
2755           return ret;
2756       }
2757
2758       /* Store this as the moov offset for later updating.
2759        * We record mdat position below */
2760       qtmux->moov_pos = qtmux->header_size;
2761
2762       /* Set up the initial 'ping' state of the ping-pong buffers */
2763       qtmux->reserved_moov_first_active = TRUE;
2764
2765       gst_qt_mux_configure_moov (qtmux);
2766       gst_qt_mux_setup_metadata (qtmux);
2767       /* Empty free atom to begin, starting on an 8-byte boundary */
2768       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2769       if (ret != GST_FLOW_OK)
2770         return ret;
2771       /* Moov header, not padded yet */
2772       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2773       if (ret != GST_FLOW_OK)
2774         return ret;
2775       /* The moov we just sent contains the 'base' size of the moov, before
2776        * we put in any time-dependent per-trak data. Use that to make
2777        * a good estimate of how much extra to reserve */
2778       /* Calculate how much space to reserve for our MOOV atom.
2779        * We actually reserve twice that, for ping-pong buffers */
2780       qtmux->base_moov_size = qtmux->last_moov_size;
2781       GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2782           qtmux->base_moov_size);
2783       qtmux->reserved_moov_size = qtmux->base_moov_size +
2784           gst_util_uint64_scale (reserved_max_duration,
2785           reserved_bytes_per_sec_per_trak *
2786           atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2787
2788       /* Need space for at least 4 atom headers. More really, but
2789        * this as an absolute minimum */
2790       if (qtmux->reserved_moov_size < 4 * 8)
2791         goto reserved_moov_too_small;
2792
2793       GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2794           2 * qtmux->reserved_moov_size + 16);
2795
2796       GST_OBJECT_LOCK (qtmux);
2797       qtmux->reserved_duration_remaining =
2798           gst_util_uint64_scale (qtmux->reserved_moov_size -
2799           qtmux->base_moov_size, GST_SECOND,
2800           reserved_bytes_per_sec_per_trak *
2801           atom_moov_get_trak_count (qtmux->moov));
2802       GST_OBJECT_UNLOCK (qtmux);
2803
2804       /* Now that we know how much reserved space is targetted,
2805        * output a free atom to fill the extra reserved */
2806       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2807           qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2808       if (ret != GST_FLOW_OK)
2809         return ret;
2810
2811       /* Then a free atom containing 'pong' buffer, with an
2812        * extra 8 bytes to account for the free atom header itself */
2813       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2814           qtmux->reserved_moov_size + 8, FALSE);
2815       if (ret != GST_FLOW_OK)
2816         return ret;
2817
2818       /* extra atoms go after the free/moov(s), before the mdat */
2819       ret =
2820           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2821       if (ret != GST_FLOW_OK)
2822         return ret;
2823
2824       qtmux->mdat_pos = qtmux->header_size;
2825       /* extended atom in case we go over 4GB while writing and need
2826        * the full 64-bit atom */
2827       ret =
2828           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2829           FALSE);
2830       break;
2831     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2832       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2833       if (ret != GST_FLOW_OK)
2834         break;
2835
2836       /* Store this as the moov offset for later updating.
2837        * We record mdat position below */
2838       qtmux->moov_pos = qtmux->header_size;
2839
2840       if (!gst_qt_mux_prefill_samples (qtmux)) {
2841         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2842             ("Unsupported codecs or configuration for prefill mode"), (NULL));
2843
2844         return GST_FLOW_ERROR;
2845       }
2846
2847       gst_qt_mux_update_global_statistics (qtmux);
2848       gst_qt_mux_configure_moov (qtmux);
2849       gst_qt_mux_update_edit_lists (qtmux);
2850       gst_qt_mux_setup_metadata (qtmux);
2851
2852       /* Moov header with pre-filled samples */
2853       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2854       if (ret != GST_FLOW_OK)
2855         return ret;
2856
2857       /* last_moov_size now contains the full size of the moov, moov_pos the
2858        * position. This allows us to rewrite it in the very end as needed */
2859       qtmux->reserved_moov_size =
2860           qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
2861
2862       /* Send an additional free atom at the end so we definitely have space
2863        * to rewrite the moov header at the end and remove the samples that
2864        * were not actually written */
2865       ret =
2866           gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2867           12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
2868       if (ret != GST_FLOW_OK)
2869         return ret;
2870
2871       /* extra atoms go after the free/moov(s), before the mdat */
2872       ret =
2873           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2874       if (ret != GST_FLOW_OK)
2875         return ret;
2876
2877       qtmux->mdat_pos = qtmux->header_size;
2878
2879       /* And now send the mdat header */
2880       ret =
2881           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
2882           qtmux->mdat_size, TRUE, FALSE);
2883
2884       /* chunks position is set relative to the first byte of the
2885        * MDAT atom payload. Set the overall offset into the file */
2886       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
2887
2888       {
2889         GstSegment segment;
2890
2891         gst_segment_init (&segment, GST_FORMAT_BYTES);
2892         segment.start = qtmux->moov_pos;
2893         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2894
2895         ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2896         if (ret != GST_FLOW_OK)
2897           return ret;
2898
2899         segment.start = qtmux->header_size;
2900         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2901       }
2902
2903       qtmux->current_chunk_size = 0;
2904       qtmux->current_chunk_duration = 0;
2905       qtmux->current_chunk_offset = -1;
2906       qtmux->mdat_size = 0;
2907       qtmux->current_pad = NULL;
2908       qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
2909
2910       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2911         GstCollectData *cdata = (GstCollectData *) walk->data;
2912         GstQTPad *qtpad = (GstQTPad *) cdata;
2913
2914         qtpad->total_bytes = 0;
2915         qtpad->total_duration = 0;
2916         qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
2917         qtpad->last_dts = GST_CLOCK_TIME_NONE;
2918         qtpad->sample_offset = 0;
2919       }
2920
2921       break;
2922     case GST_QT_MUX_MODE_FAST_START:
2923       GST_OBJECT_LOCK (qtmux);
2924       qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2925       if (!qtmux->fast_start_file)
2926         goto open_failed;
2927       GST_OBJECT_UNLOCK (qtmux);
2928       /* send a dummy buffer for preroll */
2929       ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2930       break;
2931     case GST_QT_MUX_MODE_FRAGMENTED:
2932     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2933       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2934       if (ret != GST_FLOW_OK)
2935         break;
2936       /* store the moov pos so we can update the duration later
2937        * in non-streamable mode */
2938       qtmux->moov_pos = qtmux->header_size;
2939
2940       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2941           qtmux->fragment_duration);
2942       /* also used as snapshot marker to indicate fragmented file */
2943       qtmux->fragment_sequence = 1;
2944       /* prepare moov and/or tags */
2945       gst_qt_mux_configure_moov (qtmux);
2946       gst_qt_mux_setup_metadata (qtmux);
2947       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2948       if (ret != GST_FLOW_OK)
2949         return ret;
2950       /* extra atoms */
2951       ret =
2952           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2953       if (ret != GST_FLOW_OK)
2954         break;
2955       /* prepare index if not streamable */
2956       if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2957         qtmux->mfra = atom_mfra_new (qtmux->context);
2958       break;
2959   }
2960
2961   return ret;
2962   /* ERRORS */
2963 invalid_isml:
2964   {
2965     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2966         ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2967     return GST_FLOW_ERROR;
2968   }
2969 reserved_moov_too_small:
2970   {
2971     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2972         ("Not enough reserved space for creating headers"), (NULL));
2973     return GST_FLOW_ERROR;
2974   }
2975 open_failed:
2976   {
2977     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2978         (("Could not open temporary file \"%s\""),
2979             qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2980     GST_OBJECT_UNLOCK (qtmux);
2981     return GST_FLOW_ERROR;
2982   }
2983 }
2984
2985 static GstFlowReturn
2986 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2987 {
2988   GstFlowReturn ret = GST_FLOW_OK;
2989   GSList *walk;
2990
2991   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2992     GstCollectData *cdata = (GstCollectData *) walk->data;
2993     GstQTPad *qtpad = (GstQTPad *) cdata;
2994
2995     /* avoid add_buffer complaining if not negotiated
2996      * in which case no buffers either, so skipping */
2997     if (!qtpad->fourcc) {
2998       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2999           GST_PAD_NAME (qtpad->collect.pad));
3000       continue;
3001     }
3002
3003     /* send last buffer; also flushes possibly queued buffers/ts */
3004     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3005         GST_PAD_NAME (qtpad->collect.pad));
3006     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3007     if (ret != GST_FLOW_OK) {
3008       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3009           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3010           gst_flow_get_name (ret));
3011     }
3012   }
3013
3014   return ret;
3015 }
3016
3017 static void
3018 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3019 {
3020   GSList *walk;
3021
3022   /* for setting some subtitles fields */
3023   guint max_width = 0;
3024   guint max_height = 0;
3025
3026   qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3027
3028   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3029     GstCollectData *cdata = (GstCollectData *) walk->data;
3030     GstQTPad *qtpad = (GstQTPad *) cdata;
3031
3032     if (!qtpad->fourcc) {
3033       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3034           GST_PAD_NAME (qtpad->collect.pad));
3035       continue;
3036     }
3037
3038     /* having flushed above, can check for buffers now */
3039     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3040       GstClockTime first_pts_in = qtpad->first_ts;
3041       /* it should be, since we got first_ts by adding adjustment
3042        * to a positive incoming PTS */
3043       if (qtpad->dts_adjustment <= first_pts_in)
3044         first_pts_in -= qtpad->dts_adjustment;
3045       /* determine max stream duration */
3046       if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3047           || qtpad->last_dts > qtmux->last_dts) {
3048         qtmux->last_dts = qtpad->last_dts;
3049       }
3050       if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3051           || first_pts_in < qtmux->first_ts) {
3052         /* we need the original incoming PTS here, as this first_ts
3053          * is used in update_edit_lists to construct the edit list that arrange
3054          * for sync'ed streams.  The first_ts is most likely obtained from
3055          * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3056          * so it makes no difference, though it matters in other cases */
3057         qtmux->first_ts = first_pts_in;
3058       }
3059     }
3060
3061     /* subtitles need to know the video width/height,
3062      * it is stored shifted 16 bits to the left according to the
3063      * spec */
3064     max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3065     max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3066
3067     /* update average bitrate of streams if needed */
3068     {
3069       guint32 avgbitrate = 0;
3070       guint32 maxbitrate = qtpad->max_bitrate;
3071
3072       if (qtpad->avg_bitrate)
3073         avgbitrate = qtpad->avg_bitrate;
3074       else if (qtpad->total_duration > 0)
3075         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3076             8 * GST_SECOND, qtpad->total_duration);
3077
3078       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3079     }
3080   }
3081
3082   /* need to update values on subtitle traks now that we know the
3083    * max width and height */
3084   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3085     GstCollectData *cdata = (GstCollectData *) walk->data;
3086     GstQTPad *qtpad = (GstQTPad *) cdata;
3087
3088     if (!qtpad->fourcc) {
3089       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3090           GST_PAD_NAME (qtpad->collect.pad));
3091       continue;
3092     }
3093
3094     if (qtpad->fourcc == FOURCC_tx3g) {
3095       atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3096     }
3097   }
3098 }
3099
3100 /* Called after gst_qt_mux_update_global_statistics() updates the
3101  * first_ts tracking, to create/set edit lists for delayed streams */
3102 static void
3103 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3104 {
3105   GSList *walk;
3106
3107   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3108       GST_TIME_ARGS (qtmux->first_ts));
3109   /* add/update EDTSs for late streams. configure_moov will have
3110    * set the trak durations above by summing the sample tables,
3111    * here we extend that if needing to insert an empty segment */
3112   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3113     GstCollectData *cdata = (GstCollectData *) walk->data;
3114     GstQTPad *qtpad = (GstQTPad *) cdata;
3115
3116     atom_trak_edts_clear (qtpad->trak);
3117
3118     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3119       guint32 lateness = 0;
3120       guint32 duration = qtpad->trak->tkhd.duration;
3121       gboolean has_gap;
3122
3123       has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3124
3125       if (has_gap) {
3126         GstClockTime diff;
3127
3128         diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3129         lateness = gst_util_uint64_scale_round (diff,
3130             qtmux->timescale, GST_SECOND);
3131
3132         if (lateness > 0) {
3133           GST_DEBUG_OBJECT (qtmux,
3134               "Pad %s is a late stream by %" GST_TIME_FORMAT,
3135               GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3136
3137           atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3138               (guint32) (1 * 65536.0));
3139         }
3140       }
3141
3142       /* Always write an edit list for the whole track. In general this is not
3143        * necessary except for the case of having a gap or DTS adjustment but
3144        * it allows to give the whole track's duration in the usually more
3145        * accurate media timescale
3146        */
3147       {
3148         GstClockTime ctts = 0;
3149         guint32 media_start;
3150
3151         if (qtpad->first_ts > qtpad->first_dts)
3152           ctts = qtpad->first_ts - qtpad->first_dts;
3153
3154         media_start = gst_util_uint64_scale_round (ctts,
3155             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3156
3157         /* atom_trak_set_elst_entry() has a quirk - if the edit list
3158          * is empty because there's no gap added above, this call
3159          * will not replace index 1, it will create the entry at index 0.
3160          * Luckily, that's exactly what we want here */
3161         atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3162             (guint32) (1 * 65536.0));
3163       }
3164
3165       /* need to add the empty time to the trak duration */
3166       duration += lateness;
3167       qtpad->trak->tkhd.duration = duration;
3168       if (qtpad->tc_trak) {
3169         qtpad->tc_trak->tkhd.duration = duration;
3170         qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3171       }
3172
3173       /* And possibly grow the moov duration */
3174       if (duration > qtmux->moov->mvhd.time_info.duration) {
3175         qtmux->moov->mvhd.time_info.duration = duration;
3176         qtmux->moov->mvex.mehd.fragment_duration = duration;
3177       }
3178     }
3179   }
3180 }
3181
3182 static GstFlowReturn
3183 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3184 {
3185   GstSegment segment;
3186   GstBuffer *buf;
3187   GstMapInfo map;
3188   guint64 offset = qtpad->tc_pos;
3189   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3190
3191   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3192     return GST_FLOW_OK;
3193
3194   g_assert (qtpad->tc_pos != -1);
3195
3196   gst_segment_init (&segment, GST_FORMAT_BYTES);
3197   segment.start = offset;
3198   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3199
3200   buf = gst_buffer_new_and_alloc (4);
3201   gst_buffer_map (buf, &map, GST_MAP_WRITE);
3202
3203   GST_WRITE_UINT32_BE (map.data,
3204       gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3205   gst_buffer_unmap (buf, &map);
3206
3207   /* Reset this value, so the timecode won't be re-rewritten */
3208   qtpad->tc_pos = -1;
3209
3210   return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3211 }
3212
3213 static GstFlowReturn
3214 gst_qt_mux_stop_file (GstQTMux * qtmux)
3215 {
3216   gboolean ret = GST_FLOW_OK;
3217   guint64 offset = 0, size = 0;
3218   gboolean large_file;
3219   GSList *walk;
3220
3221   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3222
3223   /* pushing last buffers for each pad */
3224   if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3225     return ret;
3226
3227   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3228     /* Streamable mode; no need to write duration or MFRA */
3229     GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3230     return GST_FLOW_OK;
3231   }
3232
3233   gst_qt_mux_update_global_statistics (qtmux);
3234   for (walk = qtmux->collect->data; walk; walk = walk->next) {
3235     GstQTPad *qtpad = (GstQTPad *) walk->data;
3236
3237     if (qtpad->tc_pos != -1) {
3238       /* File is being stopped and timecode hasn't been updated. Update it now
3239        * with whatever we have */
3240       ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3241       if (ret != GST_FLOW_OK)
3242         return ret;
3243     }
3244   }
3245
3246   switch (qtmux->mux_mode) {
3247     case GST_QT_MUX_MODE_FRAGMENTED:{
3248       GstSegment segment;
3249       guint8 *data = NULL;
3250       GstBuffer *buf;
3251
3252       size = offset = 0;
3253       GST_DEBUG_OBJECT (qtmux, "adding mfra");
3254       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3255         goto serialize_error;
3256       buf = _gst_buffer_new_take_data (data, offset);
3257       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3258       if (ret != GST_FLOW_OK)
3259         return ret;
3260
3261       /* only mvex duration is updated,
3262        * mvhd should be consistent with empty moov
3263        * (but TODO maybe some clients do not handle that well ?) */
3264       qtmux->moov->mvex.mehd.fragment_duration =
3265           gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3266       GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3267           GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3268       /* seek and rewrite the header */
3269       gst_segment_init (&segment, GST_FORMAT_BYTES);
3270       segment.start = qtmux->moov_pos;
3271       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3272       /* no need to seek back */
3273       return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3274     }
3275     case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3276       ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3277       if (G_UNLIKELY (ret != GST_FLOW_OK))
3278         return ret;
3279       /* Finalise by writing the final size into the mdat. Up until now
3280        * it's been 0, which means 'rest of the file'
3281        * No need to seek back after this, we won't write any more */
3282       return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3283           qtmux->mdat_size, NULL, TRUE);
3284     }
3285     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3286       GSList *walk;
3287       guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3288
3289       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3290         GstCollectData *cdata = (GstCollectData *) walk->data;
3291         GstQTPad *qpad = (GstQTPad *) cdata;
3292         const TrakBufferEntryInfo *sample_entry;
3293         guint64 block_idx;
3294         AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3295
3296         /* Get the block index of the last sample we wrote, not of the next
3297          * sample we would write */
3298         block_idx = prefill_get_block_index (qtmux, qpad);
3299         g_assert (block_idx > 0);
3300         block_idx--;
3301
3302         sample_entry =
3303             &g_array_index (qpad->samples, TrakBufferEntryInfo, block_idx);
3304
3305         /* stts */
3306         {
3307           STTSEntry *entry;
3308           guint64 nsamples = 0;
3309           gint i, n;
3310
3311           n = atom_array_get_len (&stbl->stts.entries);
3312           for (i = 0; i < n; i++) {
3313             entry = &atom_array_index (&stbl->stts.entries, i);
3314             if (nsamples + entry->sample_count >= qpad->sample_offset) {
3315               entry->sample_count = qpad->sample_offset - nsamples;
3316               stbl->stts.entries.len = i + 1;
3317               break;
3318             }
3319             nsamples += entry->sample_count;
3320           }
3321           g_assert (i < n);
3322         }
3323
3324         /* stsz */
3325         {
3326           g_assert (stbl->stsz.entries.len == 0);
3327           stbl->stsz.table_size = qpad->sample_offset;
3328         }
3329
3330         /* stco/stsc */
3331         {
3332           gint i, n;
3333           guint64 nsamples = 0;
3334           gint chunk_index = 0;
3335
3336           n = stbl->stco64.entries.len;
3337           for (i = 0; i < n; i++) {
3338             guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3339
3340             if (*entry == sample_entry->chunk_offset) {
3341               stbl->stco64.entries.len = i + 1;
3342               chunk_index = i + 1;
3343               break;
3344             }
3345           }
3346           g_assert (i < n);
3347           g_assert (chunk_index > 0);
3348
3349           n = stbl->stsc.entries.len;
3350           for (i = 0; i < n; i++) {
3351             STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3352
3353             if (entry->first_chunk >= chunk_index)
3354               break;
3355
3356             if (i > 0) {
3357               nsamples +=
3358                   (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3359                       i -
3360                       1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3361                   i - 1).samples_per_chunk;
3362             }
3363           }
3364           g_assert (i <= n);
3365
3366           if (i > 0) {
3367             STSCEntry *prev_entry =
3368                 &atom_array_index (&stbl->stsc.entries, i - 1);
3369             nsamples +=
3370                 (chunk_index -
3371                 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3372             if (qpad->sample_offset - nsamples > 0) {
3373               stbl->stsc.entries.len = i;
3374               atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3375                   qpad->sample_offset - nsamples);
3376             } else {
3377               stbl->stsc.entries.len = i;
3378               stbl->stco64.entries.len--;
3379             }
3380           } else {
3381             /* Everything in a single chunk */
3382             stbl->stsc.entries.len = 0;
3383             atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3384                 qpad->sample_offset);
3385           }
3386         }
3387
3388         {
3389           GList *walk2;
3390
3391           for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3392             AtomTREX *trex = walk2->data;
3393
3394             if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3395               trex->track_ID = next_track_id;
3396               break;
3397             }
3398           }
3399
3400           qpad->trak->tkhd.track_ID = next_track_id++;
3401         }
3402       }
3403       qtmux->moov->mvhd.next_track_id = next_track_id;
3404
3405       gst_qt_mux_update_global_statistics (qtmux);
3406       gst_qt_mux_configure_moov (qtmux);
3407
3408       gst_qt_mux_update_edit_lists (qtmux);
3409
3410       /* Check if any gap edit lists were added. We don't have any space
3411        * reserved for this in the moov and the pre-finalized moov would have
3412        * broken A/V synchronization. Error out here now
3413        */
3414       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3415         GstCollectData *cdata = (GstCollectData *) walk->data;
3416         GstQTPad *qpad = (GstQTPad *) cdata;
3417
3418         if (qpad->trak->edts
3419             && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3420           GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3421               ("Can't support gaps in prefill mode"));
3422
3423           return GST_FLOW_ERROR;
3424         }
3425       }
3426
3427       gst_qt_mux_setup_metadata (qtmux);
3428       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3429
3430       {
3431         GstSegment segment;
3432
3433         gst_segment_init (&segment, GST_FORMAT_BYTES);
3434         segment.start = qtmux->moov_pos;
3435         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3436
3437         ret =
3438             gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3439             FALSE);
3440         if (ret != GST_FLOW_OK)
3441           return ret;
3442
3443         if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3444           ret =
3445               gst_qt_mux_send_free_atom (qtmux, NULL,
3446               qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3447         }
3448
3449         if (ret != GST_FLOW_OK)
3450           return ret;
3451       }
3452
3453       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3454           qtmux->mdat_size, NULL, FALSE);
3455       return ret;
3456     }
3457     default:
3458       break;
3459   }
3460
3461   /* Moov-at-end or fast-start mode from here down */
3462   gst_qt_mux_configure_moov (qtmux);
3463
3464   gst_qt_mux_update_edit_lists (qtmux);
3465
3466   /* tags into file metadata */
3467   gst_qt_mux_setup_metadata (qtmux);
3468
3469   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3470
3471   switch (qtmux->mux_mode) {
3472     case GST_QT_MUX_MODE_FAST_START:{
3473       /* if faststart, update the offset of the atoms in the movie with the offset
3474        * that the movie headers before mdat will cause.
3475        * Also, send the ftyp */
3476       offset = size = 0;
3477
3478       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3479       if (ret != GST_FLOW_OK) {
3480         goto ftyp_error;
3481       }
3482       /* copy into NULL to obtain size */
3483       if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3484         goto serialize_error;
3485       GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3486           offset);
3487       offset += qtmux->header_size + (large_file ? 16 : 8);
3488
3489       /* sum up with the extra atoms size */
3490       ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3491       if (ret != GST_FLOW_OK)
3492         return ret;
3493       break;
3494     }
3495     default:
3496       offset = qtmux->header_size;
3497       break;
3498   }
3499
3500   /* Now that we know the size of moov + extra atoms, we can adjust
3501    * the chunk offsets stored into the moov */
3502   atom_moov_chunks_set_offset (qtmux->moov, offset);
3503
3504   /* write out moov and extra atoms */
3505   /* note: as of this point, we no longer care about tracking written data size,
3506    * since there is no more use for it anyway */
3507   ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3508   if (ret != GST_FLOW_OK)
3509     return ret;
3510
3511   /* extra atoms */
3512   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3513   if (ret != GST_FLOW_OK)
3514     return ret;
3515
3516   switch (qtmux->mux_mode) {
3517     case GST_QT_MUX_MODE_MOOV_AT_END:
3518     {
3519       /* mdat needs update iff not using faststart */
3520       GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3521       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3522           qtmux->mdat_size, NULL, FALSE);
3523       /* note; no seeking back to the end of file is done,
3524        * since we no longer write anything anyway */
3525       break;
3526     }
3527     case GST_QT_MUX_MODE_FAST_START:
3528     {
3529       /* send mdat atom and move buffered data into it */
3530       /* mdat_size = accumulated (buffered data) */
3531       ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3532           large_file, FALSE);
3533       if (ret != GST_FLOW_OK)
3534         return ret;
3535       ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3536       if (ret != GST_FLOW_OK)
3537         return ret;
3538       break;
3539     }
3540     default:
3541       g_assert_not_reached ();
3542   }
3543
3544   return ret;
3545
3546   /* ERRORS */
3547 serialize_error:
3548   {
3549     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3550         ("Failed to serialize moov"));
3551     return GST_FLOW_ERROR;
3552   }
3553 ftyp_error:
3554   {
3555     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3556     return GST_FLOW_ERROR;
3557   }
3558 }
3559
3560 static GstFlowReturn
3561 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3562     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3563     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3564 {
3565   GstFlowReturn ret = GST_FLOW_OK;
3566
3567   /* setup if needed */
3568   if (G_UNLIKELY (!pad->traf || force))
3569     goto init;
3570
3571 flush:
3572   /* flush pad fragment if threshold reached,
3573    * or at new keyframe if we should be minding those in the first place */
3574   if (G_UNLIKELY (force || (sync && pad->sync) ||
3575           pad->fragment_duration < (gint64) delta)) {
3576     AtomMOOF *moof;
3577     guint64 size = 0, offset = 0;
3578     guint8 *data = NULL;
3579     GstBuffer *buffer;
3580     guint i, total_size;
3581
3582     /* now we know where moof ends up, update offset in tfra */
3583     if (pad->tfra)
3584       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3585
3586     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3587     /* takes ownership */
3588     atom_moof_add_traf (moof, pad->traf);
3589     pad->traf = NULL;
3590     atom_moof_copy_data (moof, &data, &size, &offset);
3591     buffer = _gst_buffer_new_take_data (data, offset);
3592     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3593         gst_buffer_get_size (buffer));
3594     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3595
3596     /* and actual data */
3597     total_size = 0;
3598     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3599       total_size +=
3600           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3601     }
3602
3603     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3604         atom_array_get_len (&pad->fragment_buffers), total_size);
3605     if (ret == GST_FLOW_OK)
3606       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3607           FALSE, FALSE);
3608     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3609       if (G_LIKELY (ret == GST_FLOW_OK))
3610         ret = gst_qt_mux_send_buffer (qtmux,
3611             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3612             FALSE);
3613       else
3614         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3615     }
3616
3617     atom_array_clear (&pad->fragment_buffers);
3618     atom_moof_free (moof);
3619     qtmux->fragment_sequence++;
3620     force = FALSE;
3621   }
3622
3623 init:
3624   if (G_UNLIKELY (!pad->traf)) {
3625     GST_LOG_OBJECT (qtmux, "setting up new fragment");
3626     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3627     atom_array_init (&pad->fragment_buffers, 512);
3628     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3629         atom_trak_get_timescale (pad->trak), 1000);
3630
3631     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3632       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3633       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3634     }
3635     atom_traf_set_base_decode_time (pad->traf, dts);
3636   }
3637
3638   /* add buffer and metadata */
3639   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3640       pad->sync && sync);
3641   atom_array_append (&pad->fragment_buffers, buf, 256);
3642   pad->fragment_duration -= delta;
3643
3644   if (pad->tfra) {
3645     guint32 sn = atom_traf_get_sample_num (pad->traf);
3646
3647     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3648       atom_tfra_add_entry (pad->tfra, dts, sn);
3649   }
3650
3651   if (G_UNLIKELY (force))
3652     goto flush;
3653
3654   return ret;
3655 }
3656
3657 /* Here's the clever bit of robust recording: Updating the moov
3658  * header is done using a ping-pong scheme inside 2 blocks of size
3659  * 'reserved_moov_size' at the start of the file, in such a way that the
3660  * file on-disk is always valid if interrupted.
3661  * Inside the reserved space, we have 2 pairs of free + moov atoms
3662  * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3663  * at offset "reserved_moov_size".
3664  *
3665  * 1. Free-A has 0 size payload, moov-A immediately after is
3666  *    active/current, and is padded with an internal Free atom to
3667  *    end at reserved_space/2. Free-B is at reserved_space/2, sized
3668  *    to cover the remaining free space (including moov-B).
3669  * 2. We write moov-B (which is invisible inside free-B), and pad it to
3670  *    end at the end of free space. Then, we update free-A to size
3671  *    reserved_space/2 + sizeof(free-B), which hides moov-A and the
3672  *    free-B header, and makes moov-B active.
3673  * 3. Rewrite moov-A inside free-A, with padding out to free-B.
3674  *    Change the size of free-A to make moov-A active again.
3675  * 4. Rinse and repeat.
3676  *
3677  */
3678 static GstFlowReturn
3679 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
3680 {
3681   GstSegment segment;
3682   GstFlowReturn ret;
3683   guint64 freeA_offset;
3684   guint32 new_freeA_size;
3685   guint64 new_moov_offset;
3686
3687   /* Update moov info, then seek and rewrite the MOOV atom */
3688   gst_qt_mux_update_global_statistics (qtmux);
3689   gst_qt_mux_configure_moov (qtmux);
3690
3691   gst_qt_mux_update_edit_lists (qtmux);
3692
3693   /* tags into file metadata */
3694   gst_qt_mux_setup_metadata (qtmux);
3695
3696   /* chunks position is set relative to the first byte of the
3697    * MDAT atom payload. Set the overall offset into the file */
3698   atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3699
3700   /* Calculate which moov to rewrite. qtmux->moov_pos points to
3701    * the start of the free-A header */
3702   freeA_offset = qtmux->moov_pos;
3703   if (qtmux->reserved_moov_first_active) {
3704     GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
3705     /* After this, freeA will include itself, moovA, plus the freeB
3706      * header */
3707     new_freeA_size = qtmux->reserved_moov_size + 16;
3708   } else {
3709     GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
3710     new_freeA_size = 8;
3711   }
3712   /* the moov we update is after free-A, calculate its offset */
3713   new_moov_offset = freeA_offset + new_freeA_size;
3714
3715   /* Swap ping-pong cadence marker */
3716   qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
3717
3718   /* seek and rewrite the MOOV atom */
3719   gst_segment_init (&segment, GST_FORMAT_BYTES);
3720   segment.start = new_moov_offset;
3721   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3722
3723   ret =
3724       gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3725       TRUE);
3726   if (ret != GST_FLOW_OK)
3727     return ret;
3728
3729   /* Update the estimated recording space remaining, based on amount used so
3730    * far and duration muxed so far */
3731   if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
3732     GstClockTime remain;
3733     GstClockTime time_muxed = qtmux->last_dts;
3734
3735     remain =
3736         gst_util_uint64_scale (qtmux->reserved_moov_size -
3737         qtmux->last_moov_size, time_muxed,
3738         qtmux->last_moov_size - qtmux->base_moov_size);
3739     /* Always under-estimate slightly, so users
3740      * have time to stop muxing before we run out */
3741     if (remain < GST_SECOND / 2)
3742       remain = 0;
3743     else
3744       remain -= GST_SECOND / 2;
3745
3746     GST_INFO_OBJECT (qtmux,
3747         "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
3748         ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
3749         qtmux->reserved_moov_size, qtmux->last_moov_size,
3750         GST_TIME_ARGS (qtmux->last_dts),
3751         qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
3752
3753     GST_OBJECT_LOCK (qtmux);
3754     qtmux->reserved_duration_remaining = remain;
3755     qtmux->muxed_since_last_update = 0;
3756     GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
3757         G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
3758     GST_OBJECT_UNLOCK (qtmux);
3759   }
3760
3761
3762   /* Now update the moov-A size. Don't pass offset, since we don't need
3763    * send_free_atom() to seek for us - all our callers seek back to
3764    * where they need after this, or they don't need it */
3765   gst_segment_init (&segment, GST_FORMAT_BYTES);
3766   segment.start = freeA_offset;
3767   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3768
3769   ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3770
3771   return ret;
3772 }
3773
3774 static GstFlowReturn
3775 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3776 {
3777   GstSegment segment;
3778   GstFlowReturn flow_ret;
3779
3780   guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3781
3782   GST_OBJECT_LOCK (qtmux);
3783   if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3784     GST_OBJECT_UNLOCK (qtmux);
3785     return GST_FLOW_OK;
3786   }
3787
3788   /* Update if position is > the threshold or there's been no update yet */
3789   if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3790       (position <= qtmux->last_moov_update ||
3791           (position - qtmux->last_moov_update) <
3792           qtmux->reserved_moov_update_period)) {
3793     /* Update the offset of how much we've muxed, so the
3794      * report of remaining space keeps counting down */
3795     if (position > qtmux->last_moov_update &&
3796         position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3797       GST_LOG_OBJECT (qtmux,
3798           "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3799           qtmux->muxed_since_last_update);
3800       qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3801     }
3802     GST_OBJECT_UNLOCK (qtmux);
3803     return GST_FLOW_OK;         /* No update needed yet */
3804   }
3805
3806   qtmux->last_moov_update = position;
3807   GST_OBJECT_UNLOCK (qtmux);
3808
3809   GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3810       " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3811       GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3812
3813   flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3814   if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3815     return flow_ret;
3816
3817   /* Seek back to previous position */
3818   gst_segment_init (&segment, GST_FORMAT_BYTES);
3819   segment.start = mdat_offset;
3820   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3821
3822   return flow_ret;
3823 }
3824
3825 static GstFlowReturn
3826 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3827     GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3828     gint64 last_dts, gint64 scaled_duration, guint sample_size,
3829     guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3830 {
3831   GstFlowReturn ret = GST_FLOW_OK;
3832
3833   /* note that a new chunk is started each time (not fancy but works) */
3834   if (qtmux->moov_recov_file) {
3835     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3836             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3837             do_pts, pts_offset)) {
3838       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3839           "recovery file, disabling recovery");
3840       fclose (qtmux->moov_recov_file);
3841       qtmux->moov_recov_file = NULL;
3842     }
3843   }
3844
3845   switch (qtmux->mux_mode) {
3846     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3847       const TrakBufferEntryInfo *sample_entry;
3848       guint64 block_idx = prefill_get_block_index (qtmux, pad);
3849
3850       if (block_idx >= pad->samples->len) {
3851         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3852             ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
3853                 block_idx, pad->samples->len));
3854         gst_buffer_unref (buffer);
3855         return GST_FLOW_ERROR;
3856       }
3857
3858       /* Check if all values are as expected */
3859       sample_entry =
3860           &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
3861
3862       /* Allow +/- 1 difference for the scaled_duration to allow
3863        * for some rounding errors
3864        */
3865       if (sample_entry->nsamples != nsamples
3866           || ABSDIFF (sample_entry->delta, scaled_duration) > 1
3867           || sample_entry->size != sample_size
3868           || sample_entry->chunk_offset != chunk_offset
3869           || sample_entry->pts_offset != pts_offset
3870           || sample_entry->sync != sync) {
3871         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3872             ("Unexpected values in sample %" G_GUINT64_FORMAT,
3873                 pad->sample_offset + 1));
3874         gst_buffer_unref (buffer);
3875         return GST_FLOW_ERROR;
3876       }
3877
3878       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3879       break;
3880     }
3881     case GST_QT_MUX_MODE_MOOV_AT_END:
3882     case GST_QT_MUX_MODE_FAST_START:
3883     case GST_QT_MUX_MODE_ROBUST_RECORDING:
3884       atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3885           sample_size, chunk_offset, sync, pts_offset);
3886       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3887       /* Check if it's time to re-write the headers in robust-recording mode */
3888       if (ret == GST_FLOW_OK
3889           && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3890         ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3891       break;
3892     case GST_QT_MUX_MODE_FRAGMENTED:
3893     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3894       /* ensure that always sync samples are marked as such */
3895       ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3896           is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3897           sample_size, !pad->sync || sync, pts_offset);
3898       break;
3899   }
3900
3901   return ret;
3902 }
3903
3904 static void
3905 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
3906     guint buffer_size, GstClockTime duration)
3907 {
3908   /* not that much happens here,
3909    * but updating any of this very likely needs to happen all in sync,
3910    * unless there is a very good reason not to */
3911
3912   /* for computing the avg bitrate */
3913   pad->total_bytes += buffer_size;
3914   pad->total_duration += duration;
3915   /* for keeping track of where we are in chunk;
3916    * ensures that data really is located as recorded in atoms */
3917   qtmux->current_chunk_size += buffer_size;
3918   qtmux->current_chunk_duration += duration;
3919 }
3920
3921 static GstFlowReturn
3922 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
3923     GstBuffer * buf, GstFlowReturn ret)
3924 {
3925   GstVideoTimeCodeMeta *tc_meta;
3926   GstVideoTimeCode *tc;
3927   GstBuffer *tc_buf;
3928   gsize szret;
3929   guint32 frames_since_daily_jam;
3930   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3931
3932   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3933     return ret;
3934
3935   if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
3936     return ret;
3937
3938   tc_meta = gst_buffer_get_video_time_code_meta (buf);
3939   if (!tc_meta)
3940     return ret;
3941
3942   tc = &tc_meta->tc;
3943
3944   /* This means we never got a timecode before */
3945   if (pad->first_tc == NULL) {
3946 #ifndef GST_DISABLE_GST_DEBUG
3947     gchar *tc_str = gst_video_time_code_to_string (tc);
3948     GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
3949     g_free (tc_str);
3950 #endif
3951     g_assert (pad->tc_trak == NULL);
3952     pad->first_tc = gst_video_time_code_copy (tc);
3953     /* If frames are out of order, the frame we're currently getting might
3954      * not be the first one. Just write a 0 timecode for now and wait
3955      * until we receive a timecode that's lower than the current one */
3956     if (pad->is_out_of_order) {
3957       pad->first_pts = GST_BUFFER_PTS (buf);
3958       frames_since_daily_jam = 0;
3959       /* Position to rewrite */
3960       pad->tc_pos = qtmux->mdat_size;
3961     } else {
3962       frames_since_daily_jam =
3963           gst_video_time_code_frames_since_daily_jam (pad->first_tc);
3964       frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3965     }
3966     /* Write the timecode trak now */
3967     pad->tc_trak = atom_trak_new (qtmux->context);
3968     atom_moov_add_trak (qtmux->moov, pad->tc_trak);
3969
3970     pad->trak->tref = atom_tref_new (FOURCC_tmcd);
3971     atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
3972
3973     atom_trak_set_timecode_type (pad->tc_trak, qtmux->context, pad->first_tc);
3974
3975     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3976     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3977     g_assert (szret == 4);
3978
3979     atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
3980     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3981
3982     /* Need to reset the current chunk (of the previous pad) here because
3983      * some other data was written now above, and the pad has to start a
3984      * new chunk now */
3985     qtmux->current_chunk_offset = -1;
3986     qtmux->current_chunk_size = 0;
3987     qtmux->current_chunk_duration = 0;
3988   } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
3989     frames_since_daily_jam =
3990         gst_video_time_code_frames_since_daily_jam (pad->first_tc);
3991     frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3992
3993     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3994     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3995     g_assert (szret == 4);
3996
3997     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3998     pad->tc_pos = -1;
3999
4000     qtmux->current_chunk_offset = -1;
4001     qtmux->current_chunk_size = 0;
4002     qtmux->current_chunk_duration = 0;
4003   } else if (pad->is_out_of_order) {
4004     /* Check for a lower timecode than the one stored */
4005     g_assert (pad->tc_trak != NULL);
4006     if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4007       if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4008         gst_video_time_code_free (pad->first_tc);
4009         pad->first_tc = gst_video_time_code_copy (tc);
4010       }
4011     } else {
4012       guint64 bk_size = qtmux->mdat_size;
4013       GstSegment segment;
4014       /* If this frame's DTS is after the first PTS received, it means
4015        * we've already received the first frame to be presented. Otherwise
4016        * the decoder would need to go back in time */
4017       gst_qt_mux_update_timecode (qtmux, pad);
4018
4019       /* Reset writing position */
4020       gst_segment_init (&segment, GST_FORMAT_BYTES);
4021       segment.start = bk_size;
4022       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4023     }
4024   }
4025
4026   return ret;
4027 }
4028
4029 /*
4030  * Here we push the buffer and update the tables in the track atoms
4031  */
4032 static GstFlowReturn
4033 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4034 {
4035   GstBuffer *last_buf = NULL;
4036   GstClockTime duration;
4037   guint nsamples, sample_size;
4038   guint64 chunk_offset;
4039   gint64 last_dts, scaled_duration;
4040   gint64 pts_offset = 0;
4041   gboolean sync = FALSE;
4042   GstFlowReturn ret = GST_FLOW_OK;
4043   guint buffer_size;
4044
4045   if (!pad->fourcc)
4046     goto not_negotiated;
4047
4048   /* if this pad has a prepare function, call it */
4049   if (pad->prepare_buf_func != NULL) {
4050     GstBuffer *new_buf;
4051
4052     new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4053     if (buf && !new_buf)
4054       return GST_FLOW_OK;
4055     buf = new_buf;
4056   }
4057
4058   ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4059   if (ret != GST_FLOW_OK) {
4060     if (buf)
4061       gst_buffer_unref (buf);
4062     return ret;
4063   }
4064
4065   last_buf = pad->last_buf;
4066   pad->last_buf = buf;
4067
4068   if (last_buf == NULL) {
4069 #ifndef GST_DISABLE_GST_DEBUG
4070     if (buf == NULL) {
4071       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4072           "received NULL buffer, doing nothing",
4073           GST_PAD_NAME (pad->collect.pad));
4074     } else {
4075       GST_LOG_OBJECT (qtmux,
4076           "Pad %s has no previous buffer stored, storing now",
4077           GST_PAD_NAME (pad->collect.pad));
4078     }
4079 #endif
4080     goto exit;
4081   }
4082
4083   if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4084     goto no_pts;
4085
4086   /* if this is the first buffer, store the timestamp */
4087   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4088     if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4089       pad->first_ts = GST_BUFFER_PTS (last_buf);
4090     } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4091       pad->first_ts = GST_BUFFER_DTS (last_buf);
4092     }
4093
4094     if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4095       pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4096     } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4097       pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4098     }
4099
4100     if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4101       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4102     } else {
4103       GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4104           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4105       pad->first_ts = pad->first_dts = 0;
4106     }
4107     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4108         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4109         GST_TIME_ARGS (pad->first_ts));
4110   }
4111
4112   if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4113       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4114       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4115     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4116         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4117         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4118     pad->last_buf = buf = gst_buffer_make_writable (buf);
4119     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4120   }
4121
4122   buffer_size = gst_buffer_get_size (last_buf);
4123
4124   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4125     guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4126     guint fill_size = required_buffer_size - buffer_size;
4127     GstMemory *mem;
4128     GstMapInfo map;
4129
4130     if (required_buffer_size < buffer_size) {
4131       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4132           ("Sample size %u bigger than expected maximum %u", buffer_size,
4133               required_buffer_size));
4134       goto bail;
4135     }
4136
4137     if (fill_size > 0) {
4138       GST_DEBUG_OBJECT (qtmux,
4139           "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4140           required_buffer_size);
4141       mem = gst_allocator_alloc (NULL, fill_size, NULL);
4142       gst_memory_map (mem, &map, GST_MAP_WRITE);
4143       memset (map.data, 0, map.size);
4144       gst_memory_unmap (mem, &map);
4145       last_buf = gst_buffer_make_writable (last_buf);
4146       gst_buffer_append_memory (last_buf, mem);
4147       buffer_size = required_buffer_size;
4148     }
4149   }
4150
4151   /* duration actually means time delta between samples, so we calculate
4152    * the duration based on the difference in DTS or PTS, falling back
4153    * to DURATION if the other two don't exist, such as with the last
4154    * sample before EOS. Or use 0 if nothing else is available */
4155   if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4156     duration = GST_BUFFER_DURATION (last_buf);
4157   else
4158     duration = 0;
4159   if (!pad->sparse) {
4160     if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4161         && GST_BUFFER_DTS_IS_VALID (last_buf))
4162       duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4163     else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4164         && GST_BUFFER_PTS_IS_VALID (last_buf))
4165       duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4166   }
4167
4168   if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4169     GST_DEBUG_OBJECT (qtmux,
4170         "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4171         ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4172         GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4173         qtmux->current_chunk_size,
4174         GST_TIME_ARGS (qtmux->current_chunk_duration));
4175     qtmux->current_pad = pad;
4176     if (qtmux->current_chunk_offset == -1)
4177       qtmux->current_chunk_offset = qtmux->mdat_size;
4178     else
4179       qtmux->current_chunk_offset += qtmux->current_chunk_size;
4180     qtmux->current_chunk_size = 0;
4181     qtmux->current_chunk_duration = 0;
4182   }
4183
4184   last_dts = gst_util_uint64_scale_round (pad->last_dts,
4185       atom_trak_get_timescale (pad->trak), GST_SECOND);
4186
4187   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4188   if (pad->sample_size && !qtmux->fragment_sequence) {
4189     GstClockTime expected_timestamp;
4190
4191     /* Constant size packets: usually raw audio (with many samples per
4192        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4193      */
4194     sample_size = pad->sample_size;
4195     if (buffer_size % sample_size != 0)
4196       goto fragmented_sample;
4197
4198     /* note: qt raw audio storage warps it implicitly into a timewise
4199      * perfect stream, discarding buffer times.
4200      * If the difference between the current PTS and the expected one
4201      * becomes too big, we error out: there was a gap and we have no way to
4202      * represent that, causing A/V sync to be off */
4203     expected_timestamp =
4204         gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4205         atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4206     if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4207             expected_timestamp) > qtmux->max_raw_audio_drift)
4208       goto raw_audio_timestamp_drift;
4209
4210     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4211       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4212           atom_trak_get_timescale (pad->trak), GST_SECOND);
4213       duration = GST_BUFFER_DURATION (last_buf);
4214     } else {
4215       nsamples = buffer_size / sample_size;
4216       duration =
4217           gst_util_uint64_scale_round (nsamples, GST_SECOND,
4218           atom_trak_get_timescale (pad->trak));
4219     }
4220
4221     /* timescale = samplerate */
4222     scaled_duration = 1;
4223     pad->last_dts =
4224         pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4225         nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4226   } else {
4227     nsamples = 1;
4228     sample_size = buffer_size;
4229     if ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4230         || GST_BUFFER_DTS_IS_VALID (last_buf)) {
4231       gint64 scaled_dts;
4232       if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4233         pad->last_dts = GST_BUFFER_DTS (buf);
4234       } else {
4235         pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4236       }
4237       if ((gint64) (pad->last_dts) < 0) {
4238         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4239             atom_trak_get_timescale (pad->trak), GST_SECOND);
4240       } else {
4241         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4242             atom_trak_get_timescale (pad->trak), GST_SECOND);
4243       }
4244       scaled_duration = scaled_dts - last_dts;
4245       last_dts = scaled_dts;
4246     } else {
4247       /* first convert intended timestamp (in GstClockTime resolution) to
4248        * trak timescale, then derive delta;
4249        * this ensures sums of (scale)delta add up to converted timestamp,
4250        * which only deviates at most 1/scale from timestamp itself */
4251       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4252           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4253       pad->last_dts += duration;
4254     }
4255   }
4256
4257   gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4258
4259   chunk_offset = qtmux->current_chunk_offset;
4260
4261   GST_LOG_OBJECT (qtmux,
4262       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4263       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4264   GST_LOG_OBJECT (qtmux,
4265       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4266       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4267       nsamples, scaled_duration, sample_size, chunk_offset);
4268
4269   /* might be a sync sample */
4270   if (pad->sync &&
4271       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4272     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4273         GST_PAD_NAME (pad->collect.pad));
4274     sync = TRUE;
4275   }
4276
4277   if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4278     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4279         atom_trak_get_timescale (pad->trak), GST_SECOND);
4280     pts_offset =
4281         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4282             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4283   } else {
4284     pts_offset = 0;
4285     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4286         atom_trak_get_timescale (pad->trak), GST_SECOND);
4287   }
4288   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4289       " timebase_dts: %d pts_offset: %d",
4290       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4291       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4292       (int) (last_dts), (int) (pts_offset));
4293
4294   if (GST_CLOCK_TIME_IS_VALID (duration)
4295       && (qtmux->current_chunk_duration > qtmux->longest_chunk
4296           || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4297     GST_DEBUG_OBJECT (qtmux,
4298         "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4299         GST_TIME_ARGS (qtmux->current_chunk_duration),
4300         GST_PAD_NAME (pad->collect.pad));
4301     qtmux->longest_chunk = qtmux->current_chunk_duration;
4302   }
4303
4304   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4305     const TrakBufferEntryInfo *sample_entry;
4306     guint64 block_idx = prefill_get_block_index (qtmux, pad);
4307
4308     if (block_idx >= pad->samples->len) {
4309       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4310           ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4311               block_idx, pad->samples->len));
4312       goto bail;
4313     }
4314
4315     /* Check if all values are as expected */
4316     sample_entry =
4317         &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4318
4319     if (chunk_offset < sample_entry->chunk_offset) {
4320       guint fill_size = sample_entry->chunk_offset - chunk_offset;
4321       GstBuffer *fill_buf;
4322
4323       fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4324       gst_buffer_memset (fill_buf, 0, 0, fill_size);
4325
4326       ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4327       if (ret != GST_FLOW_OK)
4328         goto bail;
4329       qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4330       qtmux->current_chunk_size = buffer_size;
4331       qtmux->current_chunk_duration = duration;
4332     } else if (chunk_offset != sample_entry->chunk_offset) {
4333       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4334           ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4335               G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4336       goto bail;
4337     }
4338   }
4339
4340   /* now we go and register this buffer/sample all over */
4341   ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4342       buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4343       chunk_offset, sync, TRUE, pts_offset);
4344   pad->sample_offset += nsamples;
4345
4346   /* if this is sparse and we have a next buffer, check if there is any gap
4347    * between them to insert an empty sample */
4348   if (pad->sparse && buf) {
4349     if (pad->create_empty_buffer) {
4350       GstBuffer *empty_buf;
4351       gint64 empty_duration =
4352           GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4353       gint64 empty_duration_scaled;
4354       guint empty_size;
4355
4356       empty_buf = pad->create_empty_buffer (pad, empty_duration);
4357
4358       empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
4359           atom_trak_get_timescale (pad->trak), GST_SECOND);
4360       empty_size = gst_buffer_get_size (empty_buf);
4361
4362       gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4363           empty_duration);
4364
4365       ret =
4366           gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4367           last_dts + scaled_duration, empty_duration_scaled,
4368           empty_size, chunk_offset, sync, TRUE, 0);
4369     } else {
4370       /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
4371       g_assert_not_reached ();
4372       GST_WARNING_OBJECT (qtmux,
4373           "no empty buffer creation function found for pad %s",
4374           GST_PAD_NAME (pad->collect.pad));
4375     }
4376   }
4377
4378 exit:
4379
4380   return ret;
4381
4382   /* ERRORS */
4383 bail:
4384   {
4385     gst_buffer_unref (last_buf);
4386     return GST_FLOW_ERROR;
4387   }
4388 fragmented_sample:
4389   {
4390     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4391         ("Audio buffer contains fragmented sample."));
4392     goto bail;
4393   }
4394 raw_audio_timestamp_drift:
4395   {
4396     /* TODO: Could in theory be implemented with edit lists */
4397     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4398         ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4399             ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4400             GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4401             GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4402                     GST_SECOND,
4403                     atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4404     goto bail;
4405   }
4406 no_pts:
4407   {
4408     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4409     goto bail;
4410   }
4411 not_negotiated:
4412   {
4413     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4414         ("format wasn't negotiated before buffer flow on pad %s",
4415             GST_PAD_NAME (pad->collect.pad)));
4416     if (buf)
4417       gst_buffer_unref (buf);
4418     return GST_FLOW_NOT_NEGOTIATED;
4419   }
4420 }
4421
4422 /*
4423  * DTS running time can be negative. There is no way to represent that in
4424  * MP4 however, thus we need to offset DTS so that it starts from 0.
4425  */
4426 static void
4427 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4428     GstCollectData * cdata, GstBuffer ** buf)
4429 {
4430   GstClockTime pts;
4431   gint64 dts;
4432
4433   pts = GST_BUFFER_PTS (*buf);
4434   dts = GST_COLLECT_PADS_DTS (cdata);
4435
4436   GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4437       " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4438       GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4439
4440   if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4441     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4442       pad->dts_adjustment = -dts;
4443     else
4444       pad->dts_adjustment = 0;
4445   }
4446
4447   if (pad->dts_adjustment > 0) {
4448     *buf = gst_buffer_make_writable (*buf);
4449
4450     dts += pad->dts_adjustment;
4451
4452     if (GST_CLOCK_TIME_IS_VALID (pts))
4453       pts += pad->dts_adjustment;
4454
4455     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4456       GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4457       dts = 0;
4458     }
4459
4460     if (pts < dts) {
4461       GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4462       pts = dts;
4463     }
4464
4465     GST_BUFFER_PTS (*buf) = pts;
4466     GST_BUFFER_DTS (*buf) = dts;
4467
4468     GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4469         " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4470   }
4471 }
4472
4473 static GstQTPad *
4474 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4475 {
4476   GSList *walk;
4477   GstQTPad *best_pad = NULL;
4478
4479   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4480     guint64 smallest_offset = G_MAXUINT64;
4481     guint64 chunk_offset = 0;
4482
4483     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4484       GstCollectData *cdata = (GstCollectData *) walk->data;
4485       GstQTPad *qtpad = (GstQTPad *) cdata;
4486       const TrakBufferEntryInfo *sample_entry;
4487       guint64 block_idx, current_block_idx;
4488       guint64 chunk_offset_offset = 0;
4489       GstBuffer *tmp_buf =
4490           gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4491
4492       /* Check for EOS pads and just skip them */
4493       if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4494               || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4495         continue;
4496       if (tmp_buf)
4497         gst_buffer_unref (tmp_buf);
4498
4499       /* Find the exact offset where the next sample of this track is supposed
4500        * to be written at */
4501       block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4502       sample_entry =
4503           &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4504       while (block_idx > 0) {
4505         const TrakBufferEntryInfo *tmp =
4506             &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4507
4508         if (tmp->chunk_offset != sample_entry->chunk_offset)
4509           break;
4510         chunk_offset_offset += tmp->size * tmp->nsamples;
4511         block_idx--;
4512       }
4513
4514       /* Except for the previously selected pad being EOS we always have
4515        *  qtmux->current_chunk_offset + qtmux->current_chunk_size
4516        *    ==
4517        *  sample_entry->chunk_offset + chunk_offset_offset
4518        * for the best pad. Instead of checking that, we just return the
4519        * pad that has the smallest offset for the next to-be-written sample.
4520        */
4521       if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4522         smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4523         best_pad = qtpad;
4524         chunk_offset = sample_entry->chunk_offset;
4525       }
4526     }
4527
4528     if (chunk_offset != qtmux->current_chunk_offset) {
4529       qtmux->current_pad = NULL;
4530     }
4531
4532     return best_pad;
4533   }
4534
4535   if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4536           || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4537           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4538       && (qtmux->interleave_time == 0
4539           || qtmux->current_chunk_duration <= qtmux->interleave_time)
4540       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4541       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4542     GstBuffer *tmp_buf =
4543         gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4544
4545     if (tmp_buf || qtmux->current_pad->last_buf) {
4546       best_pad = qtmux->current_pad;
4547       if (tmp_buf)
4548         gst_buffer_unref (tmp_buf);
4549       GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4550           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4551     }
4552   } else if (qtmux->collect->data->next) {
4553     /* Only switch pads if we have more than one, otherwise
4554      * we can just put everything into a single chunk and save
4555      * a few bytes of offsets
4556      */
4557     if (qtmux->current_pad)
4558       GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4559           GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4560     best_pad = qtmux->current_pad = NULL;
4561   }
4562
4563   if (!best_pad) {
4564     GstClockTime best_time = GST_CLOCK_TIME_NONE;
4565
4566     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4567       GstCollectData *cdata = (GstCollectData *) walk->data;
4568       GstQTPad *qtpad = (GstQTPad *) cdata;
4569       GstBuffer *tmp_buf;
4570       GstClockTime timestamp;
4571
4572       tmp_buf = gst_collect_pads_peek (pads, cdata);
4573       if (!tmp_buf) {
4574         /* This one is newly EOS now, finish it for real */
4575         if (qtpad->last_buf) {
4576           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4577         } else {
4578           continue;
4579         }
4580       } else {
4581         if (qtpad->last_buf)
4582           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4583         else
4584           timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4585       }
4586
4587       if (best_pad == NULL ||
4588           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4589         best_pad = qtpad;
4590         best_time = timestamp;
4591       }
4592
4593       if (tmp_buf)
4594         gst_buffer_unref (tmp_buf);
4595     }
4596
4597     if (best_pad) {
4598       GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4599           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4600     } else {
4601       GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4602     }
4603   }
4604
4605   return best_pad;
4606 }
4607
4608 static GstFlowReturn
4609 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4610 {
4611   GstFlowReturn ret = GST_FLOW_OK;
4612   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4613   GstQTPad *best_pad = NULL;
4614
4615   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4616     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4617       return ret;
4618
4619     qtmux->state = GST_QT_MUX_STATE_DATA;
4620   }
4621
4622   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4623     return GST_FLOW_EOS;
4624
4625   best_pad = find_best_pad (qtmux, pads);
4626
4627   /* clipping already converted to running time */
4628   if (best_pad != NULL) {
4629     GstBuffer *buf = NULL;
4630
4631     if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4632         best_pad->raw_audio_adapter == NULL ||
4633         best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4634       buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4635
4636     g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4637             && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4638
4639     if (buf)
4640       gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
4641           (GstCollectData *) best_pad, &buf);
4642
4643     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
4644   } else {
4645     qtmux->state = GST_QT_MUX_STATE_EOS;
4646     ret = gst_qt_mux_stop_file (qtmux);
4647     if (ret == GST_FLOW_OK) {
4648       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
4649       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
4650       ret = GST_FLOW_EOS;
4651     } else {
4652       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
4653           gst_flow_get_name (ret));
4654     }
4655   }
4656
4657   return ret;
4658 }
4659
4660 static gboolean
4661 check_field (GQuark field_id, const GValue * value, gpointer user_data)
4662 {
4663   GstStructure *structure = (GstStructure *) user_data;
4664   const GValue *other = gst_structure_id_get_value (structure, field_id);
4665   if (other == NULL)
4666     return FALSE;
4667   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
4668 }
4669
4670 static gboolean
4671 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
4672     GstCaps * superset)
4673 {
4674   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
4675   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
4676
4677   return gst_structure_foreach (sub_s, check_field, sup_s);
4678 }
4679
4680 static gboolean
4681 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4682 {
4683   GstPad *pad = qtpad->collect.pad;
4684   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4685   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4686   GstStructure *structure;
4687   const gchar *mimetype;
4688   gint rate, channels;
4689   const GValue *value = NULL;
4690   const GstBuffer *codec_data = NULL;
4691   GstQTMuxFormat format;
4692   AudioSampleEntry entry = { 0, };
4693   AtomInfo *ext_atom = NULL;
4694   gint constant_size = 0;
4695   const gchar *stream_format;
4696
4697   /* does not go well to renegotiate stream mid-way, unless
4698    * the old caps are a subset of the new one (this means upstream
4699    * added more info to the caps, as both should be 'fixed' caps) */
4700   if (qtpad->fourcc) {
4701     GstCaps *current_caps;
4702
4703     current_caps = gst_pad_get_current_caps (pad);
4704     g_assert (caps != NULL);
4705
4706     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4707       gst_caps_unref (current_caps);
4708       goto refuse_renegotiation;
4709     }
4710     GST_DEBUG_OBJECT (qtmux,
4711         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4712         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4713     gst_caps_unref (current_caps);
4714
4715     return TRUE;
4716   }
4717
4718   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4719       GST_DEBUG_PAD_NAME (pad), caps);
4720
4721   qtpad->prepare_buf_func = NULL;
4722
4723   format = qtmux_klass->format;
4724   structure = gst_caps_get_structure (caps, 0);
4725   mimetype = gst_structure_get_name (structure);
4726
4727   /* common info */
4728   if (!gst_structure_get_int (structure, "channels", &channels) ||
4729       !gst_structure_get_int (structure, "rate", &rate)) {
4730     goto refuse_caps;
4731   }
4732
4733   /* optional */
4734   value = gst_structure_get_value (structure, "codec_data");
4735   if (value != NULL)
4736     codec_data = gst_value_get_buffer (value);
4737
4738   qtpad->is_out_of_order = FALSE;
4739
4740   /* set common properties */
4741   entry.sample_rate = rate;
4742   entry.channels = channels;
4743   /* default */
4744   entry.sample_size = 16;
4745   /* this is the typical compressed case */
4746   if (format == GST_QT_MUX_FORMAT_QT) {
4747     entry.version = 1;
4748     entry.compression_id = -2;
4749   }
4750
4751   /* now map onto a fourcc, and some extra properties */
4752   if (strcmp (mimetype, "audio/mpeg") == 0) {
4753     gint mpegversion = 0, mpegaudioversion = 0;
4754     gint layer = -1;
4755
4756     gst_structure_get_int (structure, "mpegversion", &mpegversion);
4757     switch (mpegversion) {
4758       case 1:
4759         gst_structure_get_int (structure, "layer", &layer);
4760         gst_structure_get_int (structure, "mpegaudioversion",
4761             &mpegaudioversion);
4762
4763         /* mp1/2/3 */
4764         /* note: QuickTime player does not like mp3 either way in iso/mp4 */
4765         if (format == GST_QT_MUX_FORMAT_QT)
4766           entry.fourcc = FOURCC__mp3;
4767         else {
4768           entry.fourcc = FOURCC_mp4a;
4769           ext_atom =
4770               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
4771               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4772               qtpad->max_bitrate);
4773         }
4774         if (layer == 1) {
4775           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
4776           entry.samples_per_packet = 384;
4777         } else if (layer == 2) {
4778           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
4779           entry.samples_per_packet = 1152;
4780         } else {
4781           g_warn_if_fail (layer == 3);
4782           entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
4783         }
4784         entry.bytes_per_sample = 2;
4785         break;
4786       case 4:
4787
4788         /* check stream-format */
4789         stream_format = gst_structure_get_string (structure, "stream-format");
4790         if (stream_format) {
4791           if (strcmp (stream_format, "raw") != 0) {
4792             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
4793                 "please use 'raw'", stream_format);
4794             goto refuse_caps;
4795           }
4796         } else {
4797           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
4798               "assuming 'raw'");
4799         }
4800
4801         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
4802           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
4803           goto refuse_caps;
4804         } else {
4805           guint8 profile;
4806
4807           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
4808           /* warn if not Low Complexity profile */
4809           profile >>= 3;
4810           if (profile != 2)
4811             GST_WARNING_OBJECT (qtmux,
4812                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
4813         }
4814
4815         /* AAC */
4816         entry.fourcc = FOURCC_mp4a;
4817
4818         if (format == GST_QT_MUX_FORMAT_QT)
4819           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
4820               qtpad->avg_bitrate, qtpad->max_bitrate);
4821         else
4822           ext_atom =
4823               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
4824               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4825               qtpad->max_bitrate);
4826         break;
4827       default:
4828         break;
4829     }
4830   } else if (strcmp (mimetype, "audio/AMR") == 0) {
4831     entry.fourcc = FOURCC_samr;
4832     entry.sample_size = 16;
4833     entry.samples_per_packet = 160;
4834     entry.bytes_per_sample = 2;
4835     ext_atom = build_amr_extension ();
4836   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
4837     entry.fourcc = FOURCC_sawb;
4838     entry.sample_size = 16;
4839     entry.samples_per_packet = 320;
4840     entry.bytes_per_sample = 2;
4841     ext_atom = build_amr_extension ();
4842   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
4843     GstAudioInfo info;
4844
4845     gst_audio_info_init (&info);
4846     if (!gst_audio_info_from_caps (&info, caps))
4847       goto refuse_caps;
4848
4849     /* spec has no place for a distinction in these */
4850     if (info.finfo->width != info.finfo->depth) {
4851       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
4852       goto refuse_caps;
4853     }
4854
4855     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
4856       if (info.finfo->endianness == G_LITTLE_ENDIAN)
4857         entry.fourcc = FOURCC_sowt;
4858       else if (info.finfo->endianness == G_BIG_ENDIAN)
4859         entry.fourcc = FOURCC_twos;
4860       else
4861         entry.fourcc = FOURCC_sowt;
4862       /* maximum backward compatibility; only new version for > 16 bit */
4863       if (info.finfo->depth <= 16)
4864         entry.version = 0;
4865       /* not compressed in any case */
4866       entry.compression_id = 0;
4867       /* QT spec says: max at 16 bit even if sample size were actually larger,
4868        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
4869       entry.sample_size = info.finfo->depth;
4870       entry.bytes_per_sample = info.finfo->depth / 8;
4871       entry.samples_per_packet = 1;
4872       entry.bytes_per_packet = info.finfo->depth / 8;
4873       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
4874     } else {
4875       if (info.finfo->width == 8 && info.finfo->depth == 8) {
4876         /* fall back to old 8-bit version */
4877         entry.fourcc = FOURCC_raw_;
4878         entry.version = 0;
4879         entry.compression_id = 0;
4880         entry.sample_size = 8;
4881       } else {
4882         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
4883         goto refuse_caps;
4884       }
4885     }
4886     constant_size = (info.finfo->depth / 8) * info.channels;
4887   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
4888     entry.fourcc = FOURCC_alaw;
4889     entry.samples_per_packet = 1023;
4890     entry.bytes_per_sample = 2;
4891   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
4892     entry.fourcc = FOURCC_ulaw;
4893     entry.samples_per_packet = 1023;
4894     entry.bytes_per_sample = 2;
4895   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
4896     gint blocksize;
4897     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
4898       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
4899       goto refuse_caps;
4900     }
4901     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
4902        0x11 */
4903     entry.fourcc = MS_WAVE_FOURCC (0x11);
4904     /* 4 byte header per channel (including one sample). 2 samples per byte
4905        remaining. Simplifying gives the following (samples per block per
4906        channel) */
4907     entry.samples_per_packet = 2 * blocksize / channels - 7;
4908     entry.bytes_per_sample = 2;
4909
4910     entry.bytes_per_frame = blocksize;
4911     entry.bytes_per_packet = blocksize / channels;
4912     /* ADPCM has constant size packets */
4913     constant_size = 1;
4914     /* TODO: I don't really understand why this helps, but it does! Constant
4915      * size and compression_id of -2 seem to be incompatible, and other files
4916      * in the wild use this too. */
4917     entry.compression_id = -1;
4918
4919     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
4920   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
4921     GstBuffer *codec_config;
4922     gint len;
4923     GstMapInfo map;
4924
4925     entry.fourcc = FOURCC_alac;
4926     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
4927     /* let's check if codec data already comes with 'alac' atom prefix */
4928     if (!codec_data || (len = map.size) < 28) {
4929       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
4930       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
4931       goto refuse_caps;
4932     }
4933     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
4934       len -= 8;
4935       codec_config =
4936           gst_buffer_copy_region ((GstBuffer *) codec_data,
4937           GST_BUFFER_COPY_MEMORY, 8, len);
4938     } else {
4939       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
4940     }
4941     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
4942     if (len != 28) {
4943       /* does not look good, but perhaps some trailing unneeded stuff */
4944       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
4945     }
4946     if (format == GST_QT_MUX_FORMAT_QT)
4947       ext_atom = build_mov_alac_extension (codec_config);
4948     else
4949       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
4950     /* set some more info */
4951     gst_buffer_map (codec_config, &map, GST_MAP_READ);
4952     entry.bytes_per_sample = 2;
4953     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
4954     gst_buffer_unmap (codec_config, &map);
4955     gst_buffer_unref (codec_config);
4956   } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
4957     entry.fourcc = FOURCC_ac_3;
4958
4959     /* Fixed values according to TS 102 366 but it also mentions that
4960      * they should be ignored */
4961     entry.channels = 2;
4962     entry.sample_size = 16;
4963
4964     /* AC-3 needs an extension atom but its data can only be obtained from
4965      * the stream itself. Abuse the prepare_buf_func so we parse a frame
4966      * and get the needed data */
4967     qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
4968   } else if (strcmp (mimetype, "audio/x-opus") == 0) {
4969     /* Based on the specification defined in:
4970      * https://www.opus-codec.org/docs/opus_in_isobmff.html */
4971     guint8 channels, mapping_family, stream_count, coupled_count;
4972     guint16 pre_skip;
4973     gint16 output_gain;
4974     guint32 rate;
4975     guint8 channel_mapping[256];
4976     const GValue *streamheader;
4977     const GValue *first_element;
4978     GstBuffer *header;
4979
4980     entry.fourcc = FOURCC_opus;
4981     entry.sample_size = 16;
4982
4983     streamheader = gst_structure_get_value (structure, "streamheader");
4984     if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
4985         gst_value_array_get_size (streamheader) != 0) {
4986       first_element = gst_value_array_get_value (streamheader, 0);
4987       header = gst_value_get_buffer (first_element);
4988       if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
4989               &mapping_family, &stream_count, &coupled_count, channel_mapping,
4990               &pre_skip, &output_gain)) {
4991         GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
4992         goto refuse_caps;
4993       }
4994     } else {
4995       GST_WARNING_OBJECT (qtmux,
4996           "no streamheader field in caps %" GST_PTR_FORMAT, caps);
4997
4998       if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
4999               &mapping_family, &stream_count, &coupled_count,
5000               channel_mapping)) {
5001         GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5002         goto refuse_caps;
5003       }
5004       pre_skip = 0;
5005       output_gain = 0;
5006     }
5007
5008     entry.channels = channels;
5009     ext_atom = build_opus_extension (rate, channels, mapping_family,
5010         stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5011   }
5012
5013   if (!entry.fourcc)
5014     goto refuse_caps;
5015
5016   /* ok, set the pad info accordingly */
5017   qtpad->fourcc = entry.fourcc;
5018   qtpad->sample_size = constant_size;
5019   qtpad->trak_ste =
5020       (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5021       qtmux->context, &entry,
5022       qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
5023       ext_atom, constant_size);
5024
5025   gst_object_unref (qtmux);
5026   return TRUE;
5027
5028   /* ERRORS */
5029 refuse_caps:
5030   {
5031     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5032         GST_PAD_NAME (pad), caps);
5033     gst_object_unref (qtmux);
5034     return FALSE;
5035   }
5036 refuse_renegotiation:
5037   {
5038     GST_WARNING_OBJECT (qtmux,
5039         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5040         GST_PAD_NAME (pad), caps);
5041     gst_object_unref (qtmux);
5042     return FALSE;
5043   }
5044 }
5045
5046 static gboolean
5047 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5048 {
5049   GstPad *pad = qtpad->collect.pad;
5050   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5051   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5052   GstStructure *structure;
5053   const gchar *mimetype;
5054   gint width, height, depth = -1;
5055   gint framerate_num, framerate_den;
5056   guint32 rate;
5057   const GValue *value = NULL;
5058   const GstBuffer *codec_data = NULL;
5059   VisualSampleEntry entry = { 0, };
5060   GstQTMuxFormat format;
5061   AtomInfo *ext_atom = NULL;
5062   GList *ext_atom_list = NULL;
5063   gboolean sync = FALSE;
5064   int par_num, par_den;
5065
5066   /* does not go well to renegotiate stream mid-way, unless
5067    * the old caps are a subset of the new one (this means upstream
5068    * added more info to the caps, as both should be 'fixed' caps) */
5069   if (qtpad->fourcc) {
5070     GstCaps *current_caps;
5071
5072     current_caps = gst_pad_get_current_caps (pad);
5073     g_assert (caps != NULL);
5074
5075     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5076       gst_caps_unref (current_caps);
5077       goto refuse_renegotiation;
5078     }
5079     GST_DEBUG_OBJECT (qtmux,
5080         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5081         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5082     gst_caps_unref (current_caps);
5083
5084     return TRUE;
5085   }
5086
5087   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5088       GST_DEBUG_PAD_NAME (pad), caps);
5089
5090   qtpad->prepare_buf_func = NULL;
5091
5092   format = qtmux_klass->format;
5093   structure = gst_caps_get_structure (caps, 0);
5094   mimetype = gst_structure_get_name (structure);
5095
5096   /* required parts */
5097   if (!gst_structure_get_int (structure, "width", &width) ||
5098       !gst_structure_get_int (structure, "height", &height))
5099     goto refuse_caps;
5100
5101   /* optional */
5102   depth = -1;
5103   /* works as a default timebase */
5104   framerate_num = 10000;
5105   framerate_den = 1;
5106   gst_structure_get_fraction (structure, "framerate", &framerate_num,
5107       &framerate_den);
5108   gst_structure_get_int (structure, "depth", &depth);
5109   value = gst_structure_get_value (structure, "codec_data");
5110   if (value != NULL)
5111     codec_data = gst_value_get_buffer (value);
5112
5113   par_num = 1;
5114   par_den = 1;
5115   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5116       &par_den);
5117
5118   qtpad->is_out_of_order = FALSE;
5119
5120   /* bring frame numerator into a range that ensures both reasonable resolution
5121    * as well as a fair duration */
5122   qtpad->expected_sample_duration_n = framerate_num;
5123   qtpad->expected_sample_duration_d = framerate_den;
5124   rate = qtmux->trak_timescale ?
5125       qtmux->trak_timescale : atom_framerate_to_timescale (framerate_num,
5126       framerate_den);
5127   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5128       rate);
5129
5130   /* set common properties */
5131   entry.width = width;
5132   entry.height = height;
5133   entry.par_n = par_num;
5134   entry.par_d = par_den;
5135   /* should be OK according to qt and iso spec, override if really needed */
5136   entry.color_table_id = -1;
5137   entry.frame_count = 1;
5138   entry.depth = 24;
5139
5140   /* sync entries by default */
5141   sync = TRUE;
5142
5143   /* now map onto a fourcc, and some extra properties */
5144   if (strcmp (mimetype, "video/x-raw") == 0) {
5145     const gchar *format;
5146     GstVideoFormat fmt;
5147     const GstVideoFormatInfo *vinfo;
5148
5149     format = gst_structure_get_string (structure, "format");
5150     fmt = gst_video_format_from_string (format);
5151     vinfo = gst_video_format_get_info (fmt);
5152
5153     switch (fmt) {
5154       case GST_VIDEO_FORMAT_UYVY:
5155         if (depth == -1)
5156           depth = 24;
5157         entry.fourcc = FOURCC_2vuy;
5158         entry.depth = depth;
5159         sync = FALSE;
5160         break;
5161       case GST_VIDEO_FORMAT_v210:
5162         if (depth == -1)
5163           depth = 24;
5164         entry.fourcc = FOURCC_v210;
5165         entry.depth = depth;
5166         sync = FALSE;
5167         break;
5168       default:
5169         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5170           entry.fourcc = FOURCC_raw_;
5171           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5172           sync = FALSE;
5173         }
5174         break;
5175     }
5176   } else if (strcmp (mimetype, "video/x-h263") == 0) {
5177     ext_atom = NULL;
5178     if (format == GST_QT_MUX_FORMAT_QT)
5179       entry.fourcc = FOURCC_h263;
5180     else
5181       entry.fourcc = FOURCC_s263;
5182     ext_atom = build_h263_extension ();
5183     if (ext_atom != NULL)
5184       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5185   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5186       strcmp (mimetype, "video/mpeg") == 0) {
5187     gint version = 0;
5188
5189     if (strcmp (mimetype, "video/x-divx") == 0) {
5190       gst_structure_get_int (structure, "divxversion", &version);
5191       version = version == 5 ? 1 : 0;
5192     } else {
5193       gst_structure_get_int (structure, "mpegversion", &version);
5194       version = version == 4 ? 1 : 0;
5195     }
5196     if (version) {
5197       entry.fourcc = FOURCC_mp4v;
5198       ext_atom =
5199           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5200           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5201           qtpad->max_bitrate);
5202       if (ext_atom != NULL)
5203         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5204       if (!codec_data)
5205         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5206             "output might not play in Apple QuickTime (try global-headers?)");
5207     }
5208   } else if (strcmp (mimetype, "video/x-h264") == 0) {
5209     if (!codec_data) {
5210       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5211       goto refuse_caps;
5212     }
5213
5214     entry.fourcc = FOURCC_avc1;
5215
5216     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5217     if (ext_atom != NULL)
5218       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5219     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5220     if (ext_atom != NULL)
5221       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5222   } else if (strcmp (mimetype, "video/x-h265") == 0) {
5223     const gchar *format;
5224
5225     if (!codec_data) {
5226       GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5227       goto refuse_caps;
5228     }
5229
5230     format = gst_structure_get_string (structure, "stream-format");
5231     if (strcmp (format, "hvc1") == 0)
5232       entry.fourcc = FOURCC_hvc1;
5233     else if (strcmp (format, "hev1") == 0)
5234       entry.fourcc = FOURCC_hev1;
5235
5236     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5237     if (ext_atom != NULL)
5238       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5239
5240     ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5241     if (ext_atom != NULL)
5242       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5243
5244   } else if (strcmp (mimetype, "video/x-svq") == 0) {
5245     gint version = 0;
5246     const GstBuffer *seqh = NULL;
5247     const GValue *seqh_value;
5248     gdouble gamma = 0;
5249
5250     gst_structure_get_int (structure, "svqversion", &version);
5251     if (version == 3) {
5252       entry.fourcc = FOURCC_SVQ3;
5253       entry.version = 3;
5254       entry.depth = 32;
5255
5256       seqh_value = gst_structure_get_value (structure, "seqh");
5257       if (seqh_value) {
5258         seqh = gst_value_get_buffer (seqh_value);
5259         ext_atom = build_SMI_atom (seqh);
5260         if (ext_atom)
5261           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5262       }
5263
5264       /* we need to add the gamma anyway because quicktime might crash
5265        * when it doesn't find it */
5266       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5267         /* it seems that using 0 here makes it ignored */
5268         gamma = 0.0;
5269       }
5270       ext_atom = build_gama_atom (gamma);
5271       if (ext_atom)
5272         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5273     } else {
5274       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5275           "a bug at http://bugzilla.gnome.org", version);
5276     }
5277   } else if (strcmp (mimetype, "video/x-dv") == 0) {
5278     gint version = 0;
5279     gboolean pal = TRUE;
5280
5281     sync = FALSE;
5282     if (framerate_num != 25 || framerate_den != 1)
5283       pal = FALSE;
5284     gst_structure_get_int (structure, "dvversion", &version);
5285     /* fall back to typical one */
5286     if (!version)
5287       version = 25;
5288     switch (version) {
5289       case 25:
5290         if (pal)
5291           entry.fourcc = FOURCC_dvcp;
5292         else
5293           entry.fourcc = FOURCC_dvc_;
5294         break;
5295       case 50:
5296         if (pal)
5297           entry.fourcc = FOURCC_dv5p;
5298         else
5299           entry.fourcc = FOURCC_dv5n;
5300         break;
5301       default:
5302         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5303         break;
5304     }
5305   } else if (strcmp (mimetype, "image/jpeg") == 0) {
5306     entry.fourcc = FOURCC_jpeg;
5307     sync = FALSE;
5308   } else if (strcmp (mimetype, "image/png") == 0) {
5309     entry.fourcc = FOURCC_png;
5310     sync = FALSE;
5311   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5312       strcmp (mimetype, "image/x-jpc") == 0) {
5313     const gchar *colorspace;
5314     const GValue *cmap_array;
5315     const GValue *cdef_array;
5316     gint ncomp = 0;
5317
5318     if (strcmp (mimetype, "image/x-jpc") == 0) {
5319       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5320     }
5321
5322     gst_structure_get_int (structure, "num-components", &ncomp);
5323     cmap_array = gst_structure_get_value (structure, "component-map");
5324     cdef_array = gst_structure_get_value (structure, "channel-definitions");
5325
5326     ext_atom = NULL;
5327     entry.fourcc = FOURCC_mjp2;
5328     sync = FALSE;
5329
5330     colorspace = gst_structure_get_string (structure, "colorspace");
5331     if (colorspace &&
5332         (ext_atom =
5333             build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5334                 cdef_array)) != NULL) {
5335       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5336
5337       ext_atom = build_jp2x_extension (codec_data);
5338       if (ext_atom)
5339         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5340     } else {
5341       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5342       goto refuse_caps;
5343     }
5344   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5345     entry.fourcc = FOURCC_VP80;
5346     sync = FALSE;
5347   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5348     entry.fourcc = FOURCC_drac;
5349   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5350     guint32 fourcc = 0;
5351
5352     gst_structure_get_uint (structure, "format", &fourcc);
5353     entry.fourcc = fourcc;
5354   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5355     guint32 fourcc = 0;
5356
5357     gst_structure_get_uint (structure, "format", &fourcc);
5358     entry.fourcc = fourcc;
5359   } else if (strcmp (mimetype, "video/x-prores") == 0) {
5360     const gchar *variant;
5361
5362     variant = gst_structure_get_string (structure, "variant");
5363     if (!variant || !g_strcmp0 (variant, "standard"))
5364       entry.fourcc = FOURCC_apcn;
5365     else if (!g_strcmp0 (variant, "lt"))
5366       entry.fourcc = FOURCC_apcs;
5367     else if (!g_strcmp0 (variant, "hq"))
5368       entry.fourcc = FOURCC_apch;
5369     else if (!g_strcmp0 (variant, "proxy"))
5370       entry.fourcc = FOURCC_apco;
5371     else if (!g_strcmp0 (variant, "4444"))
5372       entry.fourcc = FOURCC_ap4h;
5373     else if (!g_strcmp0 (variant, "4444xq"))
5374       entry.fourcc = FOURCC_ap4x;
5375
5376     sync = FALSE;
5377
5378     if (!qtmux->interleave_time_set)
5379       qtmux->interleave_time = 500 * GST_MSECOND;
5380     if (!qtmux->interleave_bytes_set)
5381       qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5382   } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5383     entry.fourcc = FOURCC_cfhd;
5384     sync = FALSE;
5385   }
5386
5387   if (!entry.fourcc)
5388     goto refuse_caps;
5389
5390   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5391       qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5392     const gchar *s;
5393     GstVideoColorimetry colorimetry;
5394
5395     s = gst_structure_get_string (structure, "colorimetry");
5396     if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5397       ext_atom =
5398           build_colr_extension (&colorimetry,
5399           qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5400       if (ext_atom)
5401         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5402     }
5403   }
5404
5405   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5406       || strcmp (mimetype, "image/x-j2c") == 0
5407       || strcmp (mimetype, "image/x-jpc") == 0) {
5408     const gchar *s;
5409     GstVideoInterlaceMode interlace_mode;
5410     GstVideoFieldOrder field_order;
5411     gint fields = -1;
5412
5413     if (strcmp (mimetype, "image/x-j2c") == 0 ||
5414         strcmp (mimetype, "image/x-jpc") == 0) {
5415
5416       fields = 1;
5417       gst_structure_get_int (structure, "fields", &fields);
5418     }
5419
5420     s = gst_structure_get_string (structure, "interlace-mode");
5421     if (s)
5422       interlace_mode = gst_video_interlace_mode_from_string (s);
5423     else
5424       interlace_mode =
5425           (fields <=
5426           1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5427           GST_VIDEO_INTERLACE_MODE_MIXED;
5428
5429     field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5430     if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5431       s = gst_structure_get_string (structure, "field-order");
5432       if (s)
5433         field_order = gst_video_field_order_from_string (s);
5434     }
5435
5436     ext_atom = build_fiel_extension (interlace_mode, field_order);
5437     if (ext_atom)
5438       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5439   }
5440
5441
5442   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5443       width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5444     /* The 'clap' extension is also defined for MP4 but inventing values in
5445      * general seems a bit tricky for this one. We only write it for
5446      * SD resolution in MOV, where it is a requirement.
5447      * The same goes for the 'tapt' extension, just that it is not defined for
5448      * MP4 and only for MOV
5449      */
5450     gint dar_num, dar_den;
5451     gint clef_width, clef_height, prof_width;
5452     gint clap_width_n, clap_width_d, clap_height;
5453     gint cdiv;
5454     double approx_dar;
5455
5456     /* First, guess display aspect ratio based on pixel aspect ratio,
5457      * width and height. We assume that display aspect ratio is either
5458      * 4:3 or 16:9
5459      */
5460     approx_dar = (gdouble) (width * par_num) / (height * par_den);
5461     if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5462       dar_num = 4;
5463       dar_den = 3;
5464     } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5465       dar_num = 16;
5466       dar_den = 9;
5467     } else {
5468       dar_num = width * par_num;
5469       dar_den = height * par_den;
5470       cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5471       dar_num /= cdiv;
5472       dar_den /= cdiv;
5473     }
5474
5475     /* Then, calculate clean-aperture values (clap and clef)
5476      * using the guessed DAR.
5477      */
5478     clef_height = clap_height = (height == 486 ? 480 : height);
5479     clef_width = gst_util_uint64_scale (clef_height,
5480         dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5481     prof_width = gst_util_uint64_scale (width,
5482         par_num * G_GUINT64_CONSTANT (65536), par_den);
5483     clap_width_n = clap_height * dar_num * par_den;
5484     clap_width_d = dar_den * par_num;
5485     cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5486     clap_width_n /= cdiv;
5487     clap_width_d /= cdiv;
5488
5489     ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5490         height << 16, width << 16, height << 16);
5491     qtpad->trak->tapt = ext_atom;
5492
5493     ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5494         clap_height, 1, 0, 1, 0, 1);
5495     if (ext_atom)
5496       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5497   }
5498
5499   /* ok, set the pad info accordingly */
5500   qtpad->fourcc = entry.fourcc;
5501   qtpad->sync = sync;
5502   qtpad->trak_ste =
5503       (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5504       qtmux->context, &entry, rate, ext_atom_list);
5505   if (strcmp (mimetype, "video/x-prores") == 0) {
5506     SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5507     const gchar *compressor = NULL;
5508     mp4v->spatial_quality = 0x3FF;
5509     mp4v->temporal_quality = 0;
5510     mp4v->vendor = FOURCC_appl;
5511     mp4v->horizontal_resolution = 72 << 16;
5512     mp4v->vertical_resolution = 72 << 16;
5513     mp4v->depth = (entry.fourcc == FOURCC_ap4h
5514         || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5515
5516     /* Set compressor name, required by some software */
5517     switch (entry.fourcc) {
5518       case FOURCC_apcn:
5519         compressor = "Apple ProRes 422";
5520         break;
5521       case FOURCC_apcs:
5522         compressor = "Apple ProRes 422 LT";
5523         break;
5524       case FOURCC_apch:
5525         compressor = "Apple ProRes 422 HQ";
5526         break;
5527       case FOURCC_apco:
5528         compressor = "Apple ProRes 422 Proxy";
5529         break;
5530       case FOURCC_ap4h:
5531         compressor = "Apple ProRes 4444";
5532         break;
5533       case FOURCC_ap4x:
5534         compressor = "Apple ProRes 4444 XQ";
5535         break;
5536     }
5537     if (compressor) {
5538       strcpy ((gchar *) mp4v->compressor + 1, compressor);
5539       mp4v->compressor[0] = strlen (compressor);
5540     }
5541   }
5542
5543   gst_object_unref (qtmux);
5544   return TRUE;
5545
5546   /* ERRORS */
5547 refuse_caps:
5548   {
5549     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5550         GST_PAD_NAME (pad), caps);
5551     gst_object_unref (qtmux);
5552     return FALSE;
5553   }
5554 refuse_renegotiation:
5555   {
5556     GST_WARNING_OBJECT (qtmux,
5557         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5558         caps);
5559     gst_object_unref (qtmux);
5560     return FALSE;
5561   }
5562 }
5563
5564 static gboolean
5565 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5566 {
5567   GstPad *pad = qtpad->collect.pad;
5568   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5569   GstStructure *structure;
5570   SubtitleSampleEntry entry = { 0, };
5571
5572   /* does not go well to renegotiate stream mid-way, unless
5573    * the old caps are a subset of the new one (this means upstream
5574    * added more info to the caps, as both should be 'fixed' caps) */
5575   if (qtpad->fourcc) {
5576     GstCaps *current_caps;
5577
5578     current_caps = gst_pad_get_current_caps (pad);
5579     g_assert (caps != NULL);
5580
5581     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5582       gst_caps_unref (current_caps);
5583       goto refuse_renegotiation;
5584     }
5585     GST_DEBUG_OBJECT (qtmux,
5586         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5587         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5588     gst_caps_unref (current_caps);
5589
5590     return TRUE;
5591   }
5592
5593   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5594       GST_DEBUG_PAD_NAME (pad), caps);
5595
5596   /* subtitles default */
5597   subtitle_sample_entry_init (&entry);
5598   qtpad->is_out_of_order = FALSE;
5599   qtpad->sync = FALSE;
5600   qtpad->sparse = TRUE;
5601   qtpad->prepare_buf_func = NULL;
5602
5603   structure = gst_caps_get_structure (caps, 0);
5604
5605   if (gst_structure_has_name (structure, "text/x-raw")) {
5606     const gchar *format = gst_structure_get_string (structure, "format");
5607     if (format && strcmp (format, "utf8") == 0) {
5608       entry.fourcc = FOURCC_tx3g;
5609       qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
5610       qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
5611     }
5612   }
5613
5614   if (!entry.fourcc)
5615     goto refuse_caps;
5616
5617   qtpad->fourcc = entry.fourcc;
5618   qtpad->trak_ste =
5619       (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
5620       qtmux->context, &entry);
5621
5622   gst_object_unref (qtmux);
5623   return TRUE;
5624
5625   /* ERRORS */
5626 refuse_caps:
5627   {
5628     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5629         GST_PAD_NAME (pad), caps);
5630     gst_object_unref (qtmux);
5631     return FALSE;
5632   }
5633 refuse_renegotiation:
5634   {
5635     GST_WARNING_OBJECT (qtmux,
5636         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5637         caps);
5638     gst_object_unref (qtmux);
5639     return FALSE;
5640   }
5641 }
5642
5643 static gboolean
5644 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
5645     GstEvent * event, gpointer user_data)
5646 {
5647   GstQTMux *qtmux;
5648   guint32 avg_bitrate = 0, max_bitrate = 0;
5649   GstPad *pad = data->pad;
5650   gboolean ret = TRUE;
5651
5652   qtmux = GST_QT_MUX_CAST (user_data);
5653   switch (GST_EVENT_TYPE (event)) {
5654     case GST_EVENT_CAPS:
5655     {
5656       GstCaps *caps;
5657       GstQTPad *collect_pad;
5658
5659       gst_event_parse_caps (event, &caps);
5660
5661       /* find stream data */
5662       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5663       g_assert (collect_pad);
5664       g_assert (collect_pad->set_caps);
5665
5666       ret = collect_pad->set_caps (collect_pad, caps);
5667       gst_event_unref (event);
5668       event = NULL;
5669       break;
5670     }
5671     case GST_EVENT_TAG:{
5672       GstTagList *list;
5673       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
5674       GstTagMergeMode mode;
5675       gchar *code;
5676       GstQTPad *collect_pad;
5677
5678       GST_OBJECT_LOCK (qtmux);
5679       mode = gst_tag_setter_get_tag_merge_mode (setter);
5680       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5681
5682       gst_event_parse_tag (event, &list);
5683       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
5684           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
5685
5686       if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
5687         gst_tag_setter_merge_tags (setter, list, mode);
5688         qtmux->tags_changed = TRUE;
5689       } else {
5690         if (!collect_pad->tags)
5691           collect_pad->tags = gst_tag_list_new_empty ();
5692         gst_tag_list_insert (collect_pad->tags, list, mode);
5693         collect_pad->tags_changed = TRUE;
5694       }
5695       GST_OBJECT_UNLOCK (qtmux);
5696
5697       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
5698           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
5699         GstQTPad *qtpad = gst_pad_get_element_private (pad);
5700         g_assert (qtpad);
5701
5702         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
5703           qtpad->avg_bitrate = avg_bitrate;
5704         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
5705           qtpad->max_bitrate = max_bitrate;
5706       }
5707
5708       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
5709         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
5710         if (iso_code) {
5711           GstQTPad *qtpad = gst_pad_get_element_private (pad);
5712           g_assert (qtpad);
5713           if (qtpad->trak) {
5714             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
5715             qtpad->trak->mdia.mdhd.language_code =
5716                 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
5717                 (iso_code[2] - 0x60);
5718           }
5719         }
5720         g_free (code);
5721       }
5722
5723       gst_event_unref (event);
5724       event = NULL;
5725       ret = TRUE;
5726       break;
5727     }
5728     default:
5729       break;
5730   }
5731
5732   if (event != NULL)
5733     return gst_collect_pads_event_default (pads, data, event, FALSE);
5734
5735   return ret;
5736 }
5737
5738 static void
5739 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
5740 {
5741   GstQTMux *mux = GST_QT_MUX_CAST (element);
5742   GSList *walk;
5743
5744   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
5745
5746   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
5747     GstQTPad *qtpad = (GstQTPad *) walk->data;
5748     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
5749     if (qtpad->collect.pad == pad) {
5750       /* this is it, remove */
5751       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
5752       gst_element_remove_pad (element, pad);
5753       break;
5754     }
5755   }
5756
5757   if (mux->current_pad && mux->current_pad->collect.pad == pad) {
5758     mux->current_pad = NULL;
5759     mux->current_chunk_size = 0;
5760     mux->current_chunk_duration = 0;
5761   }
5762
5763   gst_collect_pads_remove_pad (mux->collect, pad);
5764
5765   if (mux->sinkpads == NULL) {
5766     /* No more outstanding request pads, reset our counters */
5767     mux->video_pads = 0;
5768     mux->audio_pads = 0;
5769     mux->subtitle_pads = 0;
5770   }
5771 }
5772
5773 static GstPad *
5774 gst_qt_mux_request_new_pad (GstElement * element,
5775     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
5776 {
5777   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
5778   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
5779   GstQTPad *collect_pad;
5780   GstPad *newpad;
5781   GstQTPadSetCapsFunc setcaps_func;
5782   gchar *name;
5783   gint pad_id;
5784   gboolean lock = TRUE;
5785
5786   if (templ->direction != GST_PAD_SINK)
5787     goto wrong_direction;
5788
5789   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
5790     goto too_late;
5791
5792   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
5793     setcaps_func = gst_qt_mux_audio_sink_set_caps;
5794     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
5795       name = g_strdup (req_name);
5796     } else {
5797       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
5798     }
5799   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
5800     setcaps_func = gst_qt_mux_video_sink_set_caps;
5801     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
5802       name = g_strdup (req_name);
5803     } else {
5804       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
5805     }
5806   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
5807     setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
5808     if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
5809       name = g_strdup (req_name);
5810     } else {
5811       name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
5812     }
5813     lock = FALSE;
5814   } else
5815     goto wrong_template;
5816
5817   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
5818
5819   /* create pad and add to collections */
5820   newpad = gst_pad_new_from_template (templ, name);
5821   g_free (name);
5822   collect_pad = (GstQTPad *)
5823       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
5824       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
5825   /* set up pad */
5826   gst_qt_mux_pad_reset (collect_pad);
5827   collect_pad->trak = atom_trak_new (qtmux->context);
5828   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
5829
5830   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
5831
5832   /* set up pad functions */
5833   collect_pad->set_caps = setcaps_func;
5834
5835   gst_pad_set_active (newpad, TRUE);
5836   gst_element_add_pad (element, newpad);
5837
5838   return newpad;
5839
5840   /* ERRORS */
5841 wrong_direction:
5842   {
5843     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
5844     return NULL;
5845   }
5846 too_late:
5847   {
5848     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
5849     return NULL;
5850   }
5851 wrong_template:
5852   {
5853     GST_WARNING_OBJECT (qtmux, "This is not our template!");
5854     return NULL;
5855   }
5856 }
5857
5858 static void
5859 gst_qt_mux_get_property (GObject * object,
5860     guint prop_id, GValue * value, GParamSpec * pspec)
5861 {
5862   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
5863
5864   GST_OBJECT_LOCK (qtmux);
5865   switch (prop_id) {
5866     case PROP_MOVIE_TIMESCALE:
5867       g_value_set_uint (value, qtmux->timescale);
5868       break;
5869     case PROP_TRAK_TIMESCALE:
5870       g_value_set_uint (value, qtmux->trak_timescale);
5871       break;
5872     case PROP_DO_CTTS:
5873       g_value_set_boolean (value, qtmux->guess_pts);
5874       break;
5875 #ifndef GST_REMOVE_DEPRECATED
5876     case PROP_DTS_METHOD:
5877       g_value_set_enum (value, qtmux->dts_method);
5878       break;
5879 #endif
5880     case PROP_FAST_START:
5881       g_value_set_boolean (value, qtmux->fast_start);
5882       break;
5883     case PROP_FAST_START_TEMP_FILE:
5884       g_value_set_string (value, qtmux->fast_start_file_path);
5885       break;
5886     case PROP_MOOV_RECOV_FILE:
5887       g_value_set_string (value, qtmux->moov_recov_file_path);
5888       break;
5889     case PROP_FRAGMENT_DURATION:
5890       g_value_set_uint (value, qtmux->fragment_duration);
5891       break;
5892     case PROP_STREAMABLE:
5893       g_value_set_boolean (value, qtmux->streamable);
5894       break;
5895     case PROP_RESERVED_MAX_DURATION:
5896       g_value_set_uint64 (value, qtmux->reserved_max_duration);
5897       break;
5898     case PROP_RESERVED_DURATION_REMAINING:
5899       if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
5900         g_value_set_uint64 (value, qtmux->reserved_max_duration);
5901       else {
5902         GstClockTime remaining = qtmux->reserved_duration_remaining;
5903
5904         /* Report the remaining space as the calculated remaining, minus
5905          * however much we've muxed since the last update */
5906         if (remaining > qtmux->muxed_since_last_update)
5907           remaining -= qtmux->muxed_since_last_update;
5908         else
5909           remaining = 0;
5910         GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
5911             G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
5912             remaining, qtmux->reserved_duration_remaining,
5913             qtmux->muxed_since_last_update);
5914         g_value_set_uint64 (value, remaining);
5915       }
5916       break;
5917     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
5918       g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
5919       break;
5920     case PROP_RESERVED_BYTES_PER_SEC:
5921       g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
5922       break;
5923     case PROP_RESERVED_PREFILL:
5924       g_value_set_boolean (value, qtmux->reserved_prefill);
5925       break;
5926     case PROP_INTERLEAVE_BYTES:
5927       g_value_set_uint64 (value, qtmux->interleave_bytes);
5928       break;
5929     case PROP_INTERLEAVE_TIME:
5930       g_value_set_uint64 (value, qtmux->interleave_time);
5931       break;
5932     case PROP_MAX_RAW_AUDIO_DRIFT:
5933       g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
5934       break;
5935     default:
5936       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5937       break;
5938   }
5939   GST_OBJECT_UNLOCK (qtmux);
5940 }
5941
5942 static void
5943 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
5944 {
5945   gchar *tmp;
5946
5947   g_free (qtmux->fast_start_file_path);
5948   qtmux->fast_start_file_path = NULL;
5949
5950   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
5951   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
5952   g_free (tmp);
5953 }
5954
5955 static void
5956 gst_qt_mux_set_property (GObject * object,
5957     guint prop_id, const GValue * value, GParamSpec * pspec)
5958 {
5959   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
5960
5961   GST_OBJECT_LOCK (qtmux);
5962   switch (prop_id) {
5963     case PROP_MOVIE_TIMESCALE:
5964       qtmux->timescale = g_value_get_uint (value);
5965       break;
5966     case PROP_TRAK_TIMESCALE:
5967       qtmux->trak_timescale = g_value_get_uint (value);
5968       break;
5969     case PROP_DO_CTTS:
5970       qtmux->guess_pts = g_value_get_boolean (value);
5971       break;
5972 #ifndef GST_REMOVE_DEPRECATED
5973     case PROP_DTS_METHOD:
5974       qtmux->dts_method = g_value_get_enum (value);
5975       break;
5976 #endif
5977     case PROP_FAST_START:
5978       qtmux->fast_start = g_value_get_boolean (value);
5979       break;
5980     case PROP_FAST_START_TEMP_FILE:
5981       g_free (qtmux->fast_start_file_path);
5982       qtmux->fast_start_file_path = g_value_dup_string (value);
5983       /* NULL means to generate a random one */
5984       if (!qtmux->fast_start_file_path) {
5985         gst_qt_mux_generate_fast_start_file_path (qtmux);
5986       }
5987       break;
5988     case PROP_MOOV_RECOV_FILE:
5989       g_free (qtmux->moov_recov_file_path);
5990       qtmux->moov_recov_file_path = g_value_dup_string (value);
5991       break;
5992     case PROP_FRAGMENT_DURATION:
5993       qtmux->fragment_duration = g_value_get_uint (value);
5994       break;
5995     case PROP_STREAMABLE:{
5996       GstQTMuxClass *qtmux_klass =
5997           (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5998       if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
5999         qtmux->streamable = g_value_get_boolean (value);
6000       }
6001       break;
6002     }
6003     case PROP_RESERVED_MAX_DURATION:
6004       qtmux->reserved_max_duration = g_value_get_uint64 (value);
6005       break;
6006     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6007       qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6008       break;
6009     case PROP_RESERVED_BYTES_PER_SEC:
6010       qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6011       break;
6012     case PROP_RESERVED_PREFILL:
6013       qtmux->reserved_prefill = g_value_get_boolean (value);
6014       break;
6015     case PROP_INTERLEAVE_BYTES:
6016       qtmux->interleave_bytes = g_value_get_uint64 (value);
6017       qtmux->interleave_bytes_set = TRUE;
6018       break;
6019     case PROP_INTERLEAVE_TIME:
6020       qtmux->interleave_time = g_value_get_uint64 (value);
6021       qtmux->interleave_time_set = TRUE;
6022       break;
6023     case PROP_MAX_RAW_AUDIO_DRIFT:
6024       qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6025       break;
6026     default:
6027       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6028       break;
6029   }
6030   GST_OBJECT_UNLOCK (qtmux);
6031 }
6032
6033 static GstStateChangeReturn
6034 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6035 {
6036   GstStateChangeReturn ret;
6037   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6038
6039   switch (transition) {
6040     case GST_STATE_CHANGE_NULL_TO_READY:
6041       break;
6042     case GST_STATE_CHANGE_READY_TO_PAUSED:
6043       gst_collect_pads_start (qtmux->collect);
6044       qtmux->state = GST_QT_MUX_STATE_STARTED;
6045       break;
6046     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6047       break;
6048     case GST_STATE_CHANGE_PAUSED_TO_READY:
6049       gst_collect_pads_stop (qtmux->collect);
6050       break;
6051     default:
6052       break;
6053   }
6054
6055   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6056
6057   switch (transition) {
6058     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6059       break;
6060     case GST_STATE_CHANGE_PAUSED_TO_READY:
6061       gst_qt_mux_reset (qtmux, TRUE);
6062       break;
6063     case GST_STATE_CHANGE_READY_TO_NULL:
6064       break;
6065     default:
6066       break;
6067   }
6068
6069   return ret;
6070 }
6071
6072 gboolean
6073 gst_qt_mux_register (GstPlugin * plugin)
6074 {
6075   GTypeInfo typeinfo = {
6076     sizeof (GstQTMuxClass),
6077     (GBaseInitFunc) gst_qt_mux_base_init,
6078     NULL,
6079     (GClassInitFunc) gst_qt_mux_class_init,
6080     NULL,
6081     NULL,
6082     sizeof (GstQTMux),
6083     0,
6084     (GInstanceInitFunc) gst_qt_mux_init,
6085   };
6086   static const GInterfaceInfo tag_setter_info = {
6087     NULL, NULL, NULL
6088   };
6089   static const GInterfaceInfo tag_xmp_writer_info = {
6090     NULL, NULL, NULL
6091   };
6092   static const GInterfaceInfo preset_info = {
6093     NULL, NULL, NULL
6094   };
6095   GType type;
6096   GstQTMuxFormat format;
6097   GstQTMuxClassParams *params;
6098   guint i = 0;
6099
6100   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6101
6102   GST_LOG ("Registering muxers");
6103
6104   while (TRUE) {
6105     GstQTMuxFormatProp *prop;
6106     GstCaps *subtitle_caps;
6107
6108     prop = &gst_qt_mux_format_list[i];
6109     format = prop->format;
6110     if (format == GST_QT_MUX_FORMAT_NONE)
6111       break;
6112
6113     /* create a cache for these properties */
6114     params = g_new0 (GstQTMuxClassParams, 1);
6115     params->prop = prop;
6116     params->src_caps = gst_static_caps_get (&prop->src_caps);
6117     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6118     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6119     subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6120     if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6121       params->subtitle_sink_caps = subtitle_caps;
6122     } else {
6123       gst_caps_unref (subtitle_caps);
6124     }
6125
6126     /* create the type now */
6127     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6128         0);
6129     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6130     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6131     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6132         &tag_xmp_writer_info);
6133     g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6134
6135     if (!gst_element_register (plugin, prop->name, prop->rank, type))
6136       return FALSE;
6137
6138     i++;
6139   }
6140
6141   GST_LOG ("Finished registering muxers");
6142
6143   /* FIXME: ideally classification tag should be added and
6144      registered in gstreamer core gsttaglist
6145    */
6146
6147   GST_LOG ("Registering tags");
6148
6149   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6150       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6151       gst_tag_merge_use_first);
6152
6153   GST_LOG ("Finished registering tags");
6154
6155   return TRUE;
6156 }