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