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