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