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