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