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