qtmux: Fix problems causing bad durations in file
[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  * Contact: Stefan Kost <stefan.kost@nokia.com>
6
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /*
23  * Unless otherwise indicated, Source Code is licensed under MIT license.
24  * See further explanation attached in License Statement (distributed in the file
25  * LICENSE).
26  *
27  * Permission is hereby granted, free of charge, to any person obtaining a copy of
28  * this software and associated documentation files (the "Software"), to deal in
29  * the Software without restriction, including without limitation the rights to
30  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
31  * of the Software, and to permit persons to whom the Software is furnished to do
32  * so, subject to the following conditions:
33  *
34  * The above copyright notice and this permission notice shall be included in all
35  * copies or substantial portions of the Software.
36  *
37  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
38  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
40  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
41  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
42  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
43  * SOFTWARE.
44  */
45
46
47 /**
48  * SECTION:element-qtmux
49  * @short_description: Muxer for quicktime(.mov) files
50  *
51  * This element merges streams (audio and video) into QuickTime(.mov) files.
52  *
53  * The following background intends to explain why various similar muxers
54  * are present in this plugin.
55  *
56  * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
57  * QuickTime file format specification</ulink> served as basis for the MP4 file
58  * format specification (mp4mux), and as such the QuickTime file structure is
59  * nearly identical to the so-called ISO Base Media file format defined in
60  * ISO 14496-12 (except for some media specific parts).
61  * In turn, the latter ISO Base Media format was further specialized as a
62  * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
63  * and in various 3GPP(2) specs (gppmux).
64  * The fragmented file features defined (only) in ISO Base Media are used by
65  * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
66  *
67  * A few properties (<link linkend="GstQTMux--movie-timescale">movie-timescale</link>,
68  * <link linkend="GstQTMux--trak-timescale">trak-timescale</link>) allow adjusting
69  * some technical parameters, which might be useful in (rare) cases to resolve
70  * 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 file,
74  * somewhat contrary to this usually being called "the header".
75  * However, a <link linkend="GstQTMux--faststart">faststart</link> file will
76  * (with some effort) arrange this to be located near start of the file,
77  * which then allows it e.g. to be played while downloading.
78  * Alternatively, rather than having one chunk of metadata at start (or end),
79  * there can be some metadata at start and most of the other data can be spread
80  * out into fragments of <link linkend="GstQTMux--fragment-duration">fragment-duration</link>.
81  * If such fragmented layout is intended for streaming purposes, then
82  * <link linkend="GstQTMux--streamable">streamable</link> allows foregoing to add
83  * index metadata (at the end of file).
84  *
85  * <link linkend="GstQTMux--dts-method">dts-method</link> allows selecting a
86  * method for managing input timestamps (stay tuned for 0.11 to have this
87  * automagically settled).  The default delta/duration method should handle nice
88  * (aka perfect streams) just fine, but may experience problems otherwise
89  * (e.g. input stream with re-ordered B-frames and/or with frame dropping).
90  * The re-ordering approach re-assigns incoming timestamps in ascending order
91  * to incoming buffers and offers an alternative in such cases.  In cases where
92  * that might fail, the remaining method can be tried, which is exact and
93  * according to specs, but might experience playback on not so spec-wise players.
94  * Note that this latter approach also requires one to enable
95  * <link linkend="GstQTMux--presentation-timestamp">presentation-timestamp</link>.
96  *
97  * <refsect2>
98  * <title>Example pipelines</title>
99  * |[
100  * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
101  * ]|
102  * Records a video stream captured from a v4l2 device and muxes it into a qt file.
103  * </refsect2>
104  *
105  * Last reviewed on 2010-12-03
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/audio/audio.h>
121 #include <gst/video/video.h>
122 #include <gst/tag/tag.h>
123
124 #include <sys/types.h>
125 #ifdef G_OS_WIN32
126 #include <io.h>                 /* lseek, open, close, read */
127 #undef lseek
128 #define lseek _lseeki64
129 #undef off_t
130 #define off_t guint64
131 #endif
132
133 #ifdef _MSC_VER
134 #define ftruncate g_win32_ftruncate
135 #endif
136
137 #ifdef HAVE_UNISTD_H
138 #  include <unistd.h>
139 #endif
140
141 #include "gstqtmux.h"
142
143 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
144 #define GST_CAT_DEFAULT gst_qt_mux_debug
145
146 enum
147 {
148   DTS_METHOD_DD,
149   DTS_METHOD_REORDER,
150   DTS_METHOD_ASC
151 };
152
153 static GType
154 gst_qt_mux_dts_method_get_type (void)
155 {
156   static GType gst_qt_mux_dts_method = 0;
157
158   if (!gst_qt_mux_dts_method) {
159     static const GEnumValue dts_methods[] = {
160       {DTS_METHOD_DD, "delta/duration", "dd"},
161       {DTS_METHOD_REORDER, "reorder", "reorder"},
162       {DTS_METHOD_ASC, "ascending", "asc"},
163       {0, NULL, NULL},
164     };
165
166     gst_qt_mux_dts_method =
167         g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
168   }
169
170   return gst_qt_mux_dts_method;
171 }
172
173 #define GST_TYPE_QT_MUX_DTS_METHOD \
174   (gst_qt_mux_dts_method_get_type ())
175
176 /* QTMux signals and args */
177 enum
178 {
179   /* FILL ME */
180   LAST_SIGNAL
181 };
182
183 enum
184 {
185   PROP_0,
186   PROP_MOVIE_TIMESCALE,
187   PROP_TRAK_TIMESCALE,
188   PROP_FAST_START,
189   PROP_FAST_START_TEMP_FILE,
190   PROP_MOOV_RECOV_FILE,
191   PROP_FRAGMENT_DURATION,
192   PROP_STREAMABLE,
193   PROP_DTS_METHOD,
194   PROP_DO_CTTS,
195 };
196
197 /* some spare for header size as well */
198 #define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)
199 #define MAX_TOLERATED_LATENESS          (GST_SECOND / 10)
200
201 #define DEFAULT_MOVIE_TIMESCALE         1000
202 #define DEFAULT_TRAK_TIMESCALE          0
203 #define DEFAULT_DO_CTTS                 TRUE
204 #define DEFAULT_FAST_START              FALSE
205 #define DEFAULT_FAST_START_TEMP_FILE    NULL
206 #define DEFAULT_MOOV_RECOV_FILE         NULL
207 #define DEFAULT_FRAGMENT_DURATION       0
208 #define DEFAULT_STREAMABLE              FALSE
209 #define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
210
211
212 static void gst_qt_mux_finalize (GObject * object);
213
214 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
215     GstStateChange transition);
216
217 /* property functions */
218 static void gst_qt_mux_set_property (GObject * object,
219     guint prop_id, const GValue * value, GParamSpec * pspec);
220 static void gst_qt_mux_get_property (GObject * object,
221     guint prop_id, GValue * value, GParamSpec * pspec);
222
223 /* pad functions */
224 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
225     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
226 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
227
228 /* event */
229 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
230     GstCollectData * data, GstEvent * event, gpointer user_data);
231
232 static GstFlowReturn gst_qt_mux_handle_buffer (GstCollectPads * pads,
233     GstCollectData * cdata, GstBuffer * buf, gpointer user_data);
234 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
235     GstBuffer * buf);
236
237 static GstElementClass *parent_class = NULL;
238
239 static void
240 gst_qt_mux_base_init (gpointer g_class)
241 {
242   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
243   GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
244   GstQTMuxClassParams *params;
245   GstPadTemplate *videosinktempl, *audiosinktempl, *srctempl;
246   gchar *longname, *description;
247
248   params =
249       (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
250       GST_QT_MUX_PARAMS_QDATA);
251   g_assert (params != NULL);
252
253   /* construct the element details struct */
254   longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
255   description = g_strdup_printf ("Multiplex audio and video into a %s file",
256       params->prop->long_name);
257   gst_element_class_set_static_metadata (element_class, longname,
258       "Codec/Muxer", description,
259       "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
260   g_free (longname);
261   g_free (description);
262
263   /* pad templates */
264   srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
265       GST_PAD_ALWAYS, params->src_caps);
266   gst_element_class_add_pad_template (element_class, srctempl);
267
268   if (params->audio_sink_caps) {
269     audiosinktempl = gst_pad_template_new ("audio_%u",
270         GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
271     gst_element_class_add_pad_template (element_class, audiosinktempl);
272   }
273
274   if (params->video_sink_caps) {
275     videosinktempl = gst_pad_template_new ("video_%u",
276         GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
277     gst_element_class_add_pad_template (element_class, videosinktempl);
278   }
279
280   klass->format = params->prop->format;
281 }
282
283 static void
284 gst_qt_mux_class_init (GstQTMuxClass * klass)
285 {
286   GObjectClass *gobject_class;
287   GstElementClass *gstelement_class;
288
289   gobject_class = (GObjectClass *) klass;
290   gstelement_class = (GstElementClass *) klass;
291
292   parent_class = g_type_class_peek_parent (klass);
293
294   gobject_class->finalize = gst_qt_mux_finalize;
295   gobject_class->get_property = gst_qt_mux_get_property;
296   gobject_class->set_property = gst_qt_mux_set_property;
297
298   g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
299       g_param_spec_uint ("movie-timescale", "Movie timescale",
300           "Timescale to use in the movie (units per second)",
301           1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
302           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
303   g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
304       g_param_spec_uint ("trak-timescale", "Track timescale",
305           "Timescale to use for the tracks (units per second, 0 is automatic)",
306           0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
307           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
308   g_object_class_install_property (gobject_class, PROP_DO_CTTS,
309       g_param_spec_boolean ("presentation-time",
310           "Include presentation-time info",
311           "Calculate and include presentation/composition time "
312           "(in addition to decoding time)", DEFAULT_DO_CTTS,
313           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
314   g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
315       g_param_spec_enum ("dts-method", "dts-method",
316           "Method to determine DTS time",
317           GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
318           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
319   g_object_class_install_property (gobject_class, PROP_FAST_START,
320       g_param_spec_boolean ("faststart", "Format file to faststart",
321           "If the file should be formatted for faststart (headers first)",
322           DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
323   g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
324       g_param_spec_string ("faststart-file", "File to use for storing buffers",
325           "File that will be used temporarily to store data from the stream "
326           "when creating a faststart file. If null a filepath will be "
327           "created automatically", DEFAULT_FAST_START_TEMP_FILE,
328           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
329   g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
330       g_param_spec_string ("moov-recovery-file",
331           "File to store data for posterior moov atom recovery",
332           "File to be used to store "
333           "data for moov atom making movie file recovery possible in case "
334           "of a crash during muxing. Null for disabled. (Experimental)",
335           DEFAULT_MOOV_RECOV_FILE,
336           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
337   g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
338       g_param_spec_uint ("fragment-duration", "Fragment duration",
339           "Fragment durations in ms (produce a fragmented file if > 0)",
340           0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
341           2000 : DEFAULT_FRAGMENT_DURATION,
342           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
343   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
344       g_param_spec_boolean ("streamable", "Streamable",
345           "If set to true, the output should be as if it is to be streamed "
346           "and hence no indexes written or duration written.",
347           DEFAULT_STREAMABLE,
348           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
349
350   gstelement_class->request_new_pad =
351       GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
352   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
353   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
354 }
355
356 static void
357 gst_qt_mux_pad_reset (GstQTPad * qtpad)
358 {
359   qtpad->fourcc = 0;
360   qtpad->is_out_of_order = FALSE;
361   qtpad->have_dts = FALSE;
362   qtpad->sample_size = 0;
363   qtpad->sync = FALSE;
364   qtpad->last_dts = 0;
365   qtpad->first_ts = GST_CLOCK_TIME_NONE;
366   qtpad->prepare_buf_func = NULL;
367   qtpad->avg_bitrate = 0;
368   qtpad->max_bitrate = 0;
369   qtpad->total_duration = 0;
370   qtpad->total_bytes = 0;
371
372   qtpad->buf_head = 0;
373   qtpad->buf_tail = 0;
374
375   if (qtpad->last_buf)
376     gst_buffer_replace (&qtpad->last_buf, NULL);
377
378   /* reference owned elsewhere */
379   qtpad->trak = NULL;
380
381   if (qtpad->traf) {
382     atom_traf_free (qtpad->traf);
383     qtpad->traf = NULL;
384   }
385   atom_array_clear (&qtpad->fragment_buffers);
386
387   /* reference owned elsewhere */
388   qtpad->tfra = NULL;
389 }
390
391 /*
392  * Takes GstQTMux back to its initial state
393  */
394 static void
395 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
396 {
397   GSList *walk;
398
399   qtmux->state = GST_QT_MUX_STATE_NONE;
400   qtmux->header_size = 0;
401   qtmux->mdat_size = 0;
402   qtmux->mdat_pos = 0;
403   qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
404   qtmux->video_pads = 0;
405   qtmux->audio_pads = 0;
406   qtmux->fragment_sequence = 0;
407
408   if (qtmux->ftyp) {
409     atom_ftyp_free (qtmux->ftyp);
410     qtmux->ftyp = NULL;
411   }
412   if (qtmux->moov) {
413     atom_moov_free (qtmux->moov);
414     qtmux->moov = NULL;
415   }
416   if (qtmux->mfra) {
417     atom_mfra_free (qtmux->mfra);
418     qtmux->mfra = NULL;
419   }
420   if (qtmux->fast_start_file) {
421     fclose (qtmux->fast_start_file);
422     g_remove (qtmux->fast_start_file_path);
423     qtmux->fast_start_file = NULL;
424   }
425   if (qtmux->moov_recov_file) {
426     fclose (qtmux->moov_recov_file);
427     qtmux->moov_recov_file = NULL;
428   }
429   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
430     AtomInfo *ainfo = (AtomInfo *) walk->data;
431     ainfo->free_func (ainfo->atom);
432     g_free (ainfo);
433   }
434   g_slist_free (qtmux->extra_atoms);
435   qtmux->extra_atoms = NULL;
436
437   GST_OBJECT_LOCK (qtmux);
438   gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
439   GST_OBJECT_UNLOCK (qtmux);
440
441   /* reset pad data */
442   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
443     GstQTPad *qtpad = (GstQTPad *) walk->data;
444     gst_qt_mux_pad_reset (qtpad);
445
446     /* hm, moov_free above yanked the traks away from us,
447      * so do not free, but do clear */
448     qtpad->trak = NULL;
449   }
450
451   if (alloc) {
452     qtmux->moov = atom_moov_new (qtmux->context);
453     /* ensure all is as nice and fresh as request_new_pad would provide it */
454     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
455       GstQTPad *qtpad = (GstQTPad *) walk->data;
456
457       qtpad->trak = atom_trak_new (qtmux->context);
458       atom_moov_add_trak (qtmux->moov, qtpad->trak);
459     }
460   }
461 }
462
463 static void
464 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
465 {
466   GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
467   GstPadTemplate *templ;
468
469   templ = gst_element_class_get_pad_template (klass, "src");
470   qtmux->srcpad = gst_pad_new_from_template (templ, "src");
471   gst_pad_use_fixed_caps (qtmux->srcpad);
472   gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
473
474   qtmux->sinkpads = NULL;
475   qtmux->collect = gst_collect_pads_new ();
476   gst_collect_pads_set_buffer_function (qtmux->collect,
477       GST_DEBUG_FUNCPTR (gst_qt_mux_handle_buffer), qtmux);
478   gst_collect_pads_set_event_function (qtmux->collect,
479       GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
480   gst_collect_pads_set_clip_function (qtmux->collect,
481       GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
482
483   /* properties set to default upon construction */
484
485   /* always need this */
486   qtmux->context =
487       atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
488
489   /* internals to initial state */
490   gst_qt_mux_reset (qtmux, TRUE);
491 }
492
493
494 static void
495 gst_qt_mux_finalize (GObject * object)
496 {
497   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
498
499   gst_qt_mux_reset (qtmux, FALSE);
500
501   g_free (qtmux->fast_start_file_path);
502   g_free (qtmux->moov_recov_file_path);
503
504   atoms_context_free (qtmux->context);
505   gst_object_unref (qtmux->collect);
506
507   g_slist_free (qtmux->sinkpads);
508
509   G_OBJECT_CLASS (parent_class)->finalize (object);
510 }
511
512 static GstBuffer *
513 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
514     GstQTMux * qtmux)
515 {
516   GstBuffer *newbuf;
517   GstMapInfo map;
518   gsize size;
519
520   GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
521
522   if (buf == NULL)
523     return NULL;
524
525   size = gst_buffer_get_size (buf);
526   newbuf = gst_buffer_new_and_alloc (size + 8);
527   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
528
529   gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
530   GST_WRITE_UINT32_BE (map.data, map.size);
531   GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
532
533   gst_buffer_unmap (buf, &map);
534   gst_buffer_unref (buf);
535
536   return newbuf;
537 }
538
539 static void
540 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
541     const char *tag, const char *tag2, guint32 fourcc)
542 {
543   switch (gst_tag_get_type (tag)) {
544       /* strings */
545     case G_TYPE_STRING:
546     {
547       gchar *str = NULL;
548
549       if (!gst_tag_list_get_string (list, tag, &str) || !str)
550         break;
551       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
552           GST_FOURCC_ARGS (fourcc), str);
553       atom_moov_add_str_tag (qtmux->moov, fourcc, str);
554       g_free (str);
555       break;
556     }
557       /* double */
558     case G_TYPE_DOUBLE:
559     {
560       gdouble value;
561
562       if (!gst_tag_list_get_double (list, tag, &value))
563         break;
564       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
565           GST_FOURCC_ARGS (fourcc), (gint) value);
566       atom_moov_add_uint_tag (qtmux->moov, fourcc, 21, (gint) value);
567       break;
568     }
569     case G_TYPE_UINT:
570     {
571       guint value = 0;
572       if (tag2) {
573         /* paired unsigned integers */
574         guint count = 0;
575         gboolean got_tag;
576
577         got_tag = gst_tag_list_get_uint (list, tag, &value);
578         got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
579         if (!got_tag)
580           break;
581         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
582             GST_FOURCC_ARGS (fourcc), value, count);
583         atom_moov_add_uint_tag (qtmux->moov, fourcc, 0,
584             value << 16 | (count & 0xFFFF));
585       } else {
586         /* unpaired unsigned integers */
587         if (!gst_tag_list_get_uint (list, tag, &value))
588           break;
589         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
590             GST_FOURCC_ARGS (fourcc), value);
591         atom_moov_add_uint_tag (qtmux->moov, fourcc, 1, value);
592       }
593       break;
594     }
595     default:
596       g_assert_not_reached ();
597       break;
598   }
599 }
600
601 static void
602 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
603     const char *tag, const char *tag2, guint32 fourcc)
604 {
605   GDate *date = NULL;
606   GDateYear year;
607   GDateMonth month;
608   GDateDay day;
609   gchar *str;
610
611   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
612
613   if (!gst_tag_list_get_date (list, tag, &date) || !date)
614     return;
615
616   year = g_date_get_year (date);
617   month = g_date_get_month (date);
618   day = g_date_get_day (date);
619
620   g_date_free (date);
621
622   if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
623       day == G_DATE_BAD_DAY) {
624     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
625     return;
626   }
627
628   str = g_strdup_printf ("%u-%u-%u", year, month, day);
629   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
630       GST_FOURCC_ARGS (fourcc), str);
631   atom_moov_add_str_tag (qtmux->moov, fourcc, str);
632   g_free (str);
633 }
634
635 static void
636 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
637     const char *tag, const char *tag2, guint32 fourcc)
638 {
639   GValue value = { 0, };
640   GstBuffer *buf;
641   GstSample *sample;
642   GstCaps *caps;
643   GstStructure *structure;
644   gint flags = 0;
645   GstMapInfo map;
646
647   g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
648
649   if (!gst_tag_list_copy_value (&value, list, tag))
650     return;
651
652   sample = gst_value_get_sample (&value);
653
654   if (!sample)
655     goto done;
656
657   buf = gst_sample_get_buffer (sample);
658   if (!buf)
659     goto done;
660
661   caps = gst_sample_get_caps (sample);
662   if (!caps) {
663     GST_WARNING_OBJECT (qtmux, "preview image without caps");
664     goto done;
665   }
666
667   GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
668
669   structure = gst_caps_get_structure (caps, 0);
670   if (gst_structure_has_name (structure, "image/jpeg"))
671     flags = 13;
672   else if (gst_structure_has_name (structure, "image/png"))
673     flags = 14;
674
675   if (!flags) {
676     GST_WARNING_OBJECT (qtmux, "preview image format not supported");
677     goto done;
678   }
679
680   gst_buffer_map (buf, &map, GST_MAP_READ);
681   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
682       " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
683   atom_moov_add_tag (qtmux->moov, fourcc, flags, map.data, map.size);
684   gst_buffer_unmap (buf, &map);
685 done:
686   g_value_unset (&value);
687 }
688
689 static void
690 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
691     const char *tag, const char *tag2, guint32 fourcc)
692 {
693   gchar *str = NULL;
694   guint number;
695
696   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
697   g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
698
699   if (!gst_tag_list_get_string (list, tag, &str) || !str)
700     return;
701
702   if (tag2)
703     if (!gst_tag_list_get_uint (list, tag2, &number))
704       tag2 = NULL;
705
706   if (!tag2) {
707     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
708         GST_FOURCC_ARGS (fourcc), str);
709     atom_moov_add_3gp_str_tag (qtmux->moov, fourcc, str);
710   } else {
711     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
712         GST_FOURCC_ARGS (fourcc), str, number);
713     atom_moov_add_3gp_str_int_tag (qtmux->moov, fourcc, str, number);
714   }
715
716   g_free (str);
717 }
718
719 static void
720 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
721     const char *tag, const char *tag2, guint32 fourcc)
722 {
723   GDate *date = NULL;
724   GDateYear year;
725
726   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
727
728   if (!gst_tag_list_get_date (list, tag, &date) || !date)
729     return;
730
731   year = g_date_get_year (date);
732
733   if (year == G_DATE_BAD_YEAR) {
734     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
735     return;
736   }
737
738   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
739       GST_FOURCC_ARGS (fourcc), year);
740   atom_moov_add_3gp_uint_tag (qtmux->moov, fourcc, year);
741 }
742
743 static void
744 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
745     const char *tag, const char *tag2, guint32 fourcc)
746 {
747   gdouble latitude = -360, longitude = -360, altitude = 0;
748   gchar *location = NULL;
749   guint8 *data, *ddata;
750   gint size = 0, len = 0;
751   gboolean ret = FALSE;
752
753   g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
754
755   ret = gst_tag_list_get_string (list, tag, &location);
756   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
757       &longitude);
758   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
759       &latitude);
760   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
761       &altitude);
762
763   if (!ret)
764     return;
765
766   if (location)
767     len = strlen (location);
768   size += len + 1 + 2;
769
770   /* role + (long, lat, alt) + body + notes */
771   size += 1 + 3 * 4 + 1 + 1;
772
773   data = ddata = g_malloc (size);
774
775   /* language tag */
776   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
777   /* location */
778   if (location)
779     memcpy (data + 2, location, len);
780   GST_WRITE_UINT8 (data + 2 + len, 0);
781   data += len + 1 + 2;
782   /* role */
783   GST_WRITE_UINT8 (data, 0);
784   /* long, lat, alt */
785 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
786   QT_WRITE_SFP32 (data + 1, longitude);
787   QT_WRITE_SFP32 (data + 5, latitude);
788   QT_WRITE_SFP32 (data + 9, altitude);
789   /* neither astronomical body nor notes */
790   GST_WRITE_UINT16_BE (data + 13, 0);
791
792   GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
793   atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
794   g_free (ddata);
795 }
796
797 static void
798 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
799     const char *tag, const char *tag2, guint32 fourcc)
800 {
801   gchar *keywords = NULL;
802   guint8 *data, *ddata;
803   gint size = 0, i;
804   gchar **kwds;
805
806   g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
807
808   if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
809     return;
810
811   kwds = g_strsplit (keywords, ",", 0);
812   g_free (keywords);
813
814   size = 0;
815   for (i = 0; kwds[i]; i++) {
816     /* size byte + null-terminator */
817     size += strlen (kwds[i]) + 1 + 1;
818   }
819
820   /* language tag + count + keywords */
821   size += 2 + 1;
822
823   data = ddata = g_malloc (size);
824
825   /* language tag */
826   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
827   /* count */
828   GST_WRITE_UINT8 (data + 2, i);
829   data += 3;
830   /* keywords */
831   for (i = 0; kwds[i]; ++i) {
832     gint len = strlen (kwds[i]);
833
834     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
835         GST_FOURCC_ARGS (fourcc), kwds[i]);
836     /* size */
837     GST_WRITE_UINT8 (data, len + 1);
838     memcpy (data + 1, kwds[i], len + 1);
839     data += len + 2;
840   }
841
842   g_strfreev (kwds);
843
844   atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
845   g_free (ddata);
846 }
847
848 static gboolean
849 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
850     guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
851 {
852   guint32 fourcc;
853   gint table;
854   gint size;
855   const gchar *data;
856
857   data = input;
858   size = strlen (input);
859
860   if (size < 4 + 3 + 1 + 1 + 1) {
861     /* at least the minimum xxxx://y/z */
862     GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
863         "ignoring", input);
864     return FALSE;
865   }
866
867   /* read the fourcc */
868   memcpy (&fourcc, data, 4);
869   size -= 4;
870   data += 4;
871
872   if (strncmp (data, "://", 3) != 0) {
873     goto mismatch;
874   }
875   data += 3;
876   size -= 3;
877
878   /* read the table number */
879   if (sscanf (data, "%d", &table) != 1) {
880     goto mismatch;
881   }
882   if (table < 0) {
883     GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
884         ", table numbers should be positive, ignoring tag", table);
885     return FALSE;
886   }
887
888   /* find the next / */
889   while (size > 0 && data[0] != '/') {
890     data += 1;
891     size -= 1;
892   }
893   if (size == 0) {
894     goto mismatch;
895   }
896   g_assert (data[0] == '/');
897
898   /* skip the '/' */
899   data += 1;
900   size -= 1;
901   if (size == 0) {
902     goto mismatch;
903   }
904
905   /* read up the rest of the string */
906   *p_content = g_strdup (data);
907   *p_table = (guint16) table;
908   *p_fourcc = fourcc;
909   return TRUE;
910
911 mismatch:
912   {
913     GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
914         "input (%s) didn't match the expected entitycode://table/content",
915         input);
916     return FALSE;
917   }
918 }
919
920 static void
921 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
922     const char *tag, const char *tag2, guint32 fourcc)
923 {
924   gchar *clsf_data = NULL;
925   gint size = 0;
926   guint32 entity = 0;
927   guint16 table = 0;
928   gchar *content = NULL;
929   guint8 *data;
930
931   g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
932
933   if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
934     return;
935
936   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
937       GST_FOURCC_ARGS (fourcc), clsf_data);
938
939   /* parse the string, format is:
940    * entityfourcc://table/content
941    */
942   gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
943       &content);
944   g_free (clsf_data);
945   /* +1 for the \0 */
946   size = strlen (content) + 1;
947
948   /* now we have everything, build the atom
949    * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
950   data = g_malloc (4 + 2 + 2 + size);
951   GST_WRITE_UINT32_LE (data, entity);
952   GST_WRITE_UINT16_BE (data + 4, (guint16) table);
953   GST_WRITE_UINT16_BE (data + 6, 0);
954   memcpy (data + 8, content, size);
955   g_free (content);
956
957   atom_moov_add_3gp_tag (qtmux->moov, fourcc, data, 4 + 2 + 2 + size);
958   g_free (data);
959 }
960
961 typedef void (*GstQTMuxAddTagFunc) (GstQTMux * mux, const GstTagList * list,
962     const char *tag, const char *tag2, guint32 fourcc);
963
964 /*
965  * Struct to record mappings from gstreamer tags to fourcc codes
966  */
967 typedef struct _GstTagToFourcc
968 {
969   guint32 fourcc;
970   const gchar *gsttag;
971   const gchar *gsttag2;
972   const GstQTMuxAddTagFunc func;
973 } GstTagToFourcc;
974
975 /* tag list tags to fourcc matching */
976 static const GstTagToFourcc tag_matches_mp4[] = {
977   {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
978   {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
979   {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
980   {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
981   {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
982   {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
983   {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
984   {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
985   {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
986   {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
987   {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
988   {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
989   {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
990   {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
991   {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
992   {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
993   {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
994   {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
995   {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
996   {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
997   {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
998   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
999   {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1000   {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1001   {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1002   {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1003       gst_qt_mux_add_mp4_tag},
1004   {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1005       gst_qt_mux_add_mp4_tag},
1006   {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1007   {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1008   {0, NULL,}
1009 };
1010
1011 static const GstTagToFourcc tag_matches_3gp[] = {
1012   {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1013   {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1014   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1015   {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1016   {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1017   {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1018   {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1019   {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1020   {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1021   {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1022   {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1023       gst_qt_mux_add_3gp_classification},
1024   {0, NULL,}
1025 };
1026
1027 /* qtdemux produces these for atoms it cannot parse */
1028 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1029
1030 static void
1031 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1032 {
1033   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1034   GstBuffer *xmp = NULL;
1035
1036   /* adobe specs only have 'quicktime' and 'mp4',
1037    * but I guess we can extrapolate to gpp.
1038    * Keep mj2 out for now as we don't add any tags for it yet.
1039    * If you have further info about xmp on these formats, please share */
1040   if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1041     return;
1042
1043   GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1044
1045   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1046     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1047         list, TRUE);
1048     if (xmp)
1049       atom_moov_add_xmp_tags (qtmux->moov, xmp);
1050   } else {
1051     AtomInfo *ainfo;
1052     /* for isom/mp4, it is a top level uuid atom */
1053     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1054         list, TRUE);
1055     if (xmp) {
1056       ainfo = build_uuid_xmp_atom (xmp);
1057       if (ainfo) {
1058         qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1059       }
1060     }
1061   }
1062   if (xmp)
1063     gst_buffer_unref (xmp);
1064 }
1065
1066 static void
1067 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list)
1068 {
1069   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1070   guint32 fourcc;
1071   gint i;
1072   const gchar *tag, *tag2;
1073   const GstTagToFourcc *tag_matches;
1074
1075   switch (qtmux_klass->format) {
1076     case GST_QT_MUX_FORMAT_3GP:
1077       tag_matches = tag_matches_3gp;
1078       break;
1079     case GST_QT_MUX_FORMAT_MJ2:
1080       tag_matches = NULL;
1081       break;
1082     default:
1083       /* sort of iTunes style for mp4 and QT (?) */
1084       tag_matches = tag_matches_mp4;
1085       break;
1086   }
1087
1088   if (!tag_matches)
1089     return;
1090
1091   for (i = 0; tag_matches[i].fourcc; i++) {
1092     fourcc = tag_matches[i].fourcc;
1093     tag = tag_matches[i].gsttag;
1094     tag2 = tag_matches[i].gsttag2;
1095
1096     g_assert (tag_matches[i].func);
1097     tag_matches[i].func (qtmux, list, tag, tag2, fourcc);
1098   }
1099
1100   /* add unparsed blobs if present */
1101   if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1102     guint num_tags;
1103
1104     num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1105     for (i = 0; i < num_tags; ++i) {
1106       GstSample *sample = NULL;
1107       GstBuffer *buf;
1108       const GstStructure *s;
1109
1110       if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1111               &sample))
1112         continue;
1113       buf = gst_sample_get_buffer (sample);
1114
1115       if (buf && (s = gst_sample_get_info (sample))) {
1116         const gchar *style = NULL;
1117         GstMapInfo map;
1118
1119         gst_buffer_map (buf, &map, GST_MAP_READ);
1120         GST_DEBUG_OBJECT (qtmux,
1121             "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1122             GST_PTR_FORMAT, i, num_tags, map.size, s);
1123         if (s && (style = gst_structure_get_string (s, "style"))) {
1124           /* try to prevent some style tag ending up into another variant
1125            * (todo: make into a list if more cases) */
1126           if ((strcmp (style, "itunes") == 0 &&
1127                   qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1128               (strcmp (style, "iso") == 0 &&
1129                   qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1130             GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1131             atom_moov_add_blob_tag (qtmux->moov, map.data, map.size);
1132           }
1133         }
1134         gst_buffer_unmap (buf, &map);
1135       }
1136     }
1137   }
1138
1139   return;
1140 }
1141
1142 /*
1143  * Gets the tagsetter iface taglist and puts the known tags
1144  * into the output stream
1145  */
1146 static void
1147 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1148 {
1149   const GstTagList *tags;
1150
1151   GST_OBJECT_LOCK (qtmux);
1152   tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1153   GST_OBJECT_UNLOCK (qtmux);
1154
1155   GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1156
1157   if (tags && !gst_tag_list_is_empty (tags)) {
1158     GstTagList *copy = gst_tag_list_copy (tags);
1159
1160     GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1161     gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1162     gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1163     gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1164
1165     GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1166     gst_qt_mux_add_metadata_tags (qtmux, copy);
1167     gst_qt_mux_add_xmp_tags (qtmux, copy);
1168     gst_tag_list_unref (copy);
1169   } else {
1170     GST_DEBUG_OBJECT (qtmux, "No tags received");
1171   }
1172 }
1173
1174 static inline GstBuffer *
1175 _gst_buffer_new_take_data (guint8 * data, guint size)
1176 {
1177   GstBuffer *buf;
1178
1179   buf = gst_buffer_new ();
1180   gst_buffer_append_memory (buf,
1181       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1182
1183   return buf;
1184 }
1185
1186 static GstFlowReturn
1187 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1188     gboolean mind_fast)
1189 {
1190   GstFlowReturn res;
1191   gsize size;
1192
1193   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1194
1195   size = gst_buffer_get_size (buf);
1196   GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1197
1198   if (mind_fast && qtmux->fast_start_file) {
1199     GstMapInfo map;
1200     gint ret;
1201
1202     GST_LOG_OBJECT (qtmux, "to temporary file");
1203     gst_buffer_map (buf, &map, GST_MAP_READ);
1204     ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1205     gst_buffer_unmap (buf, &map);
1206     gst_buffer_unref (buf);
1207     if (ret != size)
1208       goto write_error;
1209     else
1210       res = GST_FLOW_OK;
1211   } else {
1212     GST_LOG_OBJECT (qtmux, "downstream");
1213     res = gst_pad_push (qtmux->srcpad, buf);
1214   }
1215
1216   if (G_LIKELY (offset))
1217     *offset += size;
1218
1219   return res;
1220
1221   /* ERRORS */
1222 write_error:
1223   {
1224     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1225         ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1226     return GST_FLOW_ERROR;
1227   }
1228 }
1229
1230 static gboolean
1231 gst_qt_mux_seek_to_beginning (FILE * f)
1232 {
1233 #ifdef HAVE_FSEEKO
1234   if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1235     return FALSE;
1236 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1237   if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1238     return FALSE;
1239 #else
1240   if (fseek (f, (long) 0, SEEK_SET) != 0)
1241     return FALSE;
1242 #endif
1243   return TRUE;
1244 }
1245
1246 static GstFlowReturn
1247 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1248 {
1249   GstFlowReturn ret = GST_FLOW_OK;
1250   GstBuffer *buf = NULL;
1251
1252   if (fflush (qtmux->fast_start_file))
1253     goto flush_failed;
1254
1255   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1256     goto seek_failed;
1257
1258   /* hm, this could all take a really really long time,
1259    * but there may not be another way to get moov atom first
1260    * (somehow optimize copy?) */
1261   GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1262   while (ret == GST_FLOW_OK) {
1263     const int bufsize = 4096;
1264     GstMapInfo map;
1265     gsize size;
1266
1267     buf = gst_buffer_new_and_alloc (bufsize);
1268     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1269     size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1270     if (size == 0) {
1271       gst_buffer_unmap (buf, &map);
1272       break;
1273     }
1274     GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1275     gst_buffer_unmap (buf, &map);
1276     if (size != bufsize)
1277       gst_buffer_set_size (buf, size);
1278     ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1279     buf = NULL;
1280   }
1281   if (buf)
1282     gst_buffer_unref (buf);
1283
1284   if (ftruncate (fileno (qtmux->fast_start_file), 0))
1285     goto seek_failed;
1286   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1287     goto seek_failed;
1288
1289   return ret;
1290
1291   /* ERRORS */
1292 flush_failed:
1293   {
1294     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1295         ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1296     ret = GST_FLOW_ERROR;
1297     goto fail;
1298   }
1299 seek_failed:
1300   {
1301     GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1302         ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1303     ret = GST_FLOW_ERROR;
1304     goto fail;
1305   }
1306 fail:
1307   {
1308     /* clear descriptor so we don't remove temp file later on,
1309      * might be possible to recover */
1310     fclose (qtmux->fast_start_file);
1311     qtmux->fast_start_file = NULL;
1312     return ret;
1313   }
1314 }
1315
1316 /*
1317  * Sends the initial mdat atom fields (size fields and fourcc type),
1318  * the subsequent buffers are considered part of it's data.
1319  * As we can't predict the amount of data that we are going to place in mdat
1320  * we need to record the position of the size field in the stream so we can
1321  * seek back to it later and update when the streams have finished.
1322  */
1323 static GstFlowReturn
1324 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1325     gboolean extended)
1326 {
1327   Atom *node_header;
1328   GstBuffer *buf;
1329   guint8 *data = NULL;
1330   guint64 offset = 0;
1331
1332   GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1333       "size %" G_GUINT64_FORMAT, size);
1334
1335   node_header = g_malloc0 (sizeof (Atom));
1336   node_header->type = FOURCC_mdat;
1337   if (extended) {
1338     /* use extended size */
1339     node_header->size = 1;
1340     node_header->extended_size = 0;
1341     if (size)
1342       node_header->extended_size = size + 16;
1343   } else {
1344     node_header->size = size + 8;
1345   }
1346
1347   size = offset = 0;
1348   if (atom_copy_data (node_header, &data, &size, &offset) == 0)
1349     goto serialize_error;
1350
1351   buf = _gst_buffer_new_take_data (data, offset);
1352   g_free (node_header);
1353
1354   GST_LOG_OBJECT (qtmux, "Pushing mdat start");
1355   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1356
1357   /* ERRORS */
1358 serialize_error:
1359   {
1360     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1361         ("Failed to serialize mdat"));
1362     return GST_FLOW_ERROR;
1363   }
1364 }
1365
1366 /*
1367  * We get the position of the mdat size field, seek back to it
1368  * and overwrite with the real value
1369  */
1370 static GstFlowReturn
1371 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1372     guint64 mdat_size, guint64 * offset)
1373 {
1374   GstBuffer *buf;
1375   gboolean large_file;
1376   GstSegment segment;
1377   GstMapInfo map;
1378
1379   large_file = (mdat_size > MDAT_LARGE_FILE_LIMIT);
1380
1381   if (large_file)
1382     mdat_pos += 8;
1383
1384   /* seek and rewrite the header */
1385   gst_segment_init (&segment, GST_FORMAT_BYTES);
1386   segment.start = mdat_pos;
1387   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1388
1389   if (large_file) {
1390     buf = gst_buffer_new_and_alloc (sizeof (guint64));
1391     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1392     GST_WRITE_UINT64_BE (map.data, mdat_size + 16);
1393   } else {
1394     buf = gst_buffer_new_and_alloc (16);
1395     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1396     GST_WRITE_UINT32_BE (map.data, 8);
1397     GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1398     GST_WRITE_UINT32_BE (map.data + 8, mdat_size + 8);
1399     GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1400   }
1401   gst_buffer_unmap (buf, &map);
1402
1403   return gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1404 }
1405
1406 static GstFlowReturn
1407 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1408 {
1409   GstBuffer *buf;
1410   guint64 size = 0, offset = 0;
1411   guint8 *data = NULL;
1412
1413   GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1414
1415   if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1416     goto serialize_error;
1417
1418   buf = _gst_buffer_new_take_data (data, offset);
1419
1420   GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1421   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1422
1423   /* ERRORS */
1424 serialize_error:
1425   {
1426     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1427         ("Failed to serialize ftyp"));
1428     return GST_FLOW_ERROR;
1429   }
1430 }
1431
1432 static void
1433 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1434     GstBuffer ** p_prefix)
1435 {
1436   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1437   guint32 major, version;
1438   GList *comp;
1439   GstBuffer *prefix = NULL;
1440   AtomFTYP *ftyp = NULL;
1441
1442   GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1443
1444   /* init and send context and ftyp based on current property state */
1445   gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1446       &version, &comp, qtmux->moov, qtmux->longest_chunk,
1447       qtmux->fast_start_file != NULL);
1448   ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1449   if (comp)
1450     g_list_free (comp);
1451   if (prefix) {
1452     if (p_prefix)
1453       *p_prefix = prefix;
1454     else
1455       gst_buffer_unref (prefix);
1456   }
1457   *p_ftyp = ftyp;
1458 }
1459
1460 static GstFlowReturn
1461 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1462 {
1463   GstFlowReturn ret = GST_FLOW_OK;
1464   GstBuffer *prefix = NULL;
1465
1466   GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1467
1468   /* init and send context and ftyp based on current property state */
1469   if (qtmux->ftyp) {
1470     atom_ftyp_free (qtmux->ftyp);
1471     qtmux->ftyp = NULL;
1472   }
1473   gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1474   if (prefix) {
1475     ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1476     if (ret != GST_FLOW_OK)
1477       return ret;
1478   }
1479   return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1480 }
1481
1482 static void
1483 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1484 {
1485   GstStructure *structure;
1486   GValue array = { 0 };
1487   GValue value = { 0 };
1488   GstCaps *caps, *tcaps;
1489
1490   tcaps = gst_pad_get_current_caps (mux->srcpad);
1491   caps = gst_caps_copy (tcaps);
1492   gst_caps_unref (tcaps);
1493
1494   structure = gst_caps_get_structure (caps, 0);
1495
1496   g_value_init (&array, GST_TYPE_ARRAY);
1497
1498   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1499   g_value_init (&value, GST_TYPE_BUFFER);
1500   gst_value_take_buffer (&value, gst_buffer_ref (buf));
1501   gst_value_array_append_value (&array, &value);
1502   g_value_unset (&value);
1503
1504   gst_structure_set_value (structure, "streamheader", &array);
1505   g_value_unset (&array);
1506   gst_pad_set_caps (mux->srcpad, caps);
1507   gst_caps_unref (caps);
1508 }
1509
1510 static void
1511 gst_qt_mux_configure_moov (GstQTMux * qtmux, guint32 * _timescale)
1512 {
1513   gboolean fragmented;
1514   guint32 timescale;
1515
1516   GST_OBJECT_LOCK (qtmux);
1517   timescale = qtmux->timescale;
1518   fragmented = qtmux->fragment_sequence > 0;
1519   GST_OBJECT_UNLOCK (qtmux);
1520
1521   /* inform lower layers of our property wishes, and determine duration.
1522    * Let moov take care of this using its list of traks;
1523    * so that released pads are also included */
1524   GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1525       timescale);
1526   atom_moov_update_timescale (qtmux->moov, timescale);
1527   atom_moov_set_fragmented (qtmux->moov, fragmented);
1528
1529   atom_moov_update_duration (qtmux->moov);
1530
1531   if (_timescale)
1532     *_timescale = timescale;
1533 }
1534
1535 static GstFlowReturn
1536 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset, gboolean mind_fast)
1537 {
1538   guint64 offset = 0, size = 0;
1539   guint8 *data;
1540   GstBuffer *buf;
1541   GstFlowReturn ret = GST_FLOW_OK;
1542
1543   /* serialize moov */
1544   offset = size = 0;
1545   data = NULL;
1546   GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1547   if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1548     goto serialize_error;
1549
1550   buf = _gst_buffer_new_take_data (data, offset);
1551   GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1552   gst_qt_mux_set_header_on_caps (qtmux, buf);
1553   ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1554
1555   return ret;
1556
1557 serialize_error:
1558   {
1559     g_free (data);
1560     return GST_FLOW_ERROR;
1561   }
1562 }
1563
1564 /* either calculates size of extra atoms or pushes them */
1565 static GstFlowReturn
1566 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1567     gboolean mind_fast)
1568 {
1569   GSList *walk;
1570   guint64 loffset = 0, size = 0;
1571   guint8 *data;
1572   GstFlowReturn ret = GST_FLOW_OK;
1573
1574   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1575     AtomInfo *ainfo = (AtomInfo *) walk->data;
1576
1577     loffset = size = 0;
1578     data = NULL;
1579     if (!ainfo->copy_data_func (ainfo->atom,
1580             send ? &data : NULL, &size, &loffset))
1581       goto serialize_error;
1582
1583     if (send) {
1584       GstBuffer *buf;
1585
1586       GST_DEBUG_OBJECT (qtmux,
1587           "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1588           GST_FOURCC_ARGS (ainfo->atom->type));
1589       buf = _gst_buffer_new_take_data (data, loffset);
1590       ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1591       if (ret != GST_FLOW_OK)
1592         break;
1593     } else {
1594       if (offset)
1595         *offset += loffset;
1596     }
1597   }
1598
1599   return ret;
1600
1601 serialize_error:
1602   {
1603     g_free (data);
1604     return GST_FLOW_ERROR;
1605   }
1606 }
1607
1608 static GstFlowReturn
1609 gst_qt_mux_start_file (GstQTMux * qtmux)
1610 {
1611   GstFlowReturn ret = GST_FLOW_OK;
1612   GstCaps *caps;
1613   GstSegment segment;
1614   gchar s_id[32];
1615
1616   GST_DEBUG_OBJECT (qtmux, "starting file");
1617
1618   /* stream-start (FIXME: create id based on input ids) */
1619   g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
1620   gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
1621
1622   caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
1623   /* qtmux has structure with and without variant, remove all but the first */
1624   while (gst_caps_get_size (caps) > 1)
1625     gst_caps_remove_structure (caps, 1);
1626   gst_pad_set_caps (qtmux->srcpad, caps);
1627   gst_caps_unref (caps);
1628
1629   /* if not streaming, check if downstream is seekable */
1630   if (!qtmux->streamable) {
1631     gboolean seekable;
1632     GstQuery *query;
1633
1634     query = gst_query_new_seeking (GST_FORMAT_BYTES);
1635     if (gst_pad_peer_query (qtmux->srcpad, query)) {
1636       gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1637       GST_INFO_OBJECT (qtmux, "downstream is %sseekable",
1638           seekable ? "" : "not ");
1639     } else {
1640       /* have to assume seeking is supported if query not handled downstream */
1641       GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
1642       seekable = FALSE;
1643     }
1644     if (!seekable) {
1645       qtmux->streamable = TRUE;
1646       g_object_notify (G_OBJECT (qtmux), "streamable");
1647       GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
1648           "streamable=false. Will ignore that and create streamable output "
1649           "instead");
1650     }
1651     gst_query_unref (query);
1652   }
1653
1654   /* let downstream know we think in BYTES and expect to do seeking later on */
1655   gst_segment_init (&segment, GST_FORMAT_BYTES);
1656   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1657
1658   /* initialize our moov recovery file */
1659   GST_OBJECT_LOCK (qtmux);
1660   if (qtmux->moov_recov_file_path) {
1661     GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1662         qtmux->moov_recov_file_path);
1663     qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1664     if (qtmux->moov_recov_file == NULL) {
1665       GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1666           qtmux->moov_recov_file_path);
1667     } else {
1668       GSList *walk;
1669       gboolean fail = FALSE;
1670       AtomFTYP *ftyp = NULL;
1671       GstBuffer *prefix = NULL;
1672
1673       gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1674
1675       if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1676               qtmux->moov, qtmux->timescale,
1677               g_slist_length (qtmux->sinkpads))) {
1678         GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1679             "headers");
1680         fail = TRUE;
1681       }
1682
1683       atom_ftyp_free (ftyp);
1684       if (prefix)
1685         gst_buffer_unref (prefix);
1686
1687       for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1688         GstCollectData *cdata = (GstCollectData *) walk->data;
1689         GstQTPad *qpad = (GstQTPad *) cdata;
1690         /* write info for each stream */
1691         fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1692         if (fail) {
1693           GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1694               "file");
1695         }
1696       }
1697       if (fail) {
1698         /* cleanup */
1699         fclose (qtmux->moov_recov_file);
1700         qtmux->moov_recov_file = NULL;
1701         GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1702             "recover file, moov recovery won't work");
1703       }
1704     }
1705   }
1706   GST_OBJECT_UNLOCK (qtmux);
1707
1708   /* 
1709    * send mdat header if already needed, and mark position for later update.
1710    * We don't send ftyp now if we are on fast start mode, because we can
1711    * better fine tune using the information we gather to create the whole moov
1712    * atom.
1713    */
1714   if (qtmux->fast_start) {
1715     GST_OBJECT_LOCK (qtmux);
1716     qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1717     if (!qtmux->fast_start_file)
1718       goto open_failed;
1719     GST_OBJECT_UNLOCK (qtmux);
1720
1721     /* send a dummy buffer for preroll */
1722     ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1723     if (ret != GST_FLOW_OK)
1724       goto exit;
1725
1726   } else {
1727     ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1728     if (ret != GST_FLOW_OK) {
1729       goto exit;
1730     }
1731
1732     /* well, it's moov pos if fragmented ... */
1733     qtmux->mdat_pos = qtmux->header_size;
1734
1735     if (qtmux->fragment_duration) {
1736       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1737           qtmux->fragment_duration);
1738       /* also used as snapshot marker to indicate fragmented file */
1739       qtmux->fragment_sequence = 1;
1740       /* prepare moov and/or tags */
1741       gst_qt_mux_configure_moov (qtmux, NULL);
1742       gst_qt_mux_setup_metadata (qtmux);
1743       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1744       if (ret != GST_FLOW_OK)
1745         return ret;
1746       /* extra atoms */
1747       ret =
1748           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1749       if (ret != GST_FLOW_OK)
1750         return ret;
1751       /* prepare index */
1752       if (!qtmux->streamable)
1753         qtmux->mfra = atom_mfra_new (qtmux->context);
1754     } else {
1755       /* extended to ensure some spare space */
1756       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1757     }
1758   }
1759
1760 exit:
1761   return ret;
1762
1763   /* ERRORS */
1764 open_failed:
1765   {
1766     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1767         (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1768         GST_ERROR_SYSTEM);
1769     GST_OBJECT_UNLOCK (qtmux);
1770     return GST_FLOW_ERROR;
1771   }
1772 }
1773
1774 static GstFlowReturn
1775 gst_qt_mux_stop_file (GstQTMux * qtmux)
1776 {
1777   gboolean ret = GST_FLOW_OK;
1778   guint64 offset = 0, size = 0;
1779   GSList *walk;
1780   gboolean large_file;
1781   guint32 timescale;
1782   GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1783
1784   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1785
1786   /* pushing last buffers for each pad */
1787   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1788     GstCollectData *cdata = (GstCollectData *) walk->data;
1789     GstQTPad *qtpad = (GstQTPad *) cdata;
1790
1791     /* avoid add_buffer complaining if not negotiated
1792      * in which case no buffers either, so skipping */
1793     if (!qtpad->fourcc) {
1794       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
1795           GST_PAD_NAME (qtpad->collect.pad));
1796       continue;
1797     }
1798
1799     /* send last buffer; also flushes possibly queued buffers/ts */
1800     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1801         GST_PAD_NAME (qtpad->collect.pad));
1802     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1803     if (ret != GST_FLOW_OK) {
1804       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1805           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1806           gst_flow_get_name (ret));
1807     }
1808
1809     /* having flushed above, can check for buffers now */
1810     if (!GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
1811       GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1812           GST_PAD_NAME (qtpad->collect.pad));
1813       continue;
1814     }
1815
1816     /* determine max stream duration */
1817     if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1818         (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1819             qtpad->last_dts > first_ts)) {
1820       first_ts = qtpad->last_dts;
1821     }
1822
1823     /* update average bitrate of streams if needed */
1824     {
1825       guint32 avgbitrate = 0;
1826       guint32 maxbitrate = qtpad->max_bitrate;
1827
1828       if (qtpad->avg_bitrate)
1829         avgbitrate = qtpad->avg_bitrate;
1830       else if (qtpad->total_duration > 0)
1831         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
1832             8 * GST_SECOND, qtpad->total_duration);
1833
1834       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
1835     }
1836   }
1837
1838   if (qtmux->fragment_sequence) {
1839     GstSegment segment;
1840
1841     if (qtmux->mfra) {
1842       guint8 *data = NULL;
1843       GstBuffer *buf;
1844
1845       size = offset = 0;
1846       GST_DEBUG_OBJECT (qtmux, "adding mfra");
1847       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1848         goto serialize_error;
1849       buf = _gst_buffer_new_take_data (data, offset);
1850       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1851       if (ret != GST_FLOW_OK)
1852         return ret;
1853     } else {
1854       /* must have been streamable; no need to write duration */
1855       GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1856       return GST_FLOW_OK;
1857     }
1858
1859     timescale = qtmux->timescale;
1860     /* only mvex duration is updated,
1861      * mvhd should be consistent with empty moov
1862      * (but TODO maybe some clients do not handle that well ?) */
1863     qtmux->moov->mvex.mehd.fragment_duration =
1864         gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1865     GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1866         GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1867     /* seek and rewrite the header */
1868     gst_segment_init (&segment, GST_FORMAT_BYTES);
1869     segment.start = qtmux->mdat_pos;
1870     gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1871     /* no need to seek back */
1872     return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1873   }
1874
1875   gst_qt_mux_configure_moov (qtmux, &timescale);
1876
1877   /* check for late streams */
1878   first_ts = GST_CLOCK_TIME_NONE;
1879   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1880     GstCollectData *cdata = (GstCollectData *) walk->data;
1881     GstQTPad *qtpad = (GstQTPad *) cdata;
1882
1883     if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1884         (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1885             qtpad->first_ts < first_ts)) {
1886       first_ts = qtpad->first_ts;
1887     }
1888   }
1889   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1890       GST_TIME_ARGS (first_ts));
1891   /* add EDTSs for late streams */
1892   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1893     GstCollectData *cdata = (GstCollectData *) walk->data;
1894     GstQTPad *qtpad = (GstQTPad *) cdata;
1895     guint32 lateness;
1896     guint32 duration;
1897
1898     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1899         qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1900       GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1901           GST_PAD_NAME (qtpad->collect.pad),
1902           GST_TIME_ARGS (qtpad->first_ts - first_ts));
1903       lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1904           timescale, GST_SECOND);
1905       duration = qtpad->trak->tkhd.duration;
1906       atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1907           (guint32) (1 * 65536.0));
1908       atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1909           (guint32) (1 * 65536.0));
1910
1911       /* need to add the empty time to the trak duration */
1912       qtpad->trak->tkhd.duration += lateness;
1913     }
1914   }
1915
1916   /* tags into file metadata */
1917   gst_qt_mux_setup_metadata (qtmux);
1918
1919   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1920   /* if faststart, update the offset of the atoms in the movie with the offset
1921    * that the movie headers before mdat will cause.
1922    * Also, send the ftyp */
1923   if (qtmux->fast_start_file) {
1924     GstFlowReturn flow_ret;
1925     offset = size = 0;
1926
1927     flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1928     if (flow_ret != GST_FLOW_OK) {
1929       goto ftyp_error;
1930     }
1931     /* copy into NULL to obtain size */
1932     if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1933       goto serialize_error;
1934     GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1935         offset);
1936     offset += qtmux->header_size + (large_file ? 16 : 8);
1937
1938     /* sum up with the extra atoms size */
1939     ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1940     if (ret != GST_FLOW_OK)
1941       return ret;
1942   } else {
1943     offset = qtmux->header_size;
1944   }
1945   atom_moov_chunks_add_offset (qtmux->moov, offset);
1946
1947   /* moov */
1948   /* note: as of this point, we no longer care about tracking written data size,
1949    * since there is no more use for it anyway */
1950   ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1951   if (ret != GST_FLOW_OK)
1952     return ret;
1953
1954   /* extra atoms */
1955   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1956   if (ret != GST_FLOW_OK)
1957     return ret;
1958
1959   /* if needed, send mdat atom and move buffered data into it */
1960   if (qtmux->fast_start_file) {
1961     /* mdat_size = accumulated (buffered data) */
1962     ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1963         large_file);
1964     if (ret != GST_FLOW_OK)
1965       return ret;
1966     ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1967     if (ret != GST_FLOW_OK)
1968       return ret;
1969   } else {
1970     /* mdat needs update iff not using faststart */
1971     GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1972     ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1973         qtmux->mdat_size, NULL);
1974     /* note; no seeking back to the end of file is done,
1975      * since we no longer write anything anyway */
1976   }
1977
1978   return ret;
1979
1980   /* ERRORS */
1981 serialize_error:
1982   {
1983     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1984         ("Failed to serialize moov"));
1985     return GST_FLOW_ERROR;
1986   }
1987 ftyp_error:
1988   {
1989     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1990     return GST_FLOW_ERROR;
1991   }
1992 }
1993
1994 static GstFlowReturn
1995 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
1996     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
1997     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
1998 {
1999   GstFlowReturn ret = GST_FLOW_OK;
2000
2001   /* setup if needed */
2002   if (G_UNLIKELY (!pad->traf || force))
2003     goto init;
2004
2005 flush:
2006   /* flush pad fragment if threshold reached,
2007    * or at new keyframe if we should be minding those in the first place */
2008   if (G_UNLIKELY (force || (sync && pad->sync) ||
2009           pad->fragment_duration < (gint64) delta)) {
2010     AtomMOOF *moof;
2011     guint64 size = 0, offset = 0;
2012     guint8 *data = NULL;
2013     GstBuffer *buffer;
2014     guint i, total_size;
2015
2016     /* now we know where moof ends up, update offset in tfra */
2017     if (pad->tfra)
2018       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2019
2020     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2021     /* takes ownership */
2022     atom_moof_add_traf (moof, pad->traf);
2023     pad->traf = NULL;
2024     atom_moof_copy_data (moof, &data, &size, &offset);
2025     buffer = _gst_buffer_new_take_data (data, offset);
2026     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2027         gst_buffer_get_size (buffer));
2028     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2029
2030     /* and actual data */
2031     total_size = 0;
2032     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2033       total_size +=
2034           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2035     }
2036
2037     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2038         atom_array_get_len (&pad->fragment_buffers), total_size);
2039     if (ret == GST_FLOW_OK)
2040       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2041           FALSE);
2042     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2043       if (G_LIKELY (ret == GST_FLOW_OK))
2044         ret = gst_qt_mux_send_buffer (qtmux,
2045             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2046             FALSE);
2047       else
2048         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2049     }
2050
2051     atom_array_clear (&pad->fragment_buffers);
2052     atom_moof_free (moof);
2053     qtmux->fragment_sequence++;
2054     force = FALSE;
2055   }
2056
2057 init:
2058   if (G_UNLIKELY (!pad->traf)) {
2059     GST_LOG_OBJECT (qtmux, "setting up new fragment");
2060     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2061     atom_array_init (&pad->fragment_buffers, 512);
2062     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2063         atom_trak_get_timescale (pad->trak), 1000);
2064
2065     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2066       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2067       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2068     }
2069   }
2070
2071   /* add buffer and metadata */
2072   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2073       pad->sync && sync);
2074   atom_array_append (&pad->fragment_buffers, buf, 256);
2075   pad->fragment_duration -= delta;
2076
2077   if (pad->tfra) {
2078     guint32 sn = atom_traf_get_sample_num (pad->traf);
2079
2080     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2081       atom_tfra_add_entry (pad->tfra, dts, sn);
2082   }
2083
2084   if (G_UNLIKELY (force))
2085     goto flush;
2086
2087   return ret;
2088 }
2089
2090 static void
2091 check_and_subtract_ts (GstQTMux * qtmux, GstClockTime * ts_a, GstClockTime ts_b)
2092 {
2093   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (*ts_a))) {
2094     if (G_LIKELY (*ts_a >= ts_b)) {
2095       *ts_a -= ts_b;
2096     } else {
2097       *ts_a = 0;
2098       GST_WARNING_OBJECT (qtmux, "Subtraction would result in negative value, "
2099           "using 0 as result");
2100     }
2101   }
2102 }
2103
2104 /*
2105  * Here we push the buffer and update the tables in the track atoms
2106  */
2107 static GstFlowReturn
2108 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2109 {
2110   GstBuffer *last_buf = NULL;
2111   GstClockTime duration;
2112   guint nsamples, sample_size;
2113   guint64 chunk_offset;
2114   gint64 last_dts, scaled_duration;
2115   gint64 pts_offset = 0;
2116   gboolean sync = FALSE, do_pts = FALSE;
2117   GstFlowReturn ret = GST_FLOW_OK;
2118
2119   if (!pad->fourcc)
2120     goto not_negotiated;
2121
2122   /* if this pad has a prepare function, call it */
2123   if (pad->prepare_buf_func != NULL) {
2124     buf = pad->prepare_buf_func (pad, buf, qtmux);
2125   }
2126
2127   if (G_LIKELY (buf != NULL && GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
2128           pad->first_ts != 0)) {
2129     buf = gst_buffer_make_writable (buf);
2130     check_and_subtract_ts (qtmux, &GST_BUFFER_DTS (buf), pad->first_ts);
2131     check_and_subtract_ts (qtmux, &GST_BUFFER_PTS (buf), pad->first_ts);
2132   }
2133
2134   last_buf = pad->last_buf;
2135
2136   if (last_buf == NULL) {
2137 #ifndef GST_DISABLE_GST_DEBUG
2138     if (buf == NULL) {
2139       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
2140           "received NULL buffer, doing nothing",
2141           GST_PAD_NAME (pad->collect.pad));
2142     } else {
2143       GST_LOG_OBJECT (qtmux,
2144           "Pad %s has no previous buffer stored, storing now",
2145           GST_PAD_NAME (pad->collect.pad));
2146     }
2147 #endif
2148     pad->last_buf = buf;
2149     goto exit;
2150   } else
2151     gst_buffer_ref (last_buf);
2152
2153   /* if this is the first buffer, store the timestamp */
2154   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2155     if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_PTS (last_buf))) {
2156       pad->first_ts = GST_BUFFER_PTS (last_buf);
2157       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
2158       check_and_subtract_ts (qtmux, &GST_BUFFER_DTS (last_buf), pad->first_ts);
2159       check_and_subtract_ts (qtmux, &GST_BUFFER_PTS (last_buf), pad->first_ts);
2160       check_and_subtract_ts (qtmux, &GST_BUFFER_DTS (buf), pad->first_ts);
2161       check_and_subtract_ts (qtmux, &GST_BUFFER_PTS (buf), pad->first_ts);
2162     } else {
2163       GST_ERROR_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2164           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2165       pad->first_ts = 0;
2166     }
2167     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2168         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2169         GST_TIME_ARGS (pad->first_ts));
2170
2171   }
2172
2173   if (last_buf && buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
2174       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
2175       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
2176     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
2177         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2178         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
2179     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
2180   }
2181
2182   duration = GST_BUFFER_DURATION (last_buf);
2183
2184   /* for computing the avg bitrate */
2185   if (G_LIKELY (last_buf)) {
2186     pad->total_bytes += gst_buffer_get_size (last_buf);
2187     pad->total_duration += duration;
2188   }
2189
2190   gst_buffer_replace (&pad->last_buf, buf);
2191
2192   last_dts = gst_util_uint64_scale_round (pad->last_dts,
2193       atom_trak_get_timescale (pad->trak), GST_SECOND);
2194
2195   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2196   if (pad->sample_size && !qtmux->fragment_sequence) {
2197     /* Constant size packets: usually raw audio (with many samples per
2198        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2199      */
2200     sample_size = pad->sample_size;
2201     if (gst_buffer_get_size (last_buf) % sample_size != 0)
2202       goto fragmented_sample;
2203     /* note: qt raw audio storage warps it implicitly into a timewise
2204      * perfect stream, discarding buffer times */
2205     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2206       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2207           atom_trak_get_timescale (pad->trak), GST_SECOND);
2208     } else {
2209       nsamples = gst_buffer_get_size (last_buf) / sample_size;
2210     }
2211     duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2212
2213     /* timescale = samplerate */
2214     scaled_duration = 1;
2215     pad->last_dts += duration * nsamples;
2216   } else {
2217     nsamples = 1;
2218     sample_size = gst_buffer_get_size (last_buf);
2219     if (pad->have_dts) {
2220       gint64 scaled_dts;
2221       if (pad->last_buf) {
2222         pad->last_dts = GST_BUFFER_DTS (pad->last_buf);
2223       } else {
2224         pad->last_dts = GST_BUFFER_DTS (last_buf) +
2225             GST_BUFFER_DURATION (last_buf);
2226       }
2227       if ((gint64) (pad->last_dts) < 0) {
2228         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2229             atom_trak_get_timescale (pad->trak), GST_SECOND);
2230       } else {
2231         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2232             atom_trak_get_timescale (pad->trak), GST_SECOND);
2233       }
2234       scaled_duration = scaled_dts - last_dts;
2235       last_dts = scaled_dts;
2236     } else {
2237       /* first convert intended timestamp (in GstClockTime resolution) to
2238        * trak timescale, then derive delta;
2239        * this ensures sums of (scale)delta add up to converted timestamp,
2240        * which only deviates at most 1/scale from timestamp itself */
2241       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2242           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2243       pad->last_dts += duration;
2244     }
2245   }
2246   chunk_offset = qtmux->mdat_size;
2247
2248   GST_LOG_OBJECT (qtmux,
2249       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2250       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2251   GST_LOG_OBJECT (qtmux,
2252       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2253       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2254       nsamples, scaled_duration, sample_size, chunk_offset);
2255
2256   /* might be a sync sample */
2257   if (pad->sync &&
2258       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2259     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2260         GST_PAD_NAME (pad->collect.pad));
2261     sync = TRUE;
2262   }
2263
2264   if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf))) {
2265     do_pts = TRUE;
2266     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
2267         atom_trak_get_timescale (pad->trak), GST_SECOND);
2268     pts_offset =
2269         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
2270             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
2271
2272   } else {
2273     pts_offset = 0;
2274     do_pts = TRUE;
2275     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
2276         atom_trak_get_timescale (pad->trak), GST_SECOND);
2277   }
2278   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
2279       " timebase_dts: %d pts_offset: %d",
2280       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
2281       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
2282       (int) (last_dts), (int) (pts_offset));
2283
2284   /*
2285    * Each buffer starts a new chunk, so we can assume the buffer
2286    * duration is the chunk duration
2287    */
2288   if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2289           !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2290     GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2291         ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2292     qtmux->longest_chunk = duration;
2293   }
2294
2295   /* now we go and register this buffer/sample all over */
2296   /* note that a new chunk is started each time (not fancy but works) */
2297   if (qtmux->moov_recov_file) {
2298     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2299             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2300             do_pts, pts_offset)) {
2301       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2302           "recovery file, disabling recovery");
2303       fclose (qtmux->moov_recov_file);
2304       qtmux->moov_recov_file = NULL;
2305     }
2306   }
2307
2308   if (buf)
2309     gst_buffer_unref (buf);
2310
2311   if (qtmux->fragment_sequence) {
2312     /* ensure that always sync samples are marked as such */
2313     ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2314         buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2315         !pad->sync || sync, pts_offset);
2316   } else {
2317     atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2318         sample_size, chunk_offset, sync, pts_offset);
2319     ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2320   }
2321
2322 exit:
2323
2324   return ret;
2325
2326   /* ERRORS */
2327 bail:
2328   {
2329     if (buf)
2330       gst_buffer_unref (buf);
2331     gst_buffer_unref (last_buf);
2332     return GST_FLOW_ERROR;
2333   }
2334 fragmented_sample:
2335   {
2336     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2337         ("Audio buffer contains fragmented sample."));
2338     goto bail;
2339   }
2340 not_negotiated:
2341   {
2342     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2343         ("format wasn't negotiated before buffer flow on pad %s",
2344             GST_PAD_NAME (pad->collect.pad)));
2345     if (buf)
2346       gst_buffer_unref (buf);
2347     return GST_FLOW_NOT_NEGOTIATED;
2348   }
2349 }
2350
2351 static GstFlowReturn
2352 gst_qt_mux_handle_buffer (GstCollectPads * pads, GstCollectData * cdata,
2353     GstBuffer * buf, gpointer user_data)
2354 {
2355   GstFlowReturn ret = GST_FLOW_OK;
2356   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2357   GstQTPad *best_pad = NULL;
2358   GstClockTime best_time = GST_CLOCK_TIME_NONE;
2359
2360   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2361     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2362       return ret;
2363     else
2364       qtmux->state = GST_QT_MUX_STATE_DATA;
2365   }
2366
2367   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2368     return GST_FLOW_EOS;
2369
2370   best_pad = (GstQTPad *) cdata;
2371
2372   /* clipping already converted to running time */
2373   if (best_pad != NULL) {
2374     g_assert (buf);
2375     best_time = GST_BUFFER_PTS (buf);
2376     GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2377         GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2378     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2379   } else {
2380     ret = gst_qt_mux_stop_file (qtmux);
2381     if (ret == GST_FLOW_OK) {
2382       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2383       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2384       ret = GST_FLOW_EOS;
2385     } else {
2386       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2387           gst_flow_get_name (ret));
2388     }
2389     qtmux->state = GST_QT_MUX_STATE_EOS;
2390   }
2391
2392   return ret;
2393 }
2394
2395 static gboolean
2396 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2397 {
2398   GstStructure *structure = (GstStructure *) user_data;
2399   const GValue *other = gst_structure_id_get_value (structure, field_id);
2400   if (other == NULL)
2401     return FALSE;
2402   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2403 }
2404
2405 static gboolean
2406 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2407     GstCaps * superset)
2408 {
2409   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2410   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2411
2412   return gst_structure_foreach (sub_s, check_field, sup_s);
2413 }
2414
2415 static gboolean
2416 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2417 {
2418   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2419   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2420   GstQTPad *qtpad = NULL;
2421   GstStructure *structure;
2422   const gchar *mimetype;
2423   gint rate, channels;
2424   const GValue *value = NULL;
2425   const GstBuffer *codec_data = NULL;
2426   GstQTMuxFormat format;
2427   AudioSampleEntry entry = { 0, };
2428   AtomInfo *ext_atom = NULL;
2429   gint constant_size = 0;
2430   const gchar *stream_format;
2431
2432   /* find stream data */
2433   qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2434   g_assert (qtpad);
2435
2436   qtpad->prepare_buf_func = NULL;
2437
2438   /* does not go well to renegotiate stream mid-way, unless
2439    * the old caps are a subset of the new one (this means upstream
2440    * added more info to the caps, as both should be 'fixed' caps) */
2441   if (qtpad->fourcc) {
2442     GstCaps *current_caps;
2443
2444     current_caps = gst_pad_get_current_caps (pad);
2445     g_assert (caps != NULL);
2446
2447     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2448       gst_caps_unref (current_caps);
2449       goto refuse_renegotiation;
2450     }
2451     GST_DEBUG_OBJECT (qtmux,
2452         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2453         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2454     gst_caps_unref (current_caps);
2455   }
2456
2457   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2458       GST_DEBUG_PAD_NAME (pad), caps);
2459
2460   format = qtmux_klass->format;
2461   structure = gst_caps_get_structure (caps, 0);
2462   mimetype = gst_structure_get_name (structure);
2463
2464   /* common info */
2465   if (!gst_structure_get_int (structure, "channels", &channels) ||
2466       !gst_structure_get_int (structure, "rate", &rate)) {
2467     goto refuse_caps;
2468   }
2469
2470   /* optional */
2471   value = gst_structure_get_value (structure, "codec_data");
2472   if (value != NULL)
2473     codec_data = gst_value_get_buffer (value);
2474
2475   qtpad->is_out_of_order = FALSE;
2476   qtpad->have_dts = FALSE;
2477
2478   /* set common properties */
2479   entry.sample_rate = rate;
2480   entry.channels = channels;
2481   /* default */
2482   entry.sample_size = 16;
2483   /* this is the typical compressed case */
2484   if (format == GST_QT_MUX_FORMAT_QT) {
2485     entry.version = 1;
2486     entry.compression_id = -2;
2487   }
2488
2489   /* now map onto a fourcc, and some extra properties */
2490   if (strcmp (mimetype, "audio/mpeg") == 0) {
2491     gint mpegversion = 0;
2492     gint layer = -1;
2493
2494     gst_structure_get_int (structure, "mpegversion", &mpegversion);
2495     switch (mpegversion) {
2496       case 1:
2497         gst_structure_get_int (structure, "layer", &layer);
2498         switch (layer) {
2499           case 3:
2500             /* mp3 */
2501             /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2502             if (format == GST_QT_MUX_FORMAT_QT)
2503               entry.fourcc = FOURCC__mp3;
2504             else {
2505               entry.fourcc = FOURCC_mp4a;
2506               ext_atom =
2507                   build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2508                   ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2509                   qtpad->max_bitrate);
2510             }
2511             entry.samples_per_packet = 1152;
2512             entry.bytes_per_sample = 2;
2513             break;
2514         }
2515         break;
2516       case 4:
2517
2518         /* check stream-format */
2519         stream_format = gst_structure_get_string (structure, "stream-format");
2520         if (stream_format) {
2521           if (strcmp (stream_format, "raw") != 0) {
2522             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2523                 "please use 'raw'", stream_format);
2524             goto refuse_caps;
2525           }
2526         } else {
2527           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2528               "assuming 'raw'");
2529         }
2530
2531         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
2532           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2533         else {
2534           guint8 profile;
2535
2536           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
2537           /* warn if not Low Complexity profile */
2538           profile >>= 3;
2539           if (profile != 2)
2540             GST_WARNING_OBJECT (qtmux,
2541                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2542         }
2543
2544         /* AAC */
2545         entry.fourcc = FOURCC_mp4a;
2546
2547         if (format == GST_QT_MUX_FORMAT_QT)
2548           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2549               qtpad->avg_bitrate, qtpad->max_bitrate);
2550         else
2551           ext_atom =
2552               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2553               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2554               qtpad->max_bitrate);
2555         break;
2556       default:
2557         break;
2558     }
2559   } else if (strcmp (mimetype, "audio/AMR") == 0) {
2560     entry.fourcc = FOURCC_samr;
2561     entry.sample_size = 16;
2562     entry.samples_per_packet = 160;
2563     entry.bytes_per_sample = 2;
2564     ext_atom = build_amr_extension ();
2565   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2566     entry.fourcc = FOURCC_sawb;
2567     entry.sample_size = 16;
2568     entry.samples_per_packet = 320;
2569     entry.bytes_per_sample = 2;
2570     ext_atom = build_amr_extension ();
2571   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
2572     GstAudioInfo info;
2573
2574     gst_audio_info_init (&info);
2575     if (!gst_audio_info_from_caps (&info, caps))
2576       goto refuse_caps;
2577
2578     /* spec has no place for a distinction in these */
2579     if (info.finfo->width != info.finfo->depth) {
2580       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2581       goto refuse_caps;
2582     }
2583
2584     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
2585       if (info.finfo->endianness == G_LITTLE_ENDIAN)
2586         entry.fourcc = FOURCC_sowt;
2587       else if (info.finfo->endianness == G_BIG_ENDIAN)
2588         entry.fourcc = FOURCC_twos;
2589       /* maximum backward compatibility; only new version for > 16 bit */
2590       if (info.finfo->depth <= 16)
2591         entry.version = 0;
2592       /* not compressed in any case */
2593       entry.compression_id = 0;
2594       /* QT spec says: max at 16 bit even if sample size were actually larger,
2595        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2596       entry.sample_size = info.finfo->depth;
2597       entry.bytes_per_sample = info.finfo->depth / 8;
2598       entry.samples_per_packet = 1;
2599       entry.bytes_per_packet = info.finfo->depth / 8;
2600       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
2601     } else {
2602       if (info.finfo->width == 8 && info.finfo->depth == 8) {
2603         /* fall back to old 8-bit version */
2604         entry.fourcc = FOURCC_raw_;
2605         entry.version = 0;
2606         entry.compression_id = 0;
2607         entry.sample_size = 8;
2608       } else {
2609         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2610         goto refuse_caps;
2611       }
2612     }
2613     constant_size = (info.finfo->depth / 8) * info.channels;
2614   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2615     entry.fourcc = FOURCC_alaw;
2616     entry.samples_per_packet = 1023;
2617     entry.bytes_per_sample = 2;
2618   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2619     entry.fourcc = FOURCC_ulaw;
2620     entry.samples_per_packet = 1023;
2621     entry.bytes_per_sample = 2;
2622   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2623     gint blocksize;
2624     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2625       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2626       goto refuse_caps;
2627     }
2628     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2629        0x11 */
2630     entry.fourcc = MS_WAVE_FOURCC (0x11);
2631     /* 4 byte header per channel (including one sample). 2 samples per byte
2632        remaining. Simplifying gives the following (samples per block per
2633        channel) */
2634     entry.samples_per_packet = 2 * blocksize / channels - 7;
2635     entry.bytes_per_sample = 2;
2636
2637     entry.bytes_per_frame = blocksize;
2638     entry.bytes_per_packet = blocksize / channels;
2639     /* ADPCM has constant size packets */
2640     constant_size = 1;
2641     /* TODO: I don't really understand why this helps, but it does! Constant
2642      * size and compression_id of -2 seem to be incompatible, and other files
2643      * in the wild use this too. */
2644     entry.compression_id = -1;
2645
2646     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2647   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2648     GstBuffer *codec_config;
2649     gint len;
2650     GstMapInfo map;
2651
2652     entry.fourcc = FOURCC_alac;
2653     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
2654     /* let's check if codec data already comes with 'alac' atom prefix */
2655     if (!codec_data || (len = map.size) < 28) {
2656       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2657       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2658       goto refuse_caps;
2659     }
2660     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
2661       len -= 8;
2662       codec_config =
2663           gst_buffer_copy_region ((GstBuffer *) codec_data, 0, 8, len);
2664     } else {
2665       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2666     }
2667     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2668     if (len != 28) {
2669       /* does not look good, but perhaps some trailing unneeded stuff */
2670       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2671     }
2672     if (format == GST_QT_MUX_FORMAT_QT)
2673       ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2674     else
2675       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2676     /* set some more info */
2677     gst_buffer_map (codec_config, &map, GST_MAP_READ);
2678     entry.bytes_per_sample = 2;
2679     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
2680     gst_buffer_unmap (codec_config, &map);
2681     gst_buffer_unref (codec_config);
2682   }
2683
2684   if (!entry.fourcc)
2685     goto refuse_caps;
2686
2687   /* ok, set the pad info accordingly */
2688   qtpad->fourcc = entry.fourcc;
2689   qtpad->sample_size = constant_size;
2690   atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2691       qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2692       ext_atom, constant_size);
2693
2694   gst_object_unref (qtmux);
2695   return TRUE;
2696
2697   /* ERRORS */
2698 refuse_caps:
2699   {
2700     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2701         GST_PAD_NAME (pad), caps);
2702     gst_object_unref (qtmux);
2703     return FALSE;
2704   }
2705 refuse_renegotiation:
2706   {
2707     GST_WARNING_OBJECT (qtmux,
2708         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2709         GST_PAD_NAME (pad), caps);
2710     gst_object_unref (qtmux);
2711     return FALSE;
2712   }
2713 }
2714
2715 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2716 static guint32
2717 adjust_rate (guint64 rate)
2718 {
2719   if (rate == 0)
2720     return 10000;
2721
2722   while (rate >= 10000)
2723     rate /= 10;
2724
2725   while (rate < 1000)
2726     rate *= 10;
2727
2728   return (guint32) rate;
2729 }
2730
2731 static gboolean
2732 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2733 {
2734   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2735   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2736   GstQTPad *qtpad = NULL;
2737   GstStructure *structure;
2738   const gchar *mimetype;
2739   gint width, height, depth = -1;
2740   gint framerate_num, framerate_den;
2741   guint32 rate;
2742   const GValue *value = NULL;
2743   const GstBuffer *codec_data = NULL;
2744   VisualSampleEntry entry = { 0, };
2745   GstQTMuxFormat format;
2746   AtomInfo *ext_atom = NULL;
2747   GList *ext_atom_list = NULL;
2748   gboolean sync = FALSE;
2749   int par_num, par_den;
2750
2751   /* find stream data */
2752   qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2753   g_assert (qtpad);
2754
2755   qtpad->prepare_buf_func = NULL;
2756
2757   /* does not go well to renegotiate stream mid-way, unless
2758    * the old caps are a subset of the new one (this means upstream
2759    * added more info to the caps, as both should be 'fixed' caps) */
2760   if (qtpad->fourcc) {
2761     GstCaps *current_caps;
2762
2763     current_caps = gst_pad_get_current_caps (pad);
2764     g_assert (caps != NULL);
2765
2766     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2767       gst_caps_unref (current_caps);
2768       goto refuse_renegotiation;
2769     }
2770     GST_DEBUG_OBJECT (qtmux,
2771         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2772         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2773     gst_caps_unref (current_caps);
2774   }
2775
2776   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2777       GST_DEBUG_PAD_NAME (pad), caps);
2778
2779   format = qtmux_klass->format;
2780   structure = gst_caps_get_structure (caps, 0);
2781   mimetype = gst_structure_get_name (structure);
2782
2783   /* required parts */
2784   if (!gst_structure_get_int (structure, "width", &width) ||
2785       !gst_structure_get_int (structure, "height", &height))
2786     goto refuse_caps;
2787
2788   /* optional */
2789   depth = -1;
2790   /* works as a default timebase */
2791   framerate_num = 10000;
2792   framerate_den = 1;
2793   gst_structure_get_fraction (structure, "framerate", &framerate_num,
2794       &framerate_den);
2795   gst_structure_get_int (structure, "depth", &depth);
2796   value = gst_structure_get_value (structure, "codec_data");
2797   if (value != NULL)
2798     codec_data = gst_value_get_buffer (value);
2799
2800   par_num = 1;
2801   par_den = 1;
2802   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
2803       &par_den);
2804
2805   qtpad->is_out_of_order = FALSE;
2806
2807   /* bring frame numerator into a range that ensures both reasonable resolution
2808    * as well as a fair duration */
2809   rate = qtmux->trak_timescale ?
2810       qtmux->trak_timescale : adjust_rate (framerate_num);
2811   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
2812       rate);
2813
2814   /* set common properties */
2815   entry.width = width;
2816   entry.height = height;
2817   entry.par_n = par_num;
2818   entry.par_d = par_den;
2819   /* should be OK according to qt and iso spec, override if really needed */
2820   entry.color_table_id = -1;
2821   entry.frame_count = 1;
2822   entry.depth = 24;
2823
2824   /* sync entries by default */
2825   sync = TRUE;
2826
2827   /* now map onto a fourcc, and some extra properties */
2828   if (strcmp (mimetype, "video/x-raw") == 0) {
2829     const gchar *format;
2830     GstVideoFormat fmt;
2831     const GstVideoFormatInfo *vinfo;
2832
2833     format = gst_structure_get_string (structure, "format");
2834     fmt = gst_video_format_from_string (format);
2835     vinfo = gst_video_format_get_info (fmt);
2836
2837     switch (fmt) {
2838       case GST_VIDEO_FORMAT_UYVY:
2839         if (depth == -1)
2840           depth = 24;
2841         entry.fourcc = FOURCC_2vuy;
2842         entry.depth = depth;
2843         sync = FALSE;
2844         break;
2845       default:
2846         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
2847           entry.fourcc = FOURCC_raw_;
2848           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
2849           sync = FALSE;
2850         }
2851         break;
2852     }
2853   } else if (strcmp (mimetype, "video/x-h263") == 0) {
2854     ext_atom = NULL;
2855     if (format == GST_QT_MUX_FORMAT_QT)
2856       entry.fourcc = FOURCC_h263;
2857     else
2858       entry.fourcc = FOURCC_s263;
2859     ext_atom = build_h263_extension ();
2860     if (ext_atom != NULL)
2861       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2862   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
2863       strcmp (mimetype, "video/mpeg") == 0) {
2864     gint version = 0;
2865
2866     if (strcmp (mimetype, "video/x-divx") == 0) {
2867       gst_structure_get_int (structure, "divxversion", &version);
2868       version = version == 5 ? 1 : 0;
2869     } else {
2870       gst_structure_get_int (structure, "mpegversion", &version);
2871       version = version == 4 ? 1 : 0;
2872     }
2873     if (version) {
2874       entry.fourcc = FOURCC_mp4v;
2875       ext_atom =
2876           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
2877           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
2878           qtpad->max_bitrate);
2879       if (ext_atom != NULL)
2880         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2881       if (!codec_data)
2882         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
2883             "output might not play in Apple QuickTime (try global-headers?)");
2884     }
2885   } else if (strcmp (mimetype, "video/x-h264") == 0) {
2886     /* check if we accept these caps */
2887     if (gst_structure_has_field (structure, "stream-format")) {
2888       const gchar *format;
2889       const gchar *alignment;
2890
2891       format = gst_structure_get_string (structure, "stream-format");
2892       alignment = gst_structure_get_string (structure, "alignment");
2893
2894       if (strcmp (format, "avc") != 0 || alignment == NULL ||
2895           strcmp (alignment, "au") != 0) {
2896         GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
2897             "avc format with AU aligned samples");
2898         goto refuse_caps;
2899       }
2900     } else {
2901       GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
2902       goto refuse_caps;
2903     }
2904
2905     if (!codec_data) {
2906       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
2907       goto refuse_caps;
2908     }
2909
2910     entry.fourcc = FOURCC_avc1;
2911     if (qtpad->avg_bitrate == 0) {
2912       gint avg_bitrate = 0;
2913       gst_structure_get_int (structure, "bitrate", &avg_bitrate);
2914       qtpad->avg_bitrate = avg_bitrate;
2915     }
2916     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
2917     if (ext_atom != NULL)
2918       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2919     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
2920     if (ext_atom != NULL)
2921       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2922     qtpad->have_dts = TRUE;
2923   } else if (strcmp (mimetype, "video/x-svq") == 0) {
2924     gint version = 0;
2925     const GstBuffer *seqh = NULL;
2926     const GValue *seqh_value;
2927     gdouble gamma = 0;
2928
2929     gst_structure_get_int (structure, "svqversion", &version);
2930     if (version == 3) {
2931       entry.fourcc = FOURCC_SVQ3;
2932       entry.version = 3;
2933       entry.depth = 32;
2934
2935       seqh_value = gst_structure_get_value (structure, "seqh");
2936       if (seqh_value) {
2937         seqh = gst_value_get_buffer (seqh_value);
2938         ext_atom = build_SMI_atom (seqh);
2939         if (ext_atom)
2940           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2941       }
2942
2943       /* we need to add the gamma anyway because quicktime might crash
2944        * when it doesn't find it */
2945       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
2946         /* it seems that using 0 here makes it ignored */
2947         gamma = 0.0;
2948       }
2949       ext_atom = build_gama_atom (gamma);
2950       if (ext_atom)
2951         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2952     } else {
2953       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
2954           "a bug at http://bugzilla.gnome.org", version);
2955     }
2956   } else if (strcmp (mimetype, "video/x-dv") == 0) {
2957     gint version = 0;
2958     gboolean pal = TRUE;
2959
2960     sync = FALSE;
2961     if (framerate_num != 25 || framerate_den != 1)
2962       pal = FALSE;
2963     gst_structure_get_int (structure, "dvversion", &version);
2964     /* fall back to typical one */
2965     if (!version)
2966       version = 25;
2967     switch (version) {
2968       case 25:
2969         if (pal)
2970           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
2971         else
2972           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
2973         break;
2974       case 50:
2975         if (pal)
2976           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
2977         else
2978           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
2979         break;
2980       default:
2981         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
2982         break;
2983     }
2984   } else if (strcmp (mimetype, "image/jpeg") == 0) {
2985     entry.fourcc = FOURCC_jpeg;
2986     sync = FALSE;
2987   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
2988       strcmp (mimetype, "image/x-jpc") == 0) {
2989     const gchar *colorspace;
2990     const GValue *cmap_array;
2991     const GValue *cdef_array;
2992     gint ncomp = 0;
2993     gint fields = 1;
2994
2995     if (strcmp (mimetype, "image/x-jpc") == 0) {
2996       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
2997     }
2998
2999     gst_structure_get_int (structure, "num-components", &ncomp);
3000     gst_structure_get_int (structure, "fields", &fields);
3001     cmap_array = gst_structure_get_value (structure, "component-map");
3002     cdef_array = gst_structure_get_value (structure, "channel-definitions");
3003
3004     ext_atom = NULL;
3005     entry.fourcc = FOURCC_mjp2;
3006     sync = FALSE;
3007
3008     colorspace = gst_structure_get_string (structure, "colorspace");
3009     if (colorspace &&
3010         (ext_atom =
3011             build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
3012                 cmap_array, cdef_array)) != NULL) {
3013       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3014
3015       ext_atom = build_fiel_extension (fields);
3016       if (ext_atom)
3017         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3018
3019       ext_atom = build_jp2x_extension (codec_data);
3020       if (ext_atom)
3021         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3022     } else {
3023       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3024       goto refuse_caps;
3025     }
3026   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3027     entry.fourcc = FOURCC_VP80;
3028     sync = FALSE;
3029   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3030     entry.fourcc = FOURCC_drac;
3031     qtpad->have_dts = TRUE;
3032   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3033     guint32 fourcc;
3034
3035     gst_structure_get_uint (structure, "format", &fourcc);
3036     entry.fourcc = fourcc;
3037     qtpad->have_dts = TRUE;
3038   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3039     guint32 fourcc;
3040
3041     gst_structure_get_uint (structure, "format", &fourcc);
3042     entry.fourcc = fourcc;
3043     qtpad->have_dts = TRUE;
3044   }
3045
3046   if (!entry.fourcc)
3047     goto refuse_caps;
3048
3049   /* ok, set the pad info accordingly */
3050   qtpad->fourcc = entry.fourcc;
3051   qtpad->sync = sync;
3052   atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3053       ext_atom_list);
3054
3055   gst_object_unref (qtmux);
3056   return TRUE;
3057
3058   /* ERRORS */
3059 refuse_caps:
3060   {
3061     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3062         GST_PAD_NAME (pad), caps);
3063     gst_object_unref (qtmux);
3064     return FALSE;
3065   }
3066 refuse_renegotiation:
3067   {
3068     GST_WARNING_OBJECT (qtmux,
3069         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
3070         caps);
3071     gst_object_unref (qtmux);
3072     return FALSE;
3073   }
3074 }
3075
3076 static gboolean
3077 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
3078     GstEvent * event, gpointer user_data)
3079 {
3080   GstQTMux *qtmux;
3081   guint32 avg_bitrate = 0, max_bitrate = 0;
3082   GstPad *pad = data->pad;
3083   gboolean ret = TRUE;
3084
3085   qtmux = GST_QT_MUX_CAST (user_data);
3086   switch (GST_EVENT_TYPE (event)) {
3087     case GST_EVENT_CAPS:
3088     {
3089       GstCaps *caps;
3090       GstQTPad *collect_pad;
3091
3092       gst_event_parse_caps (event, &caps);
3093
3094       /* find stream data */
3095       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
3096       g_assert (collect_pad);
3097       g_assert (collect_pad->set_caps);
3098
3099       ret = collect_pad->set_caps (pad, caps);
3100       gst_event_unref (event);
3101       event = NULL;
3102       break;
3103     }
3104     case GST_EVENT_TAG:{
3105       GstTagList *list;
3106       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3107       GstTagMergeMode mode;
3108       gchar *code;
3109
3110       GST_OBJECT_LOCK (qtmux);
3111       mode = gst_tag_setter_get_tag_merge_mode (setter);
3112
3113       gst_event_parse_tag (event, &list);
3114       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
3115           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
3116
3117       gst_tag_setter_merge_tags (setter, list, mode);
3118       GST_OBJECT_UNLOCK (qtmux);
3119
3120       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3121           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3122         GstQTPad *qtpad = gst_pad_get_element_private (pad);
3123         g_assert (qtpad);
3124
3125         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3126           qtpad->avg_bitrate = avg_bitrate;
3127         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3128           qtpad->max_bitrate = max_bitrate;
3129       }
3130
3131       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
3132         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
3133         if (iso_code) {
3134           GstQTPad *qtpad = gst_pad_get_element_private (pad);
3135           g_assert (qtpad);
3136           if (qtpad->trak) {
3137             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
3138             qtpad->trak->mdia.mdhd.language_code =
3139                 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
3140                 (iso_code[2] - 0x60);
3141           }
3142         }
3143         g_free (code);
3144       }
3145
3146       gst_event_unref (event);
3147       event = NULL;
3148       ret = TRUE;
3149       break;
3150     }
3151     default:
3152       break;
3153   }
3154
3155   if (event != NULL)
3156     return gst_collect_pads_event_default (pads, data, event, FALSE);
3157
3158   return ret;
3159 }
3160
3161 static void
3162 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3163 {
3164   GstQTMux *mux = GST_QT_MUX_CAST (element);
3165   GSList *walk;
3166
3167   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3168
3169   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3170     GstQTPad *qtpad = (GstQTPad *) walk->data;
3171     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3172     if (qtpad->collect.pad == pad) {
3173       /* this is it, remove */
3174       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3175       gst_element_remove_pad (element, pad);
3176       break;
3177     }
3178   }
3179
3180   gst_collect_pads_remove_pad (mux->collect, pad);
3181 }
3182
3183 static GstPad *
3184 gst_qt_mux_request_new_pad (GstElement * element,
3185     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
3186 {
3187   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3188   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3189   GstQTPad *collect_pad;
3190   GstPad *newpad;
3191   gboolean audio;
3192   gchar *name;
3193   gint pad_id;
3194
3195   if (templ->direction != GST_PAD_SINK)
3196     goto wrong_direction;
3197
3198   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3199     goto too_late;
3200
3201   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
3202     audio = TRUE;
3203     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
3204       name = g_strdup (req_name);
3205     } else {
3206       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
3207     }
3208   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
3209     audio = FALSE;
3210     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
3211       name = g_strdup (req_name);
3212     } else {
3213       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
3214     }
3215   } else
3216     goto wrong_template;
3217
3218   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3219
3220   /* create pad and add to collections */
3221   newpad = gst_pad_new_from_template (templ, name);
3222   g_free (name);
3223   collect_pad = (GstQTPad *)
3224       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
3225       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), TRUE);
3226   /* set up pad */
3227   gst_qt_mux_pad_reset (collect_pad);
3228   collect_pad->trak = atom_trak_new (qtmux->context);
3229   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3230
3231   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3232
3233   /* set up pad functions */
3234   if (audio)
3235     collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps);
3236   else
3237     collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps);
3238
3239   gst_pad_set_active (newpad, TRUE);
3240   gst_element_add_pad (element, newpad);
3241
3242   return newpad;
3243
3244   /* ERRORS */
3245 wrong_direction:
3246   {
3247     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3248     return NULL;
3249   }
3250 too_late:
3251   {
3252     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3253     return NULL;
3254   }
3255 wrong_template:
3256   {
3257     GST_WARNING_OBJECT (qtmux, "This is not our template!");
3258     return NULL;
3259   }
3260 }
3261
3262 static void
3263 gst_qt_mux_get_property (GObject * object,
3264     guint prop_id, GValue * value, GParamSpec * pspec)
3265 {
3266   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3267
3268   GST_OBJECT_LOCK (qtmux);
3269   switch (prop_id) {
3270     case PROP_MOVIE_TIMESCALE:
3271       g_value_set_uint (value, qtmux->timescale);
3272       break;
3273     case PROP_TRAK_TIMESCALE:
3274       g_value_set_uint (value, qtmux->trak_timescale);
3275       break;
3276     case PROP_DO_CTTS:
3277       g_value_set_boolean (value, qtmux->guess_pts);
3278       break;
3279     case PROP_DTS_METHOD:
3280       g_value_set_enum (value, qtmux->dts_method);
3281       break;
3282     case PROP_FAST_START:
3283       g_value_set_boolean (value, qtmux->fast_start);
3284       break;
3285     case PROP_FAST_START_TEMP_FILE:
3286       g_value_set_string (value, qtmux->fast_start_file_path);
3287       break;
3288     case PROP_MOOV_RECOV_FILE:
3289       g_value_set_string (value, qtmux->moov_recov_file_path);
3290       break;
3291     case PROP_FRAGMENT_DURATION:
3292       g_value_set_uint (value, qtmux->fragment_duration);
3293       break;
3294     case PROP_STREAMABLE:
3295       g_value_set_boolean (value, qtmux->streamable);
3296       break;
3297     default:
3298       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3299       break;
3300   }
3301   GST_OBJECT_UNLOCK (qtmux);
3302 }
3303
3304 static void
3305 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3306 {
3307   gchar *tmp;
3308
3309   g_free (qtmux->fast_start_file_path);
3310   qtmux->fast_start_file_path = NULL;
3311
3312   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3313   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3314   g_free (tmp);
3315 }
3316
3317 static void
3318 gst_qt_mux_set_property (GObject * object,
3319     guint prop_id, const GValue * value, GParamSpec * pspec)
3320 {
3321   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3322
3323   GST_OBJECT_LOCK (qtmux);
3324   switch (prop_id) {
3325     case PROP_MOVIE_TIMESCALE:
3326       qtmux->timescale = g_value_get_uint (value);
3327       break;
3328     case PROP_TRAK_TIMESCALE:
3329       qtmux->trak_timescale = g_value_get_uint (value);
3330       break;
3331     case PROP_DO_CTTS:
3332       qtmux->guess_pts = g_value_get_boolean (value);
3333       break;
3334     case PROP_DTS_METHOD:
3335       qtmux->dts_method = g_value_get_enum (value);
3336       break;
3337     case PROP_FAST_START:
3338       qtmux->fast_start = g_value_get_boolean (value);
3339       break;
3340     case PROP_FAST_START_TEMP_FILE:
3341       g_free (qtmux->fast_start_file_path);
3342       qtmux->fast_start_file_path = g_value_dup_string (value);
3343       /* NULL means to generate a random one */
3344       if (!qtmux->fast_start_file_path) {
3345         gst_qt_mux_generate_fast_start_file_path (qtmux);
3346       }
3347       break;
3348     case PROP_MOOV_RECOV_FILE:
3349       g_free (qtmux->moov_recov_file_path);
3350       qtmux->moov_recov_file_path = g_value_dup_string (value);
3351       break;
3352     case PROP_FRAGMENT_DURATION:
3353       qtmux->fragment_duration = g_value_get_uint (value);
3354       break;
3355     case PROP_STREAMABLE:
3356       qtmux->streamable = g_value_get_boolean (value);
3357       break;
3358     default:
3359       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3360       break;
3361   }
3362   GST_OBJECT_UNLOCK (qtmux);
3363 }
3364
3365 static GstStateChangeReturn
3366 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3367 {
3368   GstStateChangeReturn ret;
3369   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3370
3371   switch (transition) {
3372     case GST_STATE_CHANGE_NULL_TO_READY:
3373       break;
3374     case GST_STATE_CHANGE_READY_TO_PAUSED:
3375       gst_collect_pads_start (qtmux->collect);
3376       qtmux->state = GST_QT_MUX_STATE_STARTED;
3377       break;
3378     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3379       break;
3380     case GST_STATE_CHANGE_PAUSED_TO_READY:
3381       gst_collect_pads_stop (qtmux->collect);
3382       break;
3383     default:
3384       break;
3385   }
3386
3387   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3388
3389   switch (transition) {
3390     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3391       break;
3392     case GST_STATE_CHANGE_PAUSED_TO_READY:
3393       gst_qt_mux_reset (qtmux, TRUE);
3394       break;
3395     case GST_STATE_CHANGE_READY_TO_NULL:
3396       break;
3397     default:
3398       break;
3399   }
3400
3401   return ret;
3402 }
3403
3404 gboolean
3405 gst_qt_mux_register (GstPlugin * plugin)
3406 {
3407   GTypeInfo typeinfo = {
3408     sizeof (GstQTMuxClass),
3409     (GBaseInitFunc) gst_qt_mux_base_init,
3410     NULL,
3411     (GClassInitFunc) gst_qt_mux_class_init,
3412     NULL,
3413     NULL,
3414     sizeof (GstQTMux),
3415     0,
3416     (GInstanceInitFunc) gst_qt_mux_init,
3417   };
3418   static const GInterfaceInfo tag_setter_info = {
3419     NULL, NULL, NULL
3420   };
3421   static const GInterfaceInfo tag_xmp_writer_info = {
3422     NULL, NULL, NULL
3423   };
3424   GType type;
3425   GstQTMuxFormat format;
3426   GstQTMuxClassParams *params;
3427   guint i = 0;
3428
3429   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3430
3431   GST_LOG ("Registering muxers");
3432
3433   while (TRUE) {
3434     GstQTMuxFormatProp *prop;
3435
3436     prop = &gst_qt_mux_format_list[i];
3437     format = prop->format;
3438     if (format == GST_QT_MUX_FORMAT_NONE)
3439       break;
3440
3441     /* create a cache for these properties */
3442     params = g_new0 (GstQTMuxClassParams, 1);
3443     params->prop = prop;
3444     params->src_caps = gst_static_caps_get (&prop->src_caps);
3445     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3446     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3447
3448     /* create the type now */
3449     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3450         0);
3451     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3452     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3453     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3454         &tag_xmp_writer_info);
3455
3456     if (!gst_element_register (plugin, prop->name, prop->rank, type))
3457       return FALSE;
3458
3459     i++;
3460   }
3461
3462   GST_LOG ("Finished registering muxers");
3463
3464   /* FIXME: ideally classification tag should be added and
3465      registered in gstreamer core gsttaglist
3466    */
3467
3468   GST_LOG ("Registering tags");
3469
3470   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3471       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3472       gst_tag_merge_use_first);
3473
3474   GST_LOG ("Finished registering tags");
3475
3476   return TRUE;
3477 }