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