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