2b4a4e25f2e7cba50be57070403d22cacef3ab80
[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       check_and_subtract_ts (qtmux, &GST_BUFFER_DTS (last_buf), pad->first_ts);
2158       check_and_subtract_ts (qtmux, &GST_BUFFER_PTS (last_buf), pad->first_ts);
2159       check_and_subtract_ts (qtmux, &GST_BUFFER_DTS (buf), pad->first_ts);
2160       check_and_subtract_ts (qtmux, &GST_BUFFER_PTS (buf), pad->first_ts);
2161     } else {
2162       GST_ERROR_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2163           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2164       pad->first_ts = 0;
2165     }
2166     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2167         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2168         GST_TIME_ARGS (pad->first_ts));
2169
2170   }
2171
2172   duration = GST_BUFFER_DURATION (last_buf);
2173
2174   /* for computing the avg bitrate */
2175   if (G_LIKELY (last_buf)) {
2176     pad->total_bytes += gst_buffer_get_size (last_buf);
2177     pad->total_duration += duration;
2178   }
2179
2180   gst_buffer_replace (&pad->last_buf, buf);
2181
2182   last_dts = gst_util_uint64_scale_round (pad->last_dts,
2183       atom_trak_get_timescale (pad->trak), GST_SECOND);
2184
2185   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2186   if (pad->sample_size && !qtmux->fragment_sequence) {
2187     /* Constant size packets: usually raw audio (with many samples per
2188        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2189      */
2190     sample_size = pad->sample_size;
2191     if (gst_buffer_get_size (last_buf) % sample_size != 0)
2192       goto fragmented_sample;
2193     /* note: qt raw audio storage warps it implicitly into a timewise
2194      * perfect stream, discarding buffer times */
2195     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2196       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2197           atom_trak_get_timescale (pad->trak), GST_SECOND);
2198     } else {
2199       nsamples = gst_buffer_get_size (last_buf) / sample_size;
2200     }
2201     duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2202
2203     /* timescale = samplerate */
2204     scaled_duration = 1;
2205     pad->last_dts += duration * nsamples;
2206   } else {
2207     nsamples = 1;
2208     sample_size = gst_buffer_get_size (last_buf);
2209     if (pad->have_dts) {
2210       gint64 scaled_dts;
2211       pad->last_dts = GST_BUFFER_DTS (last_buf);
2212       if ((gint64) (pad->last_dts) < 0) {
2213         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2214             atom_trak_get_timescale (pad->trak), GST_SECOND);
2215       } else {
2216         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2217             atom_trak_get_timescale (pad->trak), GST_SECOND);
2218       }
2219       scaled_duration = scaled_dts - last_dts;
2220       last_dts = scaled_dts;
2221     } else {
2222       /* first convert intended timestamp (in GstClockTime resolution) to
2223        * trak timescale, then derive delta;
2224        * this ensures sums of (scale)delta add up to converted timestamp,
2225        * which only deviates at most 1/scale from timestamp itself */
2226       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2227           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2228       pad->last_dts += duration;
2229     }
2230   }
2231   chunk_offset = qtmux->mdat_size;
2232
2233   GST_LOG_OBJECT (qtmux,
2234       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2235       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2236   GST_LOG_OBJECT (qtmux,
2237       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2238       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2239       nsamples, scaled_duration, sample_size, chunk_offset);
2240
2241   /* might be a sync sample */
2242   if (pad->sync &&
2243       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2244     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2245         GST_PAD_NAME (pad->collect.pad));
2246     sync = TRUE;
2247   }
2248
2249   if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf))) {
2250     do_pts = TRUE;
2251     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
2252         atom_trak_get_timescale (pad->trak), GST_SECOND);
2253     pts_offset =
2254         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
2255             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
2256
2257   } else {
2258     pts_offset = 0;
2259     do_pts = TRUE;
2260     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
2261         atom_trak_get_timescale (pad->trak), GST_SECOND);
2262   }
2263   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
2264       " timebase_dts: %d pts_offset: %d",
2265       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
2266       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
2267       (int) (last_dts), (int) (pts_offset));
2268
2269   /*
2270    * Each buffer starts a new chunk, so we can assume the buffer
2271    * duration is the chunk duration
2272    */
2273   if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2274           !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2275     GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2276         ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2277     qtmux->longest_chunk = duration;
2278   }
2279
2280   /* now we go and register this buffer/sample all over */
2281   /* note that a new chunk is started each time (not fancy but works) */
2282   if (qtmux->moov_recov_file) {
2283     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2284             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2285             do_pts, pts_offset)) {
2286       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2287           "recovery file, disabling recovery");
2288       fclose (qtmux->moov_recov_file);
2289       qtmux->moov_recov_file = NULL;
2290     }
2291   }
2292
2293   if (buf)
2294     gst_buffer_unref (buf);
2295
2296   if (qtmux->fragment_sequence) {
2297     /* ensure that always sync samples are marked as such */
2298     ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2299         buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2300         !pad->sync || sync, pts_offset);
2301   } else {
2302     atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2303         sample_size, chunk_offset, sync, pts_offset);
2304     ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2305   }
2306
2307 exit:
2308
2309   return ret;
2310
2311   /* ERRORS */
2312 bail:
2313   {
2314     if (buf)
2315       gst_buffer_unref (buf);
2316     gst_buffer_unref (last_buf);
2317     return GST_FLOW_ERROR;
2318   }
2319 fragmented_sample:
2320   {
2321     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2322         ("Audio buffer contains fragmented sample."));
2323     goto bail;
2324   }
2325 not_negotiated:
2326   {
2327     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2328         ("format wasn't negotiated before buffer flow on pad %s",
2329             GST_PAD_NAME (pad->collect.pad)));
2330     if (buf)
2331       gst_buffer_unref (buf);
2332     return GST_FLOW_NOT_NEGOTIATED;
2333   }
2334 }
2335
2336 static GstFlowReturn
2337 gst_qt_mux_handle_buffer (GstCollectPads * pads, GstCollectData * cdata,
2338     GstBuffer * buf, gpointer user_data)
2339 {
2340   GstFlowReturn ret = GST_FLOW_OK;
2341   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2342   GstQTPad *best_pad = NULL;
2343   GstClockTime best_time = GST_CLOCK_TIME_NONE;
2344
2345   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2346     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2347       return ret;
2348     else
2349       qtmux->state = GST_QT_MUX_STATE_DATA;
2350   }
2351
2352   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2353     return GST_FLOW_EOS;
2354
2355   best_pad = (GstQTPad *) cdata;
2356
2357   /* clipping already converted to running time */
2358   if (best_pad != NULL) {
2359     g_assert (buf);
2360     best_time = GST_BUFFER_PTS (buf);
2361     GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2362         GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2363     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2364   } else {
2365     ret = gst_qt_mux_stop_file (qtmux);
2366     if (ret == GST_FLOW_OK) {
2367       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2368       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2369       ret = GST_FLOW_EOS;
2370     } else {
2371       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2372           gst_flow_get_name (ret));
2373     }
2374     qtmux->state = GST_QT_MUX_STATE_EOS;
2375   }
2376
2377   return ret;
2378 }
2379
2380 static gboolean
2381 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2382 {
2383   GstStructure *structure = (GstStructure *) user_data;
2384   const GValue *other = gst_structure_id_get_value (structure, field_id);
2385   if (other == NULL)
2386     return FALSE;
2387   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2388 }
2389
2390 static gboolean
2391 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2392     GstCaps * superset)
2393 {
2394   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2395   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2396
2397   return gst_structure_foreach (sub_s, check_field, sup_s);
2398 }
2399
2400 static gboolean
2401 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2402 {
2403   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2404   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2405   GstQTPad *qtpad = NULL;
2406   GstStructure *structure;
2407   const gchar *mimetype;
2408   gint rate, channels;
2409   const GValue *value = NULL;
2410   const GstBuffer *codec_data = NULL;
2411   GstQTMuxFormat format;
2412   AudioSampleEntry entry = { 0, };
2413   AtomInfo *ext_atom = NULL;
2414   gint constant_size = 0;
2415   const gchar *stream_format;
2416
2417   /* find stream data */
2418   qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2419   g_assert (qtpad);
2420
2421   qtpad->prepare_buf_func = NULL;
2422
2423   /* does not go well to renegotiate stream mid-way, unless
2424    * the old caps are a subset of the new one (this means upstream
2425    * added more info to the caps, as both should be 'fixed' caps) */
2426   if (qtpad->fourcc) {
2427     GstCaps *current_caps;
2428
2429     current_caps = gst_pad_get_current_caps (pad);
2430     g_assert (caps != NULL);
2431
2432     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2433       gst_caps_unref (current_caps);
2434       goto refuse_renegotiation;
2435     }
2436     GST_DEBUG_OBJECT (qtmux,
2437         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2438         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2439     gst_caps_unref (current_caps);
2440   }
2441
2442   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2443       GST_DEBUG_PAD_NAME (pad), caps);
2444
2445   format = qtmux_klass->format;
2446   structure = gst_caps_get_structure (caps, 0);
2447   mimetype = gst_structure_get_name (structure);
2448
2449   /* common info */
2450   if (!gst_structure_get_int (structure, "channels", &channels) ||
2451       !gst_structure_get_int (structure, "rate", &rate)) {
2452     goto refuse_caps;
2453   }
2454
2455   /* optional */
2456   value = gst_structure_get_value (structure, "codec_data");
2457   if (value != NULL)
2458     codec_data = gst_value_get_buffer (value);
2459
2460   qtpad->is_out_of_order = FALSE;
2461   qtpad->have_dts = FALSE;
2462
2463   /* set common properties */
2464   entry.sample_rate = rate;
2465   entry.channels = channels;
2466   /* default */
2467   entry.sample_size = 16;
2468   /* this is the typical compressed case */
2469   if (format == GST_QT_MUX_FORMAT_QT) {
2470     entry.version = 1;
2471     entry.compression_id = -2;
2472   }
2473
2474   /* now map onto a fourcc, and some extra properties */
2475   if (strcmp (mimetype, "audio/mpeg") == 0) {
2476     gint mpegversion = 0;
2477     gint layer = -1;
2478
2479     gst_structure_get_int (structure, "mpegversion", &mpegversion);
2480     switch (mpegversion) {
2481       case 1:
2482         gst_structure_get_int (structure, "layer", &layer);
2483         switch (layer) {
2484           case 3:
2485             /* mp3 */
2486             /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2487             if (format == GST_QT_MUX_FORMAT_QT)
2488               entry.fourcc = FOURCC__mp3;
2489             else {
2490               entry.fourcc = FOURCC_mp4a;
2491               ext_atom =
2492                   build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2493                   ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2494                   qtpad->max_bitrate);
2495             }
2496             entry.samples_per_packet = 1152;
2497             entry.bytes_per_sample = 2;
2498             break;
2499         }
2500         break;
2501       case 4:
2502
2503         /* check stream-format */
2504         stream_format = gst_structure_get_string (structure, "stream-format");
2505         if (stream_format) {
2506           if (strcmp (stream_format, "raw") != 0) {
2507             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2508                 "please use 'raw'", stream_format);
2509             goto refuse_caps;
2510           }
2511         } else {
2512           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2513               "assuming 'raw'");
2514         }
2515
2516         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
2517           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2518         else {
2519           guint8 profile;
2520
2521           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
2522           /* warn if not Low Complexity profile */
2523           profile >>= 3;
2524           if (profile != 2)
2525             GST_WARNING_OBJECT (qtmux,
2526                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2527         }
2528
2529         /* AAC */
2530         entry.fourcc = FOURCC_mp4a;
2531
2532         if (format == GST_QT_MUX_FORMAT_QT)
2533           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2534               qtpad->avg_bitrate, qtpad->max_bitrate);
2535         else
2536           ext_atom =
2537               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2538               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2539               qtpad->max_bitrate);
2540         break;
2541       default:
2542         break;
2543     }
2544   } else if (strcmp (mimetype, "audio/AMR") == 0) {
2545     entry.fourcc = FOURCC_samr;
2546     entry.sample_size = 16;
2547     entry.samples_per_packet = 160;
2548     entry.bytes_per_sample = 2;
2549     ext_atom = build_amr_extension ();
2550   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2551     entry.fourcc = FOURCC_sawb;
2552     entry.sample_size = 16;
2553     entry.samples_per_packet = 320;
2554     entry.bytes_per_sample = 2;
2555     ext_atom = build_amr_extension ();
2556   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
2557     GstAudioInfo info;
2558
2559     gst_audio_info_init (&info);
2560     if (!gst_audio_info_from_caps (&info, caps))
2561       goto refuse_caps;
2562
2563     /* spec has no place for a distinction in these */
2564     if (info.finfo->width != info.finfo->depth) {
2565       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2566       goto refuse_caps;
2567     }
2568
2569     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
2570       if (info.finfo->endianness == G_LITTLE_ENDIAN)
2571         entry.fourcc = FOURCC_sowt;
2572       else if (info.finfo->endianness == G_BIG_ENDIAN)
2573         entry.fourcc = FOURCC_twos;
2574       /* maximum backward compatibility; only new version for > 16 bit */
2575       if (info.finfo->depth <= 16)
2576         entry.version = 0;
2577       /* not compressed in any case */
2578       entry.compression_id = 0;
2579       /* QT spec says: max at 16 bit even if sample size were actually larger,
2580        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2581       entry.sample_size = info.finfo->depth;
2582       entry.bytes_per_sample = info.finfo->depth / 8;
2583       entry.samples_per_packet = 1;
2584       entry.bytes_per_packet = info.finfo->depth / 8;
2585       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
2586     } else {
2587       if (info.finfo->width == 8 && info.finfo->depth == 8) {
2588         /* fall back to old 8-bit version */
2589         entry.fourcc = FOURCC_raw_;
2590         entry.version = 0;
2591         entry.compression_id = 0;
2592         entry.sample_size = 8;
2593       } else {
2594         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2595         goto refuse_caps;
2596       }
2597     }
2598     constant_size = (info.finfo->depth / 8) * info.channels;
2599   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2600     entry.fourcc = FOURCC_alaw;
2601     entry.samples_per_packet = 1023;
2602     entry.bytes_per_sample = 2;
2603   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2604     entry.fourcc = FOURCC_ulaw;
2605     entry.samples_per_packet = 1023;
2606     entry.bytes_per_sample = 2;
2607   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2608     gint blocksize;
2609     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2610       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2611       goto refuse_caps;
2612     }
2613     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2614        0x11 */
2615     entry.fourcc = MS_WAVE_FOURCC (0x11);
2616     /* 4 byte header per channel (including one sample). 2 samples per byte
2617        remaining. Simplifying gives the following (samples per block per
2618        channel) */
2619     entry.samples_per_packet = 2 * blocksize / channels - 7;
2620     entry.bytes_per_sample = 2;
2621
2622     entry.bytes_per_frame = blocksize;
2623     entry.bytes_per_packet = blocksize / channels;
2624     /* ADPCM has constant size packets */
2625     constant_size = 1;
2626     /* TODO: I don't really understand why this helps, but it does! Constant
2627      * size and compression_id of -2 seem to be incompatible, and other files
2628      * in the wild use this too. */
2629     entry.compression_id = -1;
2630
2631     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2632   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2633     GstBuffer *codec_config;
2634     gint len;
2635     GstMapInfo map;
2636
2637     entry.fourcc = FOURCC_alac;
2638     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
2639     /* let's check if codec data already comes with 'alac' atom prefix */
2640     if (!codec_data || (len = map.size) < 28) {
2641       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2642       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2643       goto refuse_caps;
2644     }
2645     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
2646       len -= 8;
2647       codec_config =
2648           gst_buffer_copy_region ((GstBuffer *) codec_data, 0, 8, len);
2649     } else {
2650       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2651     }
2652     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2653     if (len != 28) {
2654       /* does not look good, but perhaps some trailing unneeded stuff */
2655       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2656     }
2657     if (format == GST_QT_MUX_FORMAT_QT)
2658       ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2659     else
2660       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2661     /* set some more info */
2662     gst_buffer_map (codec_config, &map, GST_MAP_READ);
2663     entry.bytes_per_sample = 2;
2664     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
2665     gst_buffer_unmap (codec_config, &map);
2666     gst_buffer_unref (codec_config);
2667   }
2668
2669   if (!entry.fourcc)
2670     goto refuse_caps;
2671
2672   /* ok, set the pad info accordingly */
2673   qtpad->fourcc = entry.fourcc;
2674   qtpad->sample_size = constant_size;
2675   atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2676       qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2677       ext_atom, constant_size);
2678
2679   gst_object_unref (qtmux);
2680   return TRUE;
2681
2682   /* ERRORS */
2683 refuse_caps:
2684   {
2685     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2686         GST_PAD_NAME (pad), caps);
2687     gst_object_unref (qtmux);
2688     return FALSE;
2689   }
2690 refuse_renegotiation:
2691   {
2692     GST_WARNING_OBJECT (qtmux,
2693         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2694         GST_PAD_NAME (pad), caps);
2695     gst_object_unref (qtmux);
2696     return FALSE;
2697   }
2698 }
2699
2700 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2701 static guint32
2702 adjust_rate (guint64 rate)
2703 {
2704   if (rate == 0)
2705     return 10000;
2706
2707   while (rate >= 10000)
2708     rate /= 10;
2709
2710   while (rate < 1000)
2711     rate *= 10;
2712
2713   return (guint32) rate;
2714 }
2715
2716 static gboolean
2717 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2718 {
2719   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2720   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2721   GstQTPad *qtpad = NULL;
2722   GstStructure *structure;
2723   const gchar *mimetype;
2724   gint width, height, depth = -1;
2725   gint framerate_num, framerate_den;
2726   guint32 rate;
2727   const GValue *value = NULL;
2728   const GstBuffer *codec_data = NULL;
2729   VisualSampleEntry entry = { 0, };
2730   GstQTMuxFormat format;
2731   AtomInfo *ext_atom = NULL;
2732   GList *ext_atom_list = NULL;
2733   gboolean sync = FALSE;
2734   int par_num, par_den;
2735
2736   /* find stream data */
2737   qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2738   g_assert (qtpad);
2739
2740   qtpad->prepare_buf_func = NULL;
2741
2742   /* does not go well to renegotiate stream mid-way, unless
2743    * the old caps are a subset of the new one (this means upstream
2744    * added more info to the caps, as both should be 'fixed' caps) */
2745   if (qtpad->fourcc) {
2746     GstCaps *current_caps;
2747
2748     current_caps = gst_pad_get_current_caps (pad);
2749     g_assert (caps != NULL);
2750
2751     if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2752       gst_caps_unref (current_caps);
2753       goto refuse_renegotiation;
2754     }
2755     GST_DEBUG_OBJECT (qtmux,
2756         "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2757         GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2758     gst_caps_unref (current_caps);
2759   }
2760
2761   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2762       GST_DEBUG_PAD_NAME (pad), caps);
2763
2764   format = qtmux_klass->format;
2765   structure = gst_caps_get_structure (caps, 0);
2766   mimetype = gst_structure_get_name (structure);
2767
2768   /* required parts */
2769   if (!gst_structure_get_int (structure, "width", &width) ||
2770       !gst_structure_get_int (structure, "height", &height))
2771     goto refuse_caps;
2772
2773   /* optional */
2774   depth = -1;
2775   /* works as a default timebase */
2776   framerate_num = 10000;
2777   framerate_den = 1;
2778   gst_structure_get_fraction (structure, "framerate", &framerate_num,
2779       &framerate_den);
2780   gst_structure_get_int (structure, "depth", &depth);
2781   value = gst_structure_get_value (structure, "codec_data");
2782   if (value != NULL)
2783     codec_data = gst_value_get_buffer (value);
2784
2785   par_num = 1;
2786   par_den = 1;
2787   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
2788       &par_den);
2789
2790   qtpad->is_out_of_order = FALSE;
2791
2792   /* bring frame numerator into a range that ensures both reasonable resolution
2793    * as well as a fair duration */
2794   rate = qtmux->trak_timescale ?
2795       qtmux->trak_timescale : adjust_rate (framerate_num);
2796   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
2797       rate);
2798
2799   /* set common properties */
2800   entry.width = width;
2801   entry.height = height;
2802   entry.par_n = par_num;
2803   entry.par_d = par_den;
2804   /* should be OK according to qt and iso spec, override if really needed */
2805   entry.color_table_id = -1;
2806   entry.frame_count = 1;
2807   entry.depth = 24;
2808
2809   /* sync entries by default */
2810   sync = TRUE;
2811
2812   /* now map onto a fourcc, and some extra properties */
2813   if (strcmp (mimetype, "video/x-raw") == 0) {
2814     const gchar *format;
2815     GstVideoFormat fmt;
2816     const GstVideoFormatInfo *vinfo;
2817
2818     format = gst_structure_get_string (structure, "format");
2819     fmt = gst_video_format_from_string (format);
2820     vinfo = gst_video_format_get_info (fmt);
2821
2822     switch (fmt) {
2823       case GST_VIDEO_FORMAT_UYVY:
2824         if (depth == -1)
2825           depth = 24;
2826         entry.fourcc = FOURCC_2vuy;
2827         entry.depth = depth;
2828         sync = FALSE;
2829         break;
2830       default:
2831         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
2832           entry.fourcc = FOURCC_raw_;
2833           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
2834           sync = FALSE;
2835         }
2836         break;
2837     }
2838   } else if (strcmp (mimetype, "video/x-h263") == 0) {
2839     ext_atom = NULL;
2840     if (format == GST_QT_MUX_FORMAT_QT)
2841       entry.fourcc = FOURCC_h263;
2842     else
2843       entry.fourcc = FOURCC_s263;
2844     ext_atom = build_h263_extension ();
2845     if (ext_atom != NULL)
2846       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2847   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
2848       strcmp (mimetype, "video/mpeg") == 0) {
2849     gint version = 0;
2850
2851     if (strcmp (mimetype, "video/x-divx") == 0) {
2852       gst_structure_get_int (structure, "divxversion", &version);
2853       version = version == 5 ? 1 : 0;
2854     } else {
2855       gst_structure_get_int (structure, "mpegversion", &version);
2856       version = version == 4 ? 1 : 0;
2857     }
2858     if (version) {
2859       entry.fourcc = FOURCC_mp4v;
2860       ext_atom =
2861           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
2862           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
2863           qtpad->max_bitrate);
2864       if (ext_atom != NULL)
2865         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2866       if (!codec_data)
2867         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
2868             "output might not play in Apple QuickTime (try global-headers?)");
2869     }
2870   } else if (strcmp (mimetype, "video/x-h264") == 0) {
2871     /* check if we accept these caps */
2872     if (gst_structure_has_field (structure, "stream-format")) {
2873       const gchar *format;
2874       const gchar *alignment;
2875
2876       format = gst_structure_get_string (structure, "stream-format");
2877       alignment = gst_structure_get_string (structure, "alignment");
2878
2879       if (strcmp (format, "avc") != 0 || alignment == NULL ||
2880           strcmp (alignment, "au") != 0) {
2881         GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
2882             "avc format with AU aligned samples");
2883         goto refuse_caps;
2884       }
2885     } else {
2886       GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
2887       goto refuse_caps;
2888     }
2889
2890     if (!codec_data) {
2891       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
2892       goto refuse_caps;
2893     }
2894
2895     entry.fourcc = FOURCC_avc1;
2896     if (qtpad->avg_bitrate == 0) {
2897       gint avg_bitrate = 0;
2898       gst_structure_get_int (structure, "bitrate", &avg_bitrate);
2899       qtpad->avg_bitrate = avg_bitrate;
2900     }
2901     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
2902     if (ext_atom != NULL)
2903       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2904     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
2905     if (ext_atom != NULL)
2906       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2907     qtpad->have_dts = TRUE;
2908   } else if (strcmp (mimetype, "video/x-svq") == 0) {
2909     gint version = 0;
2910     const GstBuffer *seqh = NULL;
2911     const GValue *seqh_value;
2912     gdouble gamma = 0;
2913
2914     gst_structure_get_int (structure, "svqversion", &version);
2915     if (version == 3) {
2916       entry.fourcc = FOURCC_SVQ3;
2917       entry.version = 3;
2918       entry.depth = 32;
2919
2920       seqh_value = gst_structure_get_value (structure, "seqh");
2921       if (seqh_value) {
2922         seqh = gst_value_get_buffer (seqh_value);
2923         ext_atom = build_SMI_atom (seqh);
2924         if (ext_atom)
2925           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2926       }
2927
2928       /* we need to add the gamma anyway because quicktime might crash
2929        * when it doesn't find it */
2930       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
2931         /* it seems that using 0 here makes it ignored */
2932         gamma = 0.0;
2933       }
2934       ext_atom = build_gama_atom (gamma);
2935       if (ext_atom)
2936         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2937     } else {
2938       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
2939           "a bug at http://bugzilla.gnome.org", version);
2940     }
2941   } else if (strcmp (mimetype, "video/x-dv") == 0) {
2942     gint version = 0;
2943     gboolean pal = TRUE;
2944
2945     sync = FALSE;
2946     if (framerate_num != 25 || framerate_den != 1)
2947       pal = FALSE;
2948     gst_structure_get_int (structure, "dvversion", &version);
2949     /* fall back to typical one */
2950     if (!version)
2951       version = 25;
2952     switch (version) {
2953       case 25:
2954         if (pal)
2955           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
2956         else
2957           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
2958         break;
2959       case 50:
2960         if (pal)
2961           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
2962         else
2963           entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
2964         break;
2965       default:
2966         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
2967         break;
2968     }
2969   } else if (strcmp (mimetype, "image/jpeg") == 0) {
2970     entry.fourcc = FOURCC_jpeg;
2971     sync = FALSE;
2972   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
2973       strcmp (mimetype, "image/x-jpc") == 0) {
2974     const gchar *colorspace;
2975     const GValue *cmap_array;
2976     const GValue *cdef_array;
2977     gint ncomp = 0;
2978     gint fields = 1;
2979
2980     if (strcmp (mimetype, "image/x-jpc") == 0) {
2981       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
2982     }
2983
2984     gst_structure_get_int (structure, "num-components", &ncomp);
2985     gst_structure_get_int (structure, "fields", &fields);
2986     cmap_array = gst_structure_get_value (structure, "component-map");
2987     cdef_array = gst_structure_get_value (structure, "channel-definitions");
2988
2989     ext_atom = NULL;
2990     entry.fourcc = FOURCC_mjp2;
2991     sync = FALSE;
2992
2993     colorspace = gst_structure_get_string (structure, "colorspace");
2994     if (colorspace &&
2995         (ext_atom =
2996             build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
2997                 cmap_array, cdef_array)) != NULL) {
2998       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
2999
3000       ext_atom = build_fiel_extension (fields);
3001       if (ext_atom)
3002         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3003
3004       ext_atom = build_jp2x_extension (codec_data);
3005       if (ext_atom)
3006         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3007     } else {
3008       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3009       goto refuse_caps;
3010     }
3011   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3012     entry.fourcc = FOURCC_VP80;
3013     sync = FALSE;
3014   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3015     entry.fourcc = FOURCC_drac;
3016     qtpad->have_dts = TRUE;
3017   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3018     guint32 fourcc;
3019
3020     gst_structure_get_uint (structure, "format", &fourcc);
3021     entry.fourcc = fourcc;
3022     qtpad->have_dts = TRUE;
3023   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3024     guint32 fourcc;
3025
3026     gst_structure_get_uint (structure, "format", &fourcc);
3027     entry.fourcc = fourcc;
3028     qtpad->have_dts = TRUE;
3029   }
3030
3031   if (!entry.fourcc)
3032     goto refuse_caps;
3033
3034   /* ok, set the pad info accordingly */
3035   qtpad->fourcc = entry.fourcc;
3036   qtpad->sync = sync;
3037   atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3038       ext_atom_list);
3039
3040   gst_object_unref (qtmux);
3041   return TRUE;
3042
3043   /* ERRORS */
3044 refuse_caps:
3045   {
3046     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3047         GST_PAD_NAME (pad), caps);
3048     gst_object_unref (qtmux);
3049     return FALSE;
3050   }
3051 refuse_renegotiation:
3052   {
3053     GST_WARNING_OBJECT (qtmux,
3054         "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
3055         caps);
3056     gst_object_unref (qtmux);
3057     return FALSE;
3058   }
3059 }
3060
3061 static gboolean
3062 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
3063     GstEvent * event, gpointer user_data)
3064 {
3065   GstQTMux *qtmux;
3066   guint32 avg_bitrate = 0, max_bitrate = 0;
3067   GstPad *pad = data->pad;
3068   gboolean ret = TRUE;
3069
3070   qtmux = GST_QT_MUX_CAST (user_data);
3071   switch (GST_EVENT_TYPE (event)) {
3072     case GST_EVENT_CAPS:
3073     {
3074       GstCaps *caps;
3075       GstQTPad *collect_pad;
3076
3077       gst_event_parse_caps (event, &caps);
3078
3079       /* find stream data */
3080       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
3081       g_assert (collect_pad);
3082       g_assert (collect_pad->set_caps);
3083
3084       ret = collect_pad->set_caps (pad, caps);
3085       gst_event_unref (event);
3086       event = NULL;
3087       break;
3088     }
3089     case GST_EVENT_TAG:{
3090       GstTagList *list;
3091       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3092       GstTagMergeMode mode;
3093       gchar *code;
3094
3095       GST_OBJECT_LOCK (qtmux);
3096       mode = gst_tag_setter_get_tag_merge_mode (setter);
3097
3098       gst_event_parse_tag (event, &list);
3099       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
3100           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
3101
3102       gst_tag_setter_merge_tags (setter, list, mode);
3103       GST_OBJECT_UNLOCK (qtmux);
3104
3105       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3106           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3107         GstQTPad *qtpad = gst_pad_get_element_private (pad);
3108         g_assert (qtpad);
3109
3110         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3111           qtpad->avg_bitrate = avg_bitrate;
3112         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3113           qtpad->max_bitrate = max_bitrate;
3114       }
3115
3116       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
3117         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
3118         if (iso_code) {
3119           GstQTPad *qtpad = gst_pad_get_element_private (pad);
3120           g_assert (qtpad);
3121           if (qtpad->trak) {
3122             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
3123             qtpad->trak->mdia.mdhd.language_code =
3124                 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
3125                 (iso_code[2] - 0x60);
3126           }
3127         }
3128         g_free (code);
3129       }
3130
3131       gst_event_unref (event);
3132       event = NULL;
3133       ret = TRUE;
3134       break;
3135     }
3136     default:
3137       break;
3138   }
3139
3140   if (event != NULL)
3141     return gst_collect_pads_event_default (pads, data, event, FALSE);
3142
3143   return ret;
3144 }
3145
3146 static void
3147 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3148 {
3149   GstQTMux *mux = GST_QT_MUX_CAST (element);
3150   GSList *walk;
3151
3152   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3153
3154   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3155     GstQTPad *qtpad = (GstQTPad *) walk->data;
3156     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3157     if (qtpad->collect.pad == pad) {
3158       /* this is it, remove */
3159       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3160       gst_element_remove_pad (element, pad);
3161       break;
3162     }
3163   }
3164
3165   gst_collect_pads_remove_pad (mux->collect, pad);
3166 }
3167
3168 static GstPad *
3169 gst_qt_mux_request_new_pad (GstElement * element,
3170     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
3171 {
3172   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3173   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3174   GstQTPad *collect_pad;
3175   GstPad *newpad;
3176   gboolean audio;
3177   gchar *name;
3178   gint pad_id;
3179
3180   if (templ->direction != GST_PAD_SINK)
3181     goto wrong_direction;
3182
3183   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3184     goto too_late;
3185
3186   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
3187     audio = TRUE;
3188     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
3189       name = g_strdup (req_name);
3190     } else {
3191       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
3192     }
3193   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
3194     audio = FALSE;
3195     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
3196       name = g_strdup (req_name);
3197     } else {
3198       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
3199     }
3200   } else
3201     goto wrong_template;
3202
3203   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3204
3205   /* create pad and add to collections */
3206   newpad = gst_pad_new_from_template (templ, name);
3207   g_free (name);
3208   collect_pad = (GstQTPad *)
3209       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
3210       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), TRUE);
3211   /* set up pad */
3212   gst_qt_mux_pad_reset (collect_pad);
3213   collect_pad->trak = atom_trak_new (qtmux->context);
3214   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3215
3216   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3217
3218   /* set up pad functions */
3219   if (audio)
3220     collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps);
3221   else
3222     collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps);
3223
3224   gst_pad_set_active (newpad, TRUE);
3225   gst_element_add_pad (element, newpad);
3226
3227   return newpad;
3228
3229   /* ERRORS */
3230 wrong_direction:
3231   {
3232     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3233     return NULL;
3234   }
3235 too_late:
3236   {
3237     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3238     return NULL;
3239   }
3240 wrong_template:
3241   {
3242     GST_WARNING_OBJECT (qtmux, "This is not our template!");
3243     return NULL;
3244   }
3245 }
3246
3247 static void
3248 gst_qt_mux_get_property (GObject * object,
3249     guint prop_id, GValue * value, GParamSpec * pspec)
3250 {
3251   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3252
3253   GST_OBJECT_LOCK (qtmux);
3254   switch (prop_id) {
3255     case PROP_MOVIE_TIMESCALE:
3256       g_value_set_uint (value, qtmux->timescale);
3257       break;
3258     case PROP_TRAK_TIMESCALE:
3259       g_value_set_uint (value, qtmux->trak_timescale);
3260       break;
3261     case PROP_DO_CTTS:
3262       g_value_set_boolean (value, qtmux->guess_pts);
3263       break;
3264     case PROP_DTS_METHOD:
3265       g_value_set_enum (value, qtmux->dts_method);
3266       break;
3267     case PROP_FAST_START:
3268       g_value_set_boolean (value, qtmux->fast_start);
3269       break;
3270     case PROP_FAST_START_TEMP_FILE:
3271       g_value_set_string (value, qtmux->fast_start_file_path);
3272       break;
3273     case PROP_MOOV_RECOV_FILE:
3274       g_value_set_string (value, qtmux->moov_recov_file_path);
3275       break;
3276     case PROP_FRAGMENT_DURATION:
3277       g_value_set_uint (value, qtmux->fragment_duration);
3278       break;
3279     case PROP_STREAMABLE:
3280       g_value_set_boolean (value, qtmux->streamable);
3281       break;
3282     default:
3283       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3284       break;
3285   }
3286   GST_OBJECT_UNLOCK (qtmux);
3287 }
3288
3289 static void
3290 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3291 {
3292   gchar *tmp;
3293
3294   g_free (qtmux->fast_start_file_path);
3295   qtmux->fast_start_file_path = NULL;
3296
3297   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3298   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3299   g_free (tmp);
3300 }
3301
3302 static void
3303 gst_qt_mux_set_property (GObject * object,
3304     guint prop_id, const GValue * value, GParamSpec * pspec)
3305 {
3306   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3307
3308   GST_OBJECT_LOCK (qtmux);
3309   switch (prop_id) {
3310     case PROP_MOVIE_TIMESCALE:
3311       qtmux->timescale = g_value_get_uint (value);
3312       break;
3313     case PROP_TRAK_TIMESCALE:
3314       qtmux->trak_timescale = g_value_get_uint (value);
3315       break;
3316     case PROP_DO_CTTS:
3317       qtmux->guess_pts = g_value_get_boolean (value);
3318       break;
3319     case PROP_DTS_METHOD:
3320       qtmux->dts_method = g_value_get_enum (value);
3321       break;
3322     case PROP_FAST_START:
3323       qtmux->fast_start = g_value_get_boolean (value);
3324       break;
3325     case PROP_FAST_START_TEMP_FILE:
3326       g_free (qtmux->fast_start_file_path);
3327       qtmux->fast_start_file_path = g_value_dup_string (value);
3328       /* NULL means to generate a random one */
3329       if (!qtmux->fast_start_file_path) {
3330         gst_qt_mux_generate_fast_start_file_path (qtmux);
3331       }
3332       break;
3333     case PROP_MOOV_RECOV_FILE:
3334       g_free (qtmux->moov_recov_file_path);
3335       qtmux->moov_recov_file_path = g_value_dup_string (value);
3336       break;
3337     case PROP_FRAGMENT_DURATION:
3338       qtmux->fragment_duration = g_value_get_uint (value);
3339       break;
3340     case PROP_STREAMABLE:
3341       qtmux->streamable = g_value_get_boolean (value);
3342       break;
3343     default:
3344       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3345       break;
3346   }
3347   GST_OBJECT_UNLOCK (qtmux);
3348 }
3349
3350 static GstStateChangeReturn
3351 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3352 {
3353   GstStateChangeReturn ret;
3354   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3355
3356   switch (transition) {
3357     case GST_STATE_CHANGE_NULL_TO_READY:
3358       break;
3359     case GST_STATE_CHANGE_READY_TO_PAUSED:
3360       gst_collect_pads_start (qtmux->collect);
3361       qtmux->state = GST_QT_MUX_STATE_STARTED;
3362       break;
3363     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3364       break;
3365     case GST_STATE_CHANGE_PAUSED_TO_READY:
3366       gst_collect_pads_stop (qtmux->collect);
3367       break;
3368     default:
3369       break;
3370   }
3371
3372   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3373
3374   switch (transition) {
3375     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3376       break;
3377     case GST_STATE_CHANGE_PAUSED_TO_READY:
3378       gst_qt_mux_reset (qtmux, TRUE);
3379       break;
3380     case GST_STATE_CHANGE_READY_TO_NULL:
3381       break;
3382     default:
3383       break;
3384   }
3385
3386   return ret;
3387 }
3388
3389 gboolean
3390 gst_qt_mux_register (GstPlugin * plugin)
3391 {
3392   GTypeInfo typeinfo = {
3393     sizeof (GstQTMuxClass),
3394     (GBaseInitFunc) gst_qt_mux_base_init,
3395     NULL,
3396     (GClassInitFunc) gst_qt_mux_class_init,
3397     NULL,
3398     NULL,
3399     sizeof (GstQTMux),
3400     0,
3401     (GInstanceInitFunc) gst_qt_mux_init,
3402   };
3403   static const GInterfaceInfo tag_setter_info = {
3404     NULL, NULL, NULL
3405   };
3406   static const GInterfaceInfo tag_xmp_writer_info = {
3407     NULL, NULL, NULL
3408   };
3409   GType type;
3410   GstQTMuxFormat format;
3411   GstQTMuxClassParams *params;
3412   guint i = 0;
3413
3414   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3415
3416   GST_LOG ("Registering muxers");
3417
3418   while (TRUE) {
3419     GstQTMuxFormatProp *prop;
3420
3421     prop = &gst_qt_mux_format_list[i];
3422     format = prop->format;
3423     if (format == GST_QT_MUX_FORMAT_NONE)
3424       break;
3425
3426     /* create a cache for these properties */
3427     params = g_new0 (GstQTMuxClassParams, 1);
3428     params->prop = prop;
3429     params->src_caps = gst_static_caps_get (&prop->src_caps);
3430     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3431     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3432
3433     /* create the type now */
3434     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3435         0);
3436     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3437     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3438     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3439         &tag_xmp_writer_info);
3440
3441     if (!gst_element_register (plugin, prop->name, prop->rank, type))
3442       return FALSE;
3443
3444     i++;
3445   }
3446
3447   GST_LOG ("Finished registering muxers");
3448
3449   /* FIXME: ideally classification tag should be added and
3450      registered in gstreamer core gsttaglist
3451    */
3452
3453   GST_LOG ("Registering tags");
3454
3455   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3456       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3457       gst_tag_merge_use_first);
3458
3459   GST_LOG ("Finished registering tags");
3460
3461   return TRUE;
3462 }