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