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