1 /* Quicktime muxer plugin for GStreamer
2 * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3 * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4 * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5 * Contact: Stefan Kost <stefan.kost@nokia.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
23 * Unless otherwise indicated, Source Code is licensed under MIT license.
24 * See further explanation attached in License Statement (distributed in the file
27 * Permission is hereby granted, free of charge, to any person obtaining a copy of
28 * this software and associated documentation files (the "Software"), to deal in
29 * the Software without restriction, including without limitation the rights to
30 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
31 * of the Software, and to permit persons to whom the Software is furnished to do
32 * so, subject to the following conditions:
34 * The above copyright notice and this permission notice shall be included in all
35 * copies or substantial portions of the Software.
37 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
38 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
40 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
41 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
42 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48 * SECTION:element-qtmux
49 * @short_description: Muxer for quicktime(.mov) files
51 * This element merges streams (audio and video) into QuickTime(.mov) files.
53 * The following background intends to explain why various similar muxers
54 * are present in this plugin.
56 * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
57 * QuickTime file format specification</ulink> served as basis for the MP4 file
58 * format specification (mp4mux), and as such the QuickTime file structure is
59 * nearly identical to the so-called ISO Base Media file format defined in
60 * ISO 14496-12 (except for some media specific parts).
61 * In turn, the latter ISO Base Media format was further specialized as a
62 * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
63 * and in various 3GPP(2) specs (gppmux).
64 * The fragmented file features defined (only) in ISO Base Media are used by
65 * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
67 * A few properties (<link linkend="GstQTMux--movie-timescale">movie-timescale</link>,
68 * <link linkend="GstQTMux--trak-timescale">trak-timescale</link>) allow adjusting
69 * some technical parameters, which might be useful in (rare) cases to resolve
70 * compatibility issues in some situations.
72 * Some other properties influence the result more fundamentally.
73 * A typical mov/mp4 file's metadata (aka moov) is located at the end of the file,
74 * somewhat contrary to this usually being called "the header".
75 * However, a <link linkend="GstQTMux--faststart">faststart</link> file will
76 * (with some effort) arrange this to be located near start of the file,
77 * which then allows it e.g. to be played while downloading.
78 * Alternatively, rather than having one chunk of metadata at start (or end),
79 * there can be some metadata at start and most of the other data can be spread
80 * out into fragments of <link linkend="GstQTMux--fragment-duration">fragment-duration</link>.
81 * If such fragmented layout is intended for streaming purposes, then
82 * <link linkend="GstQTMux--streamable">streamable</link> allows foregoing to add
83 * index metadata (at the end of file).
85 * <link linkend="GstQTMux--dts-method">dts-method</link> allows selecting a
86 * method for managing input timestamps (stay tuned for 0.11 to have this
87 * automagically settled). The default delta/duration method should handle nice
88 * (aka perfect streams) just fine, but may experience problems otherwise
89 * (e.g. input stream with re-ordered B-frames and/or with frame dropping).
90 * The re-ordering approach re-assigns incoming timestamps in ascending order
91 * to incoming buffers and offers an alternative in such cases. In cases where
92 * that might fail, the remaining method can be tried, which is exact and
93 * according to specs, but might experience playback on not so spec-wise players.
94 * Note that this latter approach also requires one to enable
95 * <link linkend="GstQTMux--presentation-timestamp">presentation-timestamp</link>.
98 * <title>Example pipelines</title>
100 * gst-launch v4l2src num-buffers=500 ! video/x-raw-yuv,width=320,height=240 ! ffmpegcolorspace ! qtmux ! filesink location=video.mov
102 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
105 * Last reviewed on 2010-12-03
116 #include <glib/gstdio.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/tag/xmpwriter.h>
122 #include <sys/types.h>
124 #include <io.h> /* lseek, open, close, read */
126 #define lseek _lseeki64
128 #define off_t guint64
132 #define ftruncate g_win32_ftruncate
139 #include "gstqtmux.h"
141 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
142 #define GST_CAT_DEFAULT gst_qt_mux_debug
152 gst_qt_mux_dts_method_get_type (void)
154 static GType gst_qt_mux_dts_method = 0;
156 if (!gst_qt_mux_dts_method) {
157 static const GEnumValue dts_methods[] = {
158 {DTS_METHOD_DD, "delta/duration", "dd"},
159 {DTS_METHOD_REORDER, "reorder", "reorder"},
160 {DTS_METHOD_ASC, "ascending", "asc"},
164 gst_qt_mux_dts_method =
165 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
168 return gst_qt_mux_dts_method;
171 #define GST_TYPE_QT_MUX_DTS_METHOD \
172 (gst_qt_mux_dts_method_get_type ())
174 /* QTMux signals and args */
184 PROP_MOVIE_TIMESCALE,
187 PROP_FAST_START_TEMP_FILE,
188 PROP_MOOV_RECOV_FILE,
189 PROP_FRAGMENT_DURATION,
195 /* some spare for header size as well */
196 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
197 #define MAX_TOLERATED_LATENESS (GST_SECOND / 10)
199 #define DEFAULT_MOVIE_TIMESCALE 1000
200 #define DEFAULT_TRAK_TIMESCALE 0
201 #define DEFAULT_DO_CTTS TRUE
202 #define DEFAULT_FAST_START FALSE
203 #define DEFAULT_FAST_START_TEMP_FILE NULL
204 #define DEFAULT_MOOV_RECOV_FILE NULL
205 #define DEFAULT_FRAGMENT_DURATION 0
206 #define DEFAULT_STREAMABLE FALSE
207 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
210 static void gst_qt_mux_finalize (GObject * object);
212 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
213 GstStateChange transition);
215 /* property functions */
216 static void gst_qt_mux_set_property (GObject * object,
217 guint prop_id, const GValue * value, GParamSpec * pspec);
218 static void gst_qt_mux_get_property (GObject * object,
219 guint prop_id, GValue * value, GParamSpec * pspec);
222 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
223 GstPadTemplate * templ, const gchar * name);
224 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
227 static gboolean gst_qt_mux_sink_event (GstPad * pad, GstEvent * event);
229 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
231 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
234 static GstElementClass *parent_class = NULL;
237 gst_qt_mux_base_init (gpointer g_class)
239 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
240 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
241 GstQTMuxClassParams *params;
242 GstPadTemplate *videosinktempl, *audiosinktempl, *srctempl;
243 gchar *longname, *description;
246 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
247 GST_QT_MUX_PARAMS_QDATA);
248 g_assert (params != NULL);
250 /* construct the element details struct */
251 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
252 description = g_strdup_printf ("Multiplex audio and video into a %s file%s",
253 params->prop->long_name,
254 (params->prop->rank == GST_RANK_NONE) ? " (deprecated)" : "");
255 gst_element_class_set_details_simple (element_class, longname,
256 "Codec/Muxer", description,
257 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
259 g_free (description);
262 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
263 GST_PAD_ALWAYS, params->src_caps);
264 gst_element_class_add_pad_template (element_class, srctempl);
265 gst_object_unref (srctempl);
267 if (params->audio_sink_caps) {
268 audiosinktempl = gst_pad_template_new ("audio_%d",
269 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
270 gst_element_class_add_pad_template (element_class, audiosinktempl);
271 gst_object_unref (audiosinktempl);
274 if (params->video_sink_caps) {
275 videosinktempl = gst_pad_template_new ("video_%d",
276 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
277 gst_element_class_add_pad_template (element_class, videosinktempl);
278 gst_object_unref (videosinktempl);
281 klass->format = params->prop->format;
285 gst_qt_mux_class_init (GstQTMuxClass * klass)
287 GObjectClass *gobject_class;
288 GstElementClass *gstelement_class;
290 gobject_class = (GObjectClass *) klass;
291 gstelement_class = (GstElementClass *) klass;
293 parent_class = g_type_class_peek_parent (klass);
295 gobject_class->finalize = gst_qt_mux_finalize;
296 gobject_class->get_property = gst_qt_mux_get_property;
297 gobject_class->set_property = gst_qt_mux_set_property;
299 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
300 g_param_spec_uint ("movie-timescale", "Movie timescale",
301 "Timescale to use in the movie (units per second)",
302 1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
303 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
304 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
305 g_param_spec_uint ("trak-timescale", "Track timescale",
306 "Timescale to use for the tracks (units per second, 0 is automatic)",
307 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
308 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
309 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
310 g_param_spec_boolean ("presentation-time",
311 "Include presentation-time info",
312 "Calculate and include presentation/composition time "
313 "(in addition to decoding time)", DEFAULT_DO_CTTS,
314 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
315 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
316 g_param_spec_enum ("dts-method", "dts-method",
317 "Method to determine DTS time",
318 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
319 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
320 g_object_class_install_property (gobject_class, PROP_FAST_START,
321 g_param_spec_boolean ("faststart", "Format file to faststart",
322 "If the file should be formatted for faststart (headers first)",
323 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
324 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
325 g_param_spec_string ("faststart-file", "File to use for storing buffers",
326 "File that will be used temporarily to store data from the stream "
327 "when creating a faststart file. If null a filepath will be "
328 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
329 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
331 g_param_spec_string ("moov-recovery-file",
332 "File to store data for posterior moov atom recovery",
333 "File to be used to store "
334 "data for moov atom making movie file recovery possible in case "
335 "of a crash during muxing. Null for disabled. (Experimental)",
336 DEFAULT_MOOV_RECOV_FILE,
337 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
338 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
339 g_param_spec_uint ("fragment-duration", "Fragment duration",
340 "Fragment durations in ms (produce a fragmented file if > 0)",
341 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
342 2000 : DEFAULT_FRAGMENT_DURATION,
343 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
344 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
345 g_param_spec_boolean ("streamable", "Streamable",
346 "If set to true, the output should be as if it is to be streamed "
347 "and hence no indexes written or duration written.",
349 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
351 gstelement_class->request_new_pad =
352 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
353 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
354 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
358 gst_qt_mux_pad_reset (GstQTPad * qtpad)
363 qtpad->is_out_of_order = FALSE;
364 qtpad->have_dts = FALSE;
365 qtpad->sample_size = 0;
368 qtpad->first_ts = GST_CLOCK_TIME_NONE;
369 qtpad->prepare_buf_func = NULL;
370 qtpad->avg_bitrate = 0;
371 qtpad->max_bitrate = 0;
372 qtpad->ts_n_entries = 0;
373 qtpad->total_duration = 0;
374 qtpad->total_bytes = 0;
378 for (i = 0; i < G_N_ELEMENTS (qtpad->buf_entries); i++) {
379 if (qtpad->buf_entries[i]) {
380 gst_buffer_unref (qtpad->buf_entries[i]);
381 qtpad->buf_entries[i] = NULL;
386 gst_buffer_replace (&qtpad->last_buf, NULL);
388 /* reference owned elsewhere */
392 atom_traf_free (qtpad->traf);
395 atom_array_clear (&qtpad->fragment_buffers);
397 /* reference owned elsewhere */
402 * Takes GstQTMux back to its initial state
405 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
409 qtmux->state = GST_QT_MUX_STATE_NONE;
410 qtmux->header_size = 0;
411 qtmux->mdat_size = 0;
413 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
414 qtmux->video_pads = 0;
415 qtmux->audio_pads = 0;
416 qtmux->fragment_sequence = 0;
419 atom_ftyp_free (qtmux->ftyp);
423 atom_moov_free (qtmux->moov);
427 atom_mfra_free (qtmux->mfra);
430 if (qtmux->fast_start_file) {
431 fclose (qtmux->fast_start_file);
432 g_remove (qtmux->fast_start_file_path);
433 qtmux->fast_start_file = NULL;
435 if (qtmux->moov_recov_file) {
436 fclose (qtmux->moov_recov_file);
437 qtmux->moov_recov_file = NULL;
439 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
440 AtomInfo *ainfo = (AtomInfo *) walk->data;
441 ainfo->free_func (ainfo->atom);
444 g_slist_free (qtmux->extra_atoms);
445 qtmux->extra_atoms = NULL;
447 GST_OBJECT_LOCK (qtmux);
448 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
449 GST_OBJECT_UNLOCK (qtmux);
452 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
453 GstQTPad *qtpad = (GstQTPad *) walk->data;
454 gst_qt_mux_pad_reset (qtpad);
456 /* hm, moov_free above yanked the traks away from us,
457 * so do not free, but do clear */
462 qtmux->moov = atom_moov_new (qtmux->context);
463 /* ensure all is as nice and fresh as request_new_pad would provide it */
464 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
465 GstQTPad *qtpad = (GstQTPad *) walk->data;
467 qtpad->trak = atom_trak_new (qtmux->context);
468 atom_moov_add_trak (qtmux->moov, qtpad->trak);
474 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
476 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
477 GstPadTemplate *templ;
479 templ = gst_element_class_get_pad_template (klass, "src");
480 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
481 gst_pad_use_fixed_caps (qtmux->srcpad);
482 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
484 qtmux->sinkpads = NULL;
485 qtmux->collect = gst_collect_pads_new ();
486 gst_collect_pads_set_function (qtmux->collect,
487 (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
489 /* properties set to default upon construction */
491 /* always need this */
493 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
495 /* internals to initial state */
496 gst_qt_mux_reset (qtmux, TRUE);
501 gst_qt_mux_finalize (GObject * object)
503 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
505 gst_qt_mux_reset (qtmux, FALSE);
507 g_free (qtmux->fast_start_file_path);
508 g_free (qtmux->moov_recov_file_path);
510 atoms_context_free (qtmux->context);
511 gst_object_unref (qtmux->collect);
513 g_slist_free (qtmux->sinkpads);
515 G_OBJECT_CLASS (parent_class)->finalize (object);
519 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
524 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
529 newbuf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buf) + 8);
530 gst_buffer_copy_metadata (newbuf, buf, GST_BUFFER_COPY_ALL);
532 GST_WRITE_UINT32_BE (GST_BUFFER_DATA (newbuf), GST_BUFFER_SIZE (newbuf));
533 GST_WRITE_UINT32_LE (GST_BUFFER_DATA (newbuf) + 4, FOURCC_jp2c);
535 memcpy (GST_BUFFER_DATA (newbuf) + 8, GST_BUFFER_DATA (buf),
536 GST_BUFFER_SIZE (buf));
537 gst_buffer_unref (buf);
543 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
544 const char *tag, const char *tag2, guint32 fourcc)
546 switch (gst_tag_get_type (tag)) {
552 if (!gst_tag_list_get_string (list, tag, &str) || !str)
554 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
555 GST_FOURCC_ARGS (fourcc), str);
556 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
565 if (!gst_tag_list_get_double (list, tag, &value))
567 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
568 GST_FOURCC_ARGS (fourcc), (gint) value);
569 atom_moov_add_uint_tag (qtmux->moov, fourcc, 21, (gint) value);
576 /* paired unsigned integers */
580 got_tag = gst_tag_list_get_uint (list, tag, &value);
581 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
584 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
585 GST_FOURCC_ARGS (fourcc), value, count);
586 atom_moov_add_uint_tag (qtmux->moov, fourcc, 0,
587 value << 16 | (count & 0xFFFF));
589 /* unpaired unsigned integers */
590 if (!gst_tag_list_get_uint (list, tag, &value))
592 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
593 GST_FOURCC_ARGS (fourcc), value);
594 atom_moov_add_uint_tag (qtmux->moov, fourcc, 1, value);
599 g_assert_not_reached ();
605 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
606 const char *tag, const char *tag2, guint32 fourcc)
614 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_DATE);
616 if (!gst_tag_list_get_date (list, tag, &date) || !date)
619 year = g_date_get_year (date);
620 month = g_date_get_month (date);
621 day = g_date_get_day (date);
625 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
626 day == G_DATE_BAD_DAY) {
627 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
631 str = g_strdup_printf ("%u-%u-%u", year, month, day);
632 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
633 GST_FOURCC_ARGS (fourcc), str);
634 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
639 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
640 const char *tag, const char *tag2, guint32 fourcc)
642 GValue value = { 0, };
645 GstStructure *structure;
648 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_BUFFER);
650 if (!gst_tag_list_copy_value (&value, list, tag))
653 buf = gst_value_get_buffer (&value);
657 caps = gst_buffer_get_caps (buf);
659 GST_WARNING_OBJECT (qtmux, "preview image without caps");
663 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
665 structure = gst_caps_get_structure (caps, 0);
666 if (gst_structure_has_name (structure, "image/jpeg"))
668 else if (gst_structure_has_name (structure, "image/png"))
670 gst_caps_unref (caps);
673 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
677 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
678 " -> image size %d", GST_FOURCC_ARGS (fourcc), GST_BUFFER_SIZE (buf));
679 atom_moov_add_tag (qtmux->moov, fourcc, flags, GST_BUFFER_DATA (buf),
680 GST_BUFFER_SIZE (buf));
682 g_value_unset (&value);
686 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
687 const char *tag, const char *tag2, guint32 fourcc)
692 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
693 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
695 if (!gst_tag_list_get_string (list, tag, &str) || !str)
699 if (!gst_tag_list_get_uint (list, tag2, &number))
703 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
704 GST_FOURCC_ARGS (fourcc), str);
705 atom_moov_add_3gp_str_tag (qtmux->moov, fourcc, str);
707 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
708 GST_FOURCC_ARGS (fourcc), str, number);
709 atom_moov_add_3gp_str_int_tag (qtmux->moov, fourcc, str, number);
716 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
717 const char *tag, const char *tag2, guint32 fourcc)
722 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_DATE);
724 if (!gst_tag_list_get_date (list, tag, &date) || !date)
727 year = g_date_get_year (date);
729 if (year == G_DATE_BAD_YEAR) {
730 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
734 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
735 GST_FOURCC_ARGS (fourcc), year);
736 atom_moov_add_3gp_uint_tag (qtmux->moov, fourcc, year);
740 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
741 const char *tag, const char *tag2, guint32 fourcc)
743 gdouble latitude = -360, longitude = -360, altitude = 0;
744 gchar *location = NULL;
745 guint8 *data, *ddata;
746 gint size = 0, len = 0;
747 gboolean ret = FALSE;
749 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
751 ret = gst_tag_list_get_string (list, tag, &location);
752 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
754 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
756 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
763 len = strlen (location);
766 /* role + (long, lat, alt) + body + notes */
767 size += 1 + 3 * 4 + 1 + 1;
769 data = ddata = g_malloc (size);
772 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
775 memcpy (data + 2, location, len);
776 GST_WRITE_UINT8 (data + 2 + len, 0);
779 GST_WRITE_UINT8 (data, 0);
781 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
782 QT_WRITE_SFP32 (data + 1, longitude);
783 QT_WRITE_SFP32 (data + 5, latitude);
784 QT_WRITE_SFP32 (data + 9, altitude);
785 /* neither astronomical body nor notes */
786 GST_WRITE_UINT16_BE (data + 13, 0);
788 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
789 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
794 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
795 const char *tag, const char *tag2, guint32 fourcc)
797 gchar *keywords = NULL;
798 guint8 *data, *ddata;
802 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
804 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
807 kwds = g_strsplit (keywords, ",", 0);
811 for (i = 0; kwds[i]; i++) {
812 /* size byte + null-terminator */
813 size += strlen (kwds[i]) + 1 + 1;
816 /* language tag + count + keywords */
819 data = ddata = g_malloc (size);
822 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
824 GST_WRITE_UINT8 (data + 2, i);
827 for (i = 0; kwds[i]; ++i) {
828 gint len = strlen (kwds[i]);
830 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
831 GST_FOURCC_ARGS (fourcc), kwds[i]);
833 GST_WRITE_UINT8 (data, len + 1);
834 memcpy (data + 1, kwds[i], len + 1);
840 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
845 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
846 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
854 size = strlen (input);
856 if (size < 4 + 3 + 1 + 1 + 1) {
857 /* at least the minimum xxxx://y/z */
858 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
863 /* read the fourcc */
864 memcpy (&fourcc, data, 4);
868 if (strncmp (data, "://", 3) != 0) {
874 /* read the table number */
875 if (sscanf (data, "%d", &table) != 1) {
879 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
880 ", table numbers should be positive, ignoring tag", table);
884 /* find the next / */
885 while (size > 0 && data[0] != '/') {
892 g_assert (data[0] == '/');
901 /* read up the rest of the string */
902 *p_content = g_strdup (data);
903 *p_table = (guint16) table;
909 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
910 "input (%s) didn't match the expected entitycode://table/content",
917 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
918 const char *tag, const char *tag2, guint32 fourcc)
920 gchar *clsf_data = NULL;
924 gchar *content = NULL;
927 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
929 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
932 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
933 GST_FOURCC_ARGS (fourcc), clsf_data);
935 /* parse the string, format is:
936 * entityfourcc://table/content
938 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
942 size = strlen (content) + 1;
944 /* now we have everything, build the atom
945 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
946 data = g_malloc (4 + 2 + 2 + size);
947 GST_WRITE_UINT32_LE (data, entity);
948 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
949 GST_WRITE_UINT16_BE (data + 6, 0);
950 memcpy (data + 8, content, size);
953 atom_moov_add_3gp_tag (qtmux->moov, fourcc, data, 4 + 2 + 2 + size);
957 typedef void (*GstQTMuxAddTagFunc) (GstQTMux * mux, const GstTagList * list,
958 const char *tag, const char *tag2, guint32 fourcc);
961 * Struct to record mappings from gstreamer tags to fourcc codes
963 typedef struct _GstTagToFourcc
967 const gchar *gsttag2;
968 const GstQTMuxAddTagFunc func;
971 /* tag list tags to fourcc matching */
972 static const GstTagToFourcc tag_matches_mp4[] = {
973 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
974 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
975 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
976 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
977 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
978 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
979 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
980 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
981 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
982 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
983 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
984 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
985 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
986 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
987 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
988 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
989 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
990 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
991 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
992 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
993 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
994 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
995 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
996 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
997 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
998 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
999 gst_qt_mux_add_mp4_tag},
1000 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1001 gst_qt_mux_add_mp4_tag},
1002 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1003 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1007 static const GstTagToFourcc tag_matches_3gp[] = {
1008 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1009 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1010 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1011 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1012 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1013 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1014 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1015 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1016 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1017 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1018 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1019 gst_qt_mux_add_3gp_classification},
1023 /* qtdemux produces these for atoms it cannot parse */
1024 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1027 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1029 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1030 GstBuffer *xmp = NULL;
1032 /* adobe specs only have 'quicktime' and 'mp4',
1033 * but I guess we can extrapolate to gpp.
1034 * Keep mj2 out for now as we don't add any tags for it yet.
1035 * If you have further info about xmp on these formats, please share */
1036 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1039 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1041 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1042 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1045 atom_moov_add_xmp_tags (qtmux->moov, xmp);
1048 /* for isom/mp4, it is a top level uuid atom */
1049 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1052 ainfo = build_uuid_xmp_atom (xmp);
1054 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1059 gst_buffer_unref (xmp);
1063 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list)
1065 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1068 const gchar *tag, *tag2;
1069 const GstTagToFourcc *tag_matches;
1071 switch (qtmux_klass->format) {
1072 case GST_QT_MUX_FORMAT_3GP:
1073 tag_matches = tag_matches_3gp;
1075 case GST_QT_MUX_FORMAT_MJ2:
1079 /* sort of iTunes style for mp4 and QT (?) */
1080 tag_matches = tag_matches_mp4;
1087 for (i = 0; tag_matches[i].fourcc; i++) {
1088 fourcc = tag_matches[i].fourcc;
1089 tag = tag_matches[i].gsttag;
1090 tag2 = tag_matches[i].gsttag2;
1092 g_assert (tag_matches[i].func);
1093 tag_matches[i].func (qtmux, list, tag, tag2, fourcc);
1096 /* add unparsed blobs if present */
1097 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1100 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1101 for (i = 0; i < num_tags; ++i) {
1104 GstCaps *caps = NULL;
1106 val = gst_tag_list_get_value_index (list, GST_QT_DEMUX_PRIVATE_TAG, i);
1107 buf = (GstBuffer *) gst_value_get_mini_object (val);
1109 if (buf && (caps = gst_buffer_get_caps (buf))) {
1111 const gchar *style = NULL;
1113 GST_DEBUG_OBJECT (qtmux, "Found private tag %d/%d; size %d, caps %"
1114 GST_PTR_FORMAT, i, num_tags, GST_BUFFER_SIZE (buf), caps);
1115 s = gst_caps_get_structure (caps, 0);
1116 if (s && (style = gst_structure_get_string (s, "style"))) {
1117 /* try to prevent some style tag ending up into another variant
1118 * (todo: make into a list if more cases) */
1119 if ((strcmp (style, "itunes") == 0 &&
1120 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1121 (strcmp (style, "iso") == 0 &&
1122 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1123 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1124 atom_moov_add_blob_tag (qtmux->moov, GST_BUFFER_DATA (buf),
1125 GST_BUFFER_SIZE (buf));
1128 gst_caps_unref (caps);
1137 * Gets the tagsetter iface taglist and puts the known tags
1138 * into the output stream
1141 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1143 const GstTagList *tags;
1145 GST_OBJECT_LOCK (qtmux);
1146 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1147 GST_OBJECT_UNLOCK (qtmux);
1149 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1151 if (tags && !gst_tag_list_is_empty (tags)) {
1152 GstTagList *copy = gst_tag_list_copy (tags);
1154 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1155 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1156 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1157 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1159 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1160 gst_qt_mux_add_metadata_tags (qtmux, copy);
1161 gst_qt_mux_add_xmp_tags (qtmux, copy);
1162 gst_tag_list_free (copy);
1164 GST_DEBUG_OBJECT (qtmux, "No tags received");
1168 static inline GstBuffer *
1169 _gst_buffer_new_take_data (guint8 * data, guint size)
1173 buf = gst_buffer_new ();
1174 GST_BUFFER_DATA (buf) = GST_BUFFER_MALLOCDATA (buf) = data;
1175 GST_BUFFER_SIZE (buf) = size;
1180 static GstFlowReturn
1181 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1188 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1190 data = GST_BUFFER_DATA (buf);
1191 size = GST_BUFFER_SIZE (buf);
1193 GST_LOG_OBJECT (qtmux, "sending buffer size %d", size);
1195 if (mind_fast && qtmux->fast_start_file) {
1198 GST_LOG_OBJECT (qtmux, "to temporary file");
1199 ret = fwrite (data, sizeof (guint8), size, qtmux->fast_start_file);
1200 gst_buffer_unref (buf);
1206 GST_LOG_OBJECT (qtmux, "downstream");
1208 buf = gst_buffer_make_metadata_writable (buf);
1209 gst_buffer_set_caps (buf, GST_PAD_CAPS (qtmux->srcpad));
1210 res = gst_pad_push (qtmux->srcpad, buf);
1213 if (G_LIKELY (offset))
1221 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1222 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1223 return GST_FLOW_ERROR;
1228 gst_qt_mux_seek_to_beginning (FILE * f)
1231 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1233 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1234 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1237 if (fseek (f, (long) 0, SEEK_SET) != 0)
1243 static GstFlowReturn
1244 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1246 GstFlowReturn ret = GST_FLOW_OK;
1247 GstBuffer *buf = NULL;
1249 if (fflush (qtmux->fast_start_file))
1252 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1255 /* hm, this could all take a really really long time,
1256 * but there may not be another way to get moov atom first
1257 * (somehow optimize copy?) */
1258 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1259 while (ret == GST_FLOW_OK) {
1261 const int bufsize = 4096;
1263 buf = gst_buffer_new_and_alloc (bufsize);
1264 r = fread (GST_BUFFER_DATA (buf), sizeof (guint8), bufsize,
1265 qtmux->fast_start_file);
1268 GST_BUFFER_SIZE (buf) = r;
1269 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", r);
1270 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1274 gst_buffer_unref (buf);
1276 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1278 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1286 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1287 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1288 ret = GST_FLOW_ERROR;
1293 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1294 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1295 ret = GST_FLOW_ERROR;
1300 /* clear descriptor so we don't remove temp file later on,
1301 * might be possible to recover */
1302 fclose (qtmux->fast_start_file);
1303 qtmux->fast_start_file = NULL;
1309 * Sends the initial mdat atom fields (size fields and fourcc type),
1310 * the subsequent buffers are considered part of it's data.
1311 * As we can't predict the amount of data that we are going to place in mdat
1312 * we need to record the position of the size field in the stream so we can
1313 * seek back to it later and update when the streams have finished.
1315 static GstFlowReturn
1316 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1321 guint8 *data = NULL;
1324 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1325 "size %" G_GUINT64_FORMAT, size);
1327 node_header = g_malloc0 (sizeof (Atom));
1328 node_header->type = FOURCC_mdat;
1330 /* use extended size */
1331 node_header->size = 1;
1332 node_header->extended_size = 0;
1334 node_header->extended_size = size + 16;
1336 node_header->size = size + 8;
1340 if (atom_copy_data (node_header, &data, &size, &offset) == 0)
1341 goto serialize_error;
1343 buf = _gst_buffer_new_take_data (data, offset);
1344 g_free (node_header);
1346 GST_LOG_OBJECT (qtmux, "Pushing mdat start");
1347 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1352 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1353 ("Failed to serialize mdat"));
1354 return GST_FLOW_ERROR;
1359 * We get the position of the mdat size field, seek back to it
1360 * and overwrite with the real value
1362 static GstFlowReturn
1363 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1364 guint64 mdat_size, guint64 * offset)
1368 gboolean large_file;
1370 large_file = (mdat_size > MDAT_LARGE_FILE_LIMIT);
1375 /* seek and rewrite the header */
1376 event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1377 mdat_pos, GST_CLOCK_TIME_NONE, 0);
1378 gst_pad_push_event (qtmux->srcpad, event);
1381 buf = gst_buffer_new_and_alloc (sizeof (guint64));
1382 GST_WRITE_UINT64_BE (GST_BUFFER_DATA (buf), mdat_size + 16);
1386 buf = gst_buffer_new_and_alloc (16);
1387 data = GST_BUFFER_DATA (buf);
1388 GST_WRITE_UINT32_BE (data, 8);
1389 GST_WRITE_UINT32_LE (data + 4, FOURCC_free);
1390 GST_WRITE_UINT32_BE (data + 8, mdat_size + 8);
1391 GST_WRITE_UINT32_LE (data + 12, FOURCC_mdat);
1394 return gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1397 static GstFlowReturn
1398 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1401 guint64 size = 0, offset = 0;
1402 guint8 *data = NULL;
1404 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1406 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1407 goto serialize_error;
1409 buf = _gst_buffer_new_take_data (data, offset);
1411 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1412 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1417 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1418 ("Failed to serialize ftyp"));
1419 return GST_FLOW_ERROR;
1424 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1425 GstBuffer ** p_prefix)
1427 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1428 guint32 major, version;
1430 GstBuffer *prefix = NULL;
1431 AtomFTYP *ftyp = NULL;
1433 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1435 /* init and send context and ftyp based on current property state */
1436 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1437 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1438 qtmux->fast_start_file != NULL);
1439 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1446 gst_buffer_unref (prefix);
1451 static GstFlowReturn
1452 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1454 GstFlowReturn ret = GST_FLOW_OK;
1455 GstBuffer *prefix = NULL;
1457 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1459 /* init and send context and ftyp based on current property state */
1461 atom_ftyp_free (qtmux->ftyp);
1464 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1466 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1467 if (ret != GST_FLOW_OK)
1470 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1474 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1476 GstStructure *structure;
1477 GValue array = { 0 };
1478 GValue value = { 0 };
1479 GstCaps *caps = GST_PAD_CAPS (mux->srcpad);
1481 caps = gst_caps_copy (GST_PAD_CAPS (mux->srcpad));
1482 structure = gst_caps_get_structure (caps, 0);
1484 g_value_init (&array, GST_TYPE_ARRAY);
1486 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
1487 g_value_init (&value, GST_TYPE_BUFFER);
1488 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1489 gst_value_array_append_value (&array, &value);
1490 g_value_unset (&value);
1492 gst_structure_set_value (structure, "streamheader", &array);
1493 g_value_unset (&array);
1494 gst_pad_set_caps (mux->srcpad, caps);
1495 gst_caps_unref (caps);
1499 gst_qt_mux_configure_moov (GstQTMux * qtmux, guint32 * _timescale)
1501 gboolean fragmented;
1504 GST_OBJECT_LOCK (qtmux);
1505 timescale = qtmux->timescale;
1506 fragmented = qtmux->fragment_sequence > 0;
1507 GST_OBJECT_UNLOCK (qtmux);
1509 /* inform lower layers of our property wishes, and determine duration.
1510 * Let moov take care of this using its list of traks;
1511 * so that released pads are also included */
1512 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1514 atom_moov_update_timescale (qtmux->moov, timescale);
1515 atom_moov_set_fragmented (qtmux->moov, fragmented);
1517 atom_moov_update_duration (qtmux->moov);
1520 *_timescale = timescale;
1523 static GstFlowReturn
1524 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset, gboolean mind_fast)
1526 guint64 offset = 0, size = 0;
1529 GstFlowReturn ret = GST_FLOW_OK;
1531 /* serialize moov */
1534 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1535 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1536 goto serialize_error;
1538 buf = _gst_buffer_new_take_data (data, offset);
1539 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1540 gst_qt_mux_set_header_on_caps (qtmux, buf);
1541 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1548 return GST_FLOW_ERROR;
1552 /* either calculates size of extra atoms or pushes them */
1553 static GstFlowReturn
1554 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1558 guint64 loffset = 0, size = 0;
1560 GstFlowReturn ret = GST_FLOW_OK;
1562 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1563 AtomInfo *ainfo = (AtomInfo *) walk->data;
1567 if (!ainfo->copy_data_func (ainfo->atom,
1568 send ? &data : NULL, &size, &loffset))
1569 goto serialize_error;
1574 GST_DEBUG_OBJECT (qtmux,
1575 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1576 GST_FOURCC_ARGS (ainfo->atom->type));
1577 buf = _gst_buffer_new_take_data (data, loffset);
1578 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1579 if (ret != GST_FLOW_OK)
1592 return GST_FLOW_ERROR;
1596 static GstFlowReturn
1597 gst_qt_mux_start_file (GstQTMux * qtmux)
1599 GstFlowReturn ret = GST_FLOW_OK;
1602 GST_DEBUG_OBJECT (qtmux, "starting file");
1604 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
1605 /* qtmux has structure with and without variant, remove all but the first */
1606 while (gst_caps_get_size (caps) > 1)
1607 gst_caps_remove_structure (caps, 1);
1608 gst_pad_set_caps (qtmux->srcpad, caps);
1609 gst_caps_unref (caps);
1611 /* let downstream know we think in BYTES and expect to do seeking later on */
1612 gst_pad_push_event (qtmux->srcpad,
1613 gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES, 0, -1, 0));
1615 /* initialize our moov recovery file */
1616 GST_OBJECT_LOCK (qtmux);
1617 if (qtmux->moov_recov_file_path) {
1618 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1619 qtmux->moov_recov_file_path);
1620 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1621 if (qtmux->moov_recov_file == NULL) {
1622 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1623 qtmux->moov_recov_file_path);
1626 gboolean fail = FALSE;
1627 AtomFTYP *ftyp = NULL;
1628 GstBuffer *prefix = NULL;
1630 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1632 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1633 qtmux->moov, qtmux->timescale,
1634 g_slist_length (qtmux->sinkpads))) {
1635 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1640 atom_ftyp_free (ftyp);
1642 gst_buffer_unref (prefix);
1644 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1645 GstCollectData *cdata = (GstCollectData *) walk->data;
1646 GstQTPad *qpad = (GstQTPad *) cdata;
1647 /* write info for each stream */
1648 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1650 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1656 fclose (qtmux->moov_recov_file);
1657 qtmux->moov_recov_file = NULL;
1658 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1659 "recover file, moov recovery won't work");
1663 GST_OBJECT_UNLOCK (qtmux);
1666 * send mdat header if already needed, and mark position for later update.
1667 * We don't send ftyp now if we are on fast start mode, because we can
1668 * better fine tune using the information we gather to create the whole moov
1671 if (qtmux->fast_start) {
1672 GST_OBJECT_LOCK (qtmux);
1673 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1674 if (!qtmux->fast_start_file)
1676 GST_OBJECT_UNLOCK (qtmux);
1678 /* send a dummy buffer for preroll */
1679 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1680 if (ret != GST_FLOW_OK)
1684 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1685 if (ret != GST_FLOW_OK) {
1689 /* well, it's moov pos if fragmented ... */
1690 qtmux->mdat_pos = qtmux->header_size;
1692 if (qtmux->fragment_duration) {
1693 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1694 qtmux->fragment_duration);
1695 /* also used as snapshot marker to indicate fragmented file */
1696 qtmux->fragment_sequence = 1;
1697 /* prepare moov and/or tags */
1698 gst_qt_mux_configure_moov (qtmux, NULL);
1699 gst_qt_mux_setup_metadata (qtmux);
1700 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1701 if (ret != GST_FLOW_OK)
1705 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1706 if (ret != GST_FLOW_OK)
1709 if (!qtmux->streamable)
1710 qtmux->mfra = atom_mfra_new (qtmux->context);
1712 /* extended to ensure some spare space */
1713 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1723 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1724 (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1726 GST_OBJECT_UNLOCK (qtmux);
1727 return GST_FLOW_ERROR;
1731 static GstFlowReturn
1732 gst_qt_mux_stop_file (GstQTMux * qtmux)
1734 gboolean ret = GST_FLOW_OK;
1735 guint64 offset = 0, size = 0;
1737 gboolean large_file;
1739 GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1741 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1743 /* pushing last buffers for each pad */
1744 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1745 GstCollectData *cdata = (GstCollectData *) walk->data;
1746 GstQTPad *qtpad = (GstQTPad *) cdata;
1748 /* avoid add_buffer complaining if not negotiated
1749 * in which case no buffers either, so skipping */
1750 if (!qtpad->fourcc) {
1751 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
1752 GST_PAD_NAME (qtpad->collect.pad));
1756 /* send last buffer; also flushes possibly queued buffers/ts */
1757 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1758 GST_PAD_NAME (qtpad->collect.pad));
1759 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1760 if (ret != GST_FLOW_OK) {
1761 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1762 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1763 gst_flow_get_name (ret));
1766 /* having flushed above, can check for buffers now */
1767 if (!GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
1768 GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1769 GST_PAD_NAME (qtpad->collect.pad));
1773 /* determine max stream duration */
1774 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1775 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1776 qtpad->last_dts > first_ts)) {
1777 first_ts = qtpad->last_dts;
1780 /* update average bitrate of streams if needed */
1782 guint32 avgbitrate = 0;
1783 guint32 maxbitrate = qtpad->max_bitrate;
1785 if (qtpad->avg_bitrate)
1786 avgbitrate = qtpad->avg_bitrate;
1787 else if (qtpad->total_duration > 0)
1788 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
1789 8 * GST_SECOND, qtpad->total_duration);
1791 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
1795 if (qtmux->fragment_sequence) {
1799 guint8 *data = NULL;
1803 GST_DEBUG_OBJECT (qtmux, "adding mfra");
1804 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1805 goto serialize_error;
1806 buf = _gst_buffer_new_take_data (data, offset);
1807 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1808 if (ret != GST_FLOW_OK)
1811 /* must have been streamable; no need to write duration */
1812 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1817 timescale = qtmux->timescale;
1818 /* only mvex duration is updated,
1819 * mvhd should be consistent with empty moov
1820 * (but TODO maybe some clients do not handle that well ?) */
1821 qtmux->moov->mvex.mehd.fragment_duration =
1822 gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1823 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1824 GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1825 /* seek and rewrite the header */
1826 event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1827 qtmux->mdat_pos, GST_CLOCK_TIME_NONE, 0);
1828 gst_pad_push_event (qtmux->srcpad, event);
1829 /* no need to seek back */
1830 return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1833 gst_qt_mux_configure_moov (qtmux, ×cale);
1835 /* check for late streams */
1836 first_ts = GST_CLOCK_TIME_NONE;
1837 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1838 GstCollectData *cdata = (GstCollectData *) walk->data;
1839 GstQTPad *qtpad = (GstQTPad *) cdata;
1841 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1842 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1843 qtpad->first_ts < first_ts)) {
1844 first_ts = qtpad->first_ts;
1847 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1848 GST_TIME_ARGS (first_ts));
1849 /* add EDTSs for late streams */
1850 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1851 GstCollectData *cdata = (GstCollectData *) walk->data;
1852 GstQTPad *qtpad = (GstQTPad *) cdata;
1856 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1857 qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1858 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1859 GST_PAD_NAME (qtpad->collect.pad),
1860 GST_TIME_ARGS (qtpad->first_ts - first_ts));
1861 lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1862 timescale, GST_SECOND);
1863 duration = qtpad->trak->tkhd.duration;
1864 atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1865 (guint32) (1 * 65536.0));
1866 atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1867 (guint32) (1 * 65536.0));
1869 /* need to add the empty time to the trak duration */
1870 qtpad->trak->tkhd.duration += lateness;
1874 /* tags into file metadata */
1875 gst_qt_mux_setup_metadata (qtmux);
1877 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1878 /* if faststart, update the offset of the atoms in the movie with the offset
1879 * that the movie headers before mdat will cause.
1880 * Also, send the ftyp */
1881 if (qtmux->fast_start_file) {
1882 GstFlowReturn flow_ret;
1885 flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1886 if (flow_ret != GST_FLOW_OK) {
1889 /* copy into NULL to obtain size */
1890 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1891 goto serialize_error;
1892 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1894 offset += qtmux->header_size + (large_file ? 16 : 8);
1896 /* sum up with the extra atoms size */
1897 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1898 if (ret != GST_FLOW_OK)
1901 offset = qtmux->header_size;
1903 atom_moov_chunks_add_offset (qtmux->moov, offset);
1906 /* note: as of this point, we no longer care about tracking written data size,
1907 * since there is no more use for it anyway */
1908 ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1909 if (ret != GST_FLOW_OK)
1913 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1914 if (ret != GST_FLOW_OK)
1917 /* if needed, send mdat atom and move buffered data into it */
1918 if (qtmux->fast_start_file) {
1919 /* mdat_size = accumulated (buffered data) */
1920 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1922 if (ret != GST_FLOW_OK)
1924 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1925 if (ret != GST_FLOW_OK)
1928 /* mdat needs update iff not using faststart */
1929 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1930 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1931 qtmux->mdat_size, NULL);
1932 /* note; no seeking back to the end of file is done,
1933 * since we no longer write anything anyway */
1941 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1942 ("Failed to serialize moov"));
1943 return GST_FLOW_ERROR;
1947 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1948 return GST_FLOW_ERROR;
1952 static GstFlowReturn
1953 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
1954 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
1955 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
1957 GstFlowReturn ret = GST_FLOW_OK;
1959 /* setup if needed */
1960 if (G_UNLIKELY (!pad->traf || force))
1964 /* flush pad fragment if threshold reached,
1965 * or at new keyframe if we should be minding those in the first place */
1966 if (G_UNLIKELY (force || (sync && pad->sync) ||
1967 pad->fragment_duration < (gint64) delta)) {
1969 guint64 size = 0, offset = 0;
1970 guint8 *data = NULL;
1972 guint i, total_size;
1974 /* now we know where moof ends up, update offset in tfra */
1976 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
1978 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
1979 /* takes ownership */
1980 atom_moof_add_traf (moof, pad->traf);
1982 atom_moof_copy_data (moof, &data, &size, &offset);
1983 buffer = _gst_buffer_new_take_data (data, offset);
1984 GST_LOG_OBJECT (qtmux, "writing moof size %d", GST_BUFFER_SIZE (buffer));
1985 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
1987 /* and actual data */
1989 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
1991 GST_BUFFER_SIZE (atom_array_index (&pad->fragment_buffers, i));
1994 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
1995 atom_array_get_len (&pad->fragment_buffers), total_size);
1996 if (ret == GST_FLOW_OK)
1997 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
1999 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2000 if (G_LIKELY (ret == GST_FLOW_OK))
2001 ret = gst_qt_mux_send_buffer (qtmux,
2002 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2005 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2008 atom_array_clear (&pad->fragment_buffers);
2009 atom_moof_free (moof);
2010 qtmux->fragment_sequence++;
2015 if (G_UNLIKELY (!pad->traf)) {
2016 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2017 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2018 atom_array_init (&pad->fragment_buffers, 512);
2019 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2020 atom_trak_get_timescale (pad->trak), 1000);
2022 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2023 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2024 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2028 /* add buffer and metadata */
2029 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2031 atom_array_append (&pad->fragment_buffers, buf, 256);
2032 pad->fragment_duration -= delta;
2035 guint32 sn = atom_traf_get_sample_num (pad->traf);
2037 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2038 atom_tfra_add_entry (pad->tfra, dts, sn);
2041 if (G_UNLIKELY (force))
2047 /* sigh, tiny list helpers to re-order stuff */
2049 gst_qt_mux_push_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2053 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2054 if (ts > pad->ts_entries[i])
2057 memmove (&pad->ts_entries[i + 1], &pad->ts_entries[i],
2058 sizeof (GstClockTime) * (pad->ts_n_entries - i));
2059 pad->ts_entries[i] = ts;
2060 pad->ts_n_entries++;
2064 check_and_subtract_ts (GstQTMux * qtmux, GstClockTime * ts_a, GstClockTime ts_b)
2066 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (*ts_a))) {
2067 if (G_LIKELY (*ts_a > ts_b)) {
2071 GST_WARNING_OBJECT (qtmux, "Subtraction would result in negative value, "
2072 "using 0 as result");
2077 /* subtract ts from all buffers enqueued on the pad */
2079 gst_qt_mux_subtract_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2083 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2084 check_and_subtract_ts (qtmux, &pad->ts_entries[i], ts);
2086 for (i = 0; i < G_N_ELEMENTS (pad->buf_entries); i++) {
2087 if (pad->buf_entries[i]) {
2088 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (pad->buf_entries[i]),
2090 check_and_subtract_ts (qtmux,
2091 &GST_BUFFER_OFFSET_END (pad->buf_entries[i]), ts);
2096 /* takes ownership of @buf */
2098 gst_qt_mux_get_asc_buffer_ts (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2100 const gint wrap = G_N_ELEMENTS (pad->buf_entries);
2103 /* store buffer and ts, latter ordered */
2105 pad->buf_entries[pad->buf_tail++] = buf;
2106 pad->buf_tail %= wrap;
2107 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (buf));
2110 if (pad->ts_n_entries && (!buf || pad->ts_n_entries >= QTMUX_NO_OF_TS)) {
2111 ts = pad->ts_entries[--pad->ts_n_entries];
2112 buf = pad->buf_entries[pad->buf_head];
2113 pad->buf_entries[pad->buf_head++] = NULL;
2114 pad->buf_head %= wrap;
2115 buf = gst_buffer_make_metadata_writable (buf);
2116 /* track original ts (= pts ?) for later */
2117 GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_TIMESTAMP (buf);
2118 GST_BUFFER_TIMESTAMP (buf) = ts;
2119 GST_DEBUG_OBJECT (qtmux, "next buffer uses reordered ts %" GST_TIME_FORMAT,
2120 GST_TIME_ARGS (ts));
2129 * Here we push the buffer and update the tables in the track atoms
2131 static GstFlowReturn
2132 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2134 GstBuffer *last_buf = NULL;
2135 GstClockTime duration;
2136 guint nsamples, sample_size;
2137 guint64 chunk_offset;
2138 gint64 last_dts, scaled_duration;
2139 gint64 pts_offset = 0;
2140 gboolean sync = FALSE, do_pts = FALSE;
2141 gboolean drain = (buf == NULL);
2142 GstFlowReturn ret = GST_FLOW_OK;
2145 goto not_negotiated;
2147 /* if this pad has a prepare function, call it */
2148 if (pad->prepare_buf_func != NULL) {
2149 buf = pad->prepare_buf_func (pad, buf, qtmux);
2152 if (G_LIKELY (buf != NULL && GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
2153 pad->first_ts != 0)) {
2154 buf = gst_buffer_make_metadata_writable (buf);
2155 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2157 /* when we obtain the first_ts we subtract from all stored buffers we have,
2158 * after that we can subtract on input */
2161 last_buf = pad->last_buf;
2162 if (qtmux->dts_method == DTS_METHOD_REORDER) {
2163 buf = gst_qt_mux_get_asc_buffer_ts (qtmux, pad, buf);
2164 if (!buf && !last_buf) {
2165 GST_DEBUG_OBJECT (qtmux, "no reordered buffer");
2170 if (last_buf == NULL) {
2171 #ifndef GST_DISABLE_GST_DEBUG
2173 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
2174 "received NULL buffer, doing nothing",
2175 GST_PAD_NAME (pad->collect.pad));
2177 GST_LOG_OBJECT (qtmux,
2178 "Pad %s has no previous buffer stored, storing now",
2179 GST_PAD_NAME (pad->collect.pad));
2182 pad->last_buf = buf;
2185 gst_buffer_ref (last_buf);
2187 /* nasty heuristic mess to guestimate dealing with DTS/PTS,
2188 * while also trying to stay close to input ts to preserve sync,
2189 * so in DTS_METHOD_DD:
2190 * - prefer using input ts where possible
2191 * - if those detected out-of-order (*), mark as out-of-order
2192 * - if in out-of-order, then
2193 * - if duration available, use that as delta
2194 * Also mind to preserve sync between streams, and adding
2195 * durations might drift, so try to resync when we expect
2196 * input ts == (sum of durations), which is at some keyframe input frame.
2197 * - if no duration available, we are actually in serious trouble and need
2198 * to hack around that, so we fail.
2199 * To remedy failure, alternatively, in DTS_METHOD_REORDER:
2200 * - collect some buffers and re-order timestamp,
2201 * then process the oldest buffer with smallest timestamps.
2202 * This should typically compensate for some codec's handywork with ts.
2203 * ... but in case this makes ts end up where not expected, in DTS_METHOD_ASC:
2204 * - keep each ts with its buffer and still keep a list of most recent X ts,
2205 * use the (ascending) minimum of those as DTS (and the difference as ts delta),
2206 * and use this DTS as a basis to obtain a (positive) CTS offset.
2207 * This should yield exact PTS == buffer ts, but it seems not all players
2208 * out there are aware of ctts pts ...
2210 * 0.11 Phew, can we (pretty) please please sort out DTS/PTS on buffers ...
2212 if (G_LIKELY (buf) && !pad->is_out_of_order) {
2213 if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (last_buf) &&
2214 GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
2215 if ((GST_BUFFER_TIMESTAMP (buf) < GST_BUFFER_TIMESTAMP (last_buf))) {
2216 GST_DEBUG_OBJECT (qtmux, "detected out-of-order input");
2217 pad->is_out_of_order = TRUE;
2220 /* this is pretty bad */
2221 GST_WARNING_OBJECT (qtmux, "missing input timestamp");
2222 /* fall back to durations */
2223 pad->is_out_of_order = TRUE;
2227 /* would have to be some unusual input, but not impossible */
2228 if (G_UNLIKELY (qtmux->dts_method == DTS_METHOD_REORDER &&
2229 pad->is_out_of_order)) {
2233 /* if this is the first buffer, store the timestamp */
2234 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2235 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (last_buf))) {
2236 pad->first_ts = GST_BUFFER_TIMESTAMP (last_buf);
2238 GST_DEBUG_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2239 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2242 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2243 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2244 GST_TIME_ARGS (pad->first_ts));
2246 gst_qt_mux_subtract_ts (qtmux, pad, pad->first_ts);
2248 GST_BUFFER_TIMESTAMP (last_buf) = 0;
2249 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (last_buf),
2252 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2253 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (buf),
2258 /* fall back to duration if last buffer or
2259 * out-of-order (determined previously), otherwise use input ts */
2261 (pad->is_out_of_order && qtmux->dts_method == DTS_METHOD_DD)) {
2262 if (!GST_BUFFER_DURATION_IS_VALID (last_buf)) {
2263 /* be forgiving for some possibly last upstream flushed buffer */
2266 GST_WARNING_OBJECT (qtmux, "no duration for last buffer");
2267 /* iso spec recommends some small value, try 0 */
2270 duration = GST_BUFFER_DURATION (last_buf);
2271 /* avoid drift in sum timestamps,
2272 * so use input timestamp for suitable keyframe */
2273 if (buf && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) &&
2274 GST_BUFFER_TIMESTAMP (buf) >= pad->last_dts) {
2275 GST_DEBUG_OBJECT (qtmux, "resyncing out-of-order input to ts; "
2276 "replacing %" GST_TIME_FORMAT " by %" GST_TIME_FORMAT,
2277 GST_TIME_ARGS (pad->last_dts + duration),
2278 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2279 duration = GST_BUFFER_TIMESTAMP (buf) - pad->last_dts;
2282 } else if (qtmux->dts_method != DTS_METHOD_ASC) {
2283 duration = GST_BUFFER_TIMESTAMP (buf) - GST_BUFFER_TIMESTAMP (last_buf);
2287 g_assert (qtmux->dts_method == DTS_METHOD_ASC);
2288 if (!qtmux->guess_pts)
2291 /* add timestamp to queue; keeps in descending order */
2292 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (last_buf));
2293 /* chuck out smallest/last one if we have enough */
2294 if (G_LIKELY (pad->ts_n_entries > QTMUX_NO_OF_TS))
2295 pad->ts_n_entries--;
2296 /* peek the now smallest timestamp */
2297 ts = pad->ts_entries[pad->ts_n_entries - 1];
2298 /* these tails are expected to be (strictly) ascending with
2299 * large enough history */
2300 GST_DEBUG_OBJECT (qtmux, "ASC method; base timestamp %" GST_TIME_FORMAT,
2301 GST_TIME_ARGS (ts));
2302 if (ts >= pad->last_dts) {
2303 duration = ts - pad->last_dts;
2305 /* fallback to previous value, negative ct offset might handle */
2306 GST_WARNING_OBJECT (qtmux, "unexpected decrease in timestamp");
2309 /* arrange for small non-zero duration/delta << expected frame time */
2310 ts = gst_util_uint64_scale (10, GST_SECOND,
2311 atom_trak_get_timescale (pad->trak));
2312 duration = MAX (duration, ts);
2315 /* for computing the avg bitrate */
2316 if (G_LIKELY (last_buf)) {
2317 pad->total_bytes += GST_BUFFER_SIZE (last_buf);
2318 pad->total_duration += duration;
2321 gst_buffer_replace (&pad->last_buf, buf);
2323 last_dts = gst_util_uint64_scale_round (pad->last_dts,
2324 atom_trak_get_timescale (pad->trak), GST_SECOND);
2326 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2327 if (pad->sample_size && !qtmux->fragment_sequence) {
2328 /* Constant size packets: usually raw audio (with many samples per
2329 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2331 sample_size = pad->sample_size;
2332 if (GST_BUFFER_SIZE (last_buf) % sample_size != 0)
2333 goto fragmented_sample;
2334 /* note: qt raw audio storage warps it implicitly into a timewise
2335 * perfect stream, discarding buffer times */
2336 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2337 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2338 atom_trak_get_timescale (pad->trak), GST_SECOND);
2340 nsamples = GST_BUFFER_SIZE (last_buf) / sample_size;
2342 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2344 /* timescale = samplerate */
2345 scaled_duration = 1;
2346 pad->last_dts += duration * nsamples;
2349 sample_size = GST_BUFFER_SIZE (last_buf);
2350 if (pad->have_dts) {
2352 pad->last_dts = GST_BUFFER_OFFSET_END (last_buf);
2353 if ((gint64) (pad->last_dts) < 0) {
2354 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2355 atom_trak_get_timescale (pad->trak), GST_SECOND);
2357 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2358 atom_trak_get_timescale (pad->trak), GST_SECOND);
2360 scaled_duration = scaled_dts - last_dts;
2361 last_dts = scaled_dts;
2363 /* first convert intended timestamp (in GstClockTime resolution) to
2364 * trak timescale, then derive delta;
2365 * this ensures sums of (scale)delta add up to converted timestamp,
2366 * which only deviates at most 1/scale from timestamp itself */
2367 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2368 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2369 pad->last_dts += duration;
2372 chunk_offset = qtmux->mdat_size;
2374 GST_LOG_OBJECT (qtmux,
2375 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2376 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2377 GST_LOG_OBJECT (qtmux,
2378 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2379 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2380 nsamples, scaled_duration, sample_size, chunk_offset);
2382 /* might be a sync sample */
2384 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2385 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2386 GST_PAD_NAME (pad->collect.pad));
2390 /* optionally calculate ctts entry values
2391 * (if composition-time expected different from decoding-time) */
2392 /* really not recommended:
2393 * - decoder typically takes care of dts/pts issues
2394 * - in case of out-of-order, dts may only be determined as above
2395 * (e.g. sum of duration), which may be totally different from
2396 * buffer timestamps in case of multiple segment, non-perfect streams
2397 * (and just perhaps maybe with some luck segment_to_running_time
2398 * or segment_to_media_time might get near to it) */
2399 if ((pad->have_dts || qtmux->guess_pts)) {
2402 pts = qtmux->dts_method == DTS_METHOD_REORDER ?
2403 GST_BUFFER_OFFSET_END (last_buf) : GST_BUFFER_TIMESTAMP (last_buf);
2404 pts = gst_util_uint64_scale_round (pts,
2405 atom_trak_get_timescale (pad->trak), GST_SECOND);
2406 pts_offset = (gint64) (pts - last_dts);
2408 GST_LOG_OBJECT (qtmux, "Adding ctts entry for pad %s: %" G_GINT64_FORMAT,
2409 GST_PAD_NAME (pad->collect.pad), pts_offset);
2413 * Each buffer starts a new chunk, so we can assume the buffer
2414 * duration is the chunk duration
2416 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2417 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2418 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2419 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2420 qtmux->longest_chunk = duration;
2423 /* now we go and register this buffer/sample all over */
2424 /* note that a new chunk is started each time (not fancy but works) */
2425 if (qtmux->moov_recov_file) {
2426 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2427 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2428 do_pts, pts_offset)) {
2429 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2430 "recovery file, disabling recovery");
2431 fclose (qtmux->moov_recov_file);
2432 qtmux->moov_recov_file = NULL;
2437 gst_buffer_unref (buf);
2439 if (qtmux->fragment_sequence) {
2440 /* ensure that always sync samples are marked as such */
2441 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2442 buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2443 !pad->sync || sync, pts_offset);
2445 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2446 sample_size, chunk_offset, sync, pts_offset);
2447 ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2451 if (G_UNLIKELY (drain && qtmux->dts_method == DTS_METHOD_REORDER &&
2452 ret == GST_FLOW_OK)) {
2463 gst_buffer_unref (buf);
2464 gst_buffer_unref (last_buf);
2465 return GST_FLOW_ERROR;
2469 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2470 ("Received buffer without timestamp/duration. "
2471 "Using e.g. dts-method=reorder might help."));
2476 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2477 ("DTS method failed to re-order timestamps."));
2482 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2483 ("Selected DTS method also needs PTS enabled."));
2488 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2489 ("Audio buffer contains fragmented sample."));
2494 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2495 ("format wasn't negotiated before buffer flow on pad %s",
2496 GST_PAD_NAME (pad->collect.pad)));
2498 gst_buffer_unref (buf);
2499 return GST_FLOW_NOT_NEGOTIATED;
2503 static GstFlowReturn
2504 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
2506 GstFlowReturn ret = GST_FLOW_OK;
2507 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2509 GstQTPad *best_pad = NULL;
2510 GstClockTime time, best_time = GST_CLOCK_TIME_NONE;
2513 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2514 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2517 qtmux->state = GST_QT_MUX_STATE_DATA;
2520 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2521 return GST_FLOW_UNEXPECTED;
2523 /* select the best buffer */
2524 walk = qtmux->collect->data;
2527 GstCollectData *data;
2529 data = (GstCollectData *) walk->data;
2530 pad = (GstQTPad *) data;
2532 walk = g_slist_next (walk);
2534 buf = gst_collect_pads_peek (pads, data);
2536 GST_LOG_OBJECT (qtmux, "Pad %s has no buffers",
2537 GST_PAD_NAME (pad->collect.pad));
2540 time = GST_BUFFER_TIMESTAMP (buf);
2541 gst_buffer_unref (buf);
2543 /* invalid should pass */
2544 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (time))) {
2546 gst_segment_to_running_time (&data->segment, GST_FORMAT_TIME, time);
2547 if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time))) {
2548 GST_DEBUG_OBJECT (qtmux, "clipping buffer on pad %s outside segment",
2549 GST_PAD_NAME (data->pad));
2550 buf = gst_collect_pads_pop (pads, data);
2551 gst_buffer_unref (buf);
2556 if (best_pad == NULL || !GST_CLOCK_TIME_IS_VALID (time) ||
2557 (GST_CLOCK_TIME_IS_VALID (best_time) && time < best_time)) {
2563 if (best_pad != NULL) {
2564 GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2565 GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2566 buf = gst_collect_pads_pop (pads, &best_pad->collect);
2567 buf = gst_buffer_make_metadata_writable (buf);
2568 GST_BUFFER_TIMESTAMP (buf) = best_time;
2569 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2571 ret = gst_qt_mux_stop_file (qtmux);
2572 if (ret == GST_FLOW_OK) {
2573 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2574 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2575 ret = GST_FLOW_UNEXPECTED;
2577 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2578 gst_flow_get_name (ret));
2580 qtmux->state = GST_QT_MUX_STATE_EOS;
2587 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2589 GstStructure *structure = (GstStructure *) user_data;
2590 const GValue *other = gst_structure_id_get_value (structure, field_id);
2593 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2597 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2600 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2601 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2603 return gst_structure_foreach (sub_s, check_field, sup_s);
2607 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2609 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2610 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2611 GstQTPad *qtpad = NULL;
2612 GstStructure *structure;
2613 const gchar *mimetype;
2614 gint rate, channels;
2615 const GValue *value = NULL;
2616 const GstBuffer *codec_data = NULL;
2617 GstQTMuxFormat format;
2618 AudioSampleEntry entry = { 0, };
2619 AtomInfo *ext_atom = NULL;
2620 gint constant_size = 0;
2621 const gchar *stream_format;
2622 GstCaps *current_caps = NULL;
2624 /* find stream data */
2625 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2628 qtpad->prepare_buf_func = NULL;
2630 /* does not go well to renegotiate stream mid-way, unless
2631 * the old caps are a subset of the new one (this means upstream
2632 * added more info to the caps, as both should be 'fixed' caps) */
2633 if (qtpad->fourcc) {
2634 g_object_get (pad, "caps", ¤t_caps, NULL);
2635 g_assert (caps != NULL);
2637 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2638 goto refuse_renegotiation;
2640 GST_DEBUG_OBJECT (qtmux,
2641 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2642 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
2645 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2646 GST_DEBUG_PAD_NAME (pad), caps);
2648 format = qtmux_klass->format;
2649 structure = gst_caps_get_structure (caps, 0);
2650 mimetype = gst_structure_get_name (structure);
2653 if (!gst_structure_get_int (structure, "channels", &channels) ||
2654 !gst_structure_get_int (structure, "rate", &rate)) {
2659 value = gst_structure_get_value (structure, "codec_data");
2661 codec_data = gst_value_get_buffer (value);
2663 qtpad->is_out_of_order = FALSE;
2664 qtpad->have_dts = FALSE;
2666 /* set common properties */
2667 entry.sample_rate = rate;
2668 entry.channels = channels;
2670 entry.sample_size = 16;
2671 /* this is the typical compressed case */
2672 if (format == GST_QT_MUX_FORMAT_QT) {
2674 entry.compression_id = -2;
2677 /* now map onto a fourcc, and some extra properties */
2678 if (strcmp (mimetype, "audio/mpeg") == 0) {
2679 gint mpegversion = 0;
2682 gst_structure_get_int (structure, "mpegversion", &mpegversion);
2683 switch (mpegversion) {
2685 gst_structure_get_int (structure, "layer", &layer);
2689 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2690 if (format == GST_QT_MUX_FORMAT_QT)
2691 entry.fourcc = FOURCC__mp3;
2693 entry.fourcc = FOURCC_mp4a;
2695 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2696 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2697 qtpad->max_bitrate);
2699 entry.samples_per_packet = 1152;
2700 entry.bytes_per_sample = 2;
2706 /* check stream-format */
2707 stream_format = gst_structure_get_string (structure, "stream-format");
2708 if (stream_format) {
2709 if (strcmp (stream_format, "raw") != 0) {
2710 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2711 "please use 'raw'", stream_format);
2715 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2719 if (!codec_data || GST_BUFFER_SIZE (codec_data) < 2)
2720 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2722 guint8 profile = GST_READ_UINT8 (GST_BUFFER_DATA (codec_data));
2724 /* warn if not Low Complexity profile */
2727 GST_WARNING_OBJECT (qtmux,
2728 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2732 entry.fourcc = FOURCC_mp4a;
2734 if (format == GST_QT_MUX_FORMAT_QT)
2735 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2736 qtpad->avg_bitrate, qtpad->max_bitrate);
2739 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2740 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2741 qtpad->max_bitrate);
2746 } else if (strcmp (mimetype, "audio/AMR") == 0) {
2747 entry.fourcc = FOURCC_samr;
2748 entry.sample_size = 16;
2749 entry.samples_per_packet = 160;
2750 entry.bytes_per_sample = 2;
2751 ext_atom = build_amr_extension ();
2752 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2753 entry.fourcc = FOURCC_sawb;
2754 entry.sample_size = 16;
2755 entry.samples_per_packet = 320;
2756 entry.bytes_per_sample = 2;
2757 ext_atom = build_amr_extension ();
2758 } else if (strcmp (mimetype, "audio/x-raw-int") == 0) {
2764 if (!gst_structure_get_int (structure, "width", &width) ||
2765 !gst_structure_get_int (structure, "depth", &depth) ||
2766 !gst_structure_get_boolean (structure, "signed", &sign)) {
2767 GST_DEBUG_OBJECT (qtmux, "broken caps, width/depth/signed field missing");
2772 endianness = G_BYTE_ORDER;
2773 } else if (!gst_structure_get_int (structure, "endianness", &endianness)) {
2774 GST_DEBUG_OBJECT (qtmux, "broken caps, endianness field missing");
2778 /* spec has no place for a distinction in these */
2779 if (width != depth) {
2780 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2785 if (endianness == G_LITTLE_ENDIAN)
2786 entry.fourcc = FOURCC_sowt;
2787 else if (endianness == G_BIG_ENDIAN)
2788 entry.fourcc = FOURCC_twos;
2789 /* maximum backward compatibility; only new version for > 16 bit */
2792 /* not compressed in any case */
2793 entry.compression_id = 0;
2794 /* QT spec says: max at 16 bit even if sample size were actually larger,
2795 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2796 entry.sample_size = depth;
2797 entry.bytes_per_sample = depth / 8;
2798 entry.samples_per_packet = 1;
2799 entry.bytes_per_packet = depth / 8;
2800 entry.bytes_per_frame = entry.bytes_per_packet * channels;
2802 if (width == 8 && depth == 8) {
2803 /* fall back to old 8-bit version */
2804 entry.fourcc = FOURCC_raw_;
2806 entry.compression_id = 0;
2807 entry.sample_size = 8;
2809 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2813 constant_size = (depth / 8) * channels;
2814 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2815 entry.fourcc = FOURCC_alaw;
2816 entry.samples_per_packet = 1023;
2817 entry.bytes_per_sample = 2;
2818 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2819 entry.fourcc = FOURCC_ulaw;
2820 entry.samples_per_packet = 1023;
2821 entry.bytes_per_sample = 2;
2822 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2824 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2825 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2828 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2830 entry.fourcc = MS_WAVE_FOURCC (0x11);
2831 /* 4 byte header per channel (including one sample). 2 samples per byte
2832 remaining. Simplifying gives the following (samples per block per
2834 entry.samples_per_packet = 2 * blocksize / channels - 7;
2835 entry.bytes_per_sample = 2;
2837 entry.bytes_per_frame = blocksize;
2838 entry.bytes_per_packet = blocksize / channels;
2839 /* ADPCM has constant size packets */
2841 /* TODO: I don't really understand why this helps, but it does! Constant
2842 * size and compression_id of -2 seem to be incompatible, and other files
2843 * in the wild use this too. */
2844 entry.compression_id = -1;
2846 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2847 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2848 GstBuffer *codec_config;
2851 entry.fourcc = FOURCC_alac;
2852 /* let's check if codec data already comes with 'alac' atom prefix */
2853 if (!codec_data || (len = GST_BUFFER_SIZE (codec_data)) < 28) {
2854 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2857 if (GST_READ_UINT32_LE (GST_BUFFER_DATA (codec_data) + 4) == FOURCC_alac) {
2859 codec_config = gst_buffer_create_sub ((GstBuffer *) codec_data, 8, len);
2861 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2864 /* does not look good, but perhaps some trailing unneeded stuff */
2865 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2867 if (format == GST_QT_MUX_FORMAT_QT)
2868 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2870 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2871 /* set some more info */
2872 entry.bytes_per_sample = 2;
2873 entry.samples_per_packet =
2874 GST_READ_UINT32_BE (GST_BUFFER_DATA (codec_config) + 4);
2875 gst_buffer_unref (codec_config);
2881 /* ok, set the pad info accordingly */
2882 qtpad->fourcc = entry.fourcc;
2883 qtpad->sample_size = constant_size;
2884 atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2885 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2886 ext_atom, constant_size);
2888 gst_object_unref (qtmux);
2894 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2895 GST_PAD_NAME (pad), caps);
2896 gst_object_unref (qtmux);
2899 refuse_renegotiation:
2901 GST_WARNING_OBJECT (qtmux,
2902 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2903 GST_PAD_NAME (pad), caps);
2904 gst_object_unref (qtmux);
2909 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2911 adjust_rate (guint64 rate)
2916 while (rate >= 10000)
2922 return (guint32) rate;
2926 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2928 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2929 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2930 GstQTPad *qtpad = NULL;
2931 GstStructure *structure;
2932 const gchar *mimetype;
2933 gint width, height, depth = -1;
2934 gint framerate_num, framerate_den;
2936 const GValue *value = NULL;
2937 const GstBuffer *codec_data = NULL;
2938 VisualSampleEntry entry = { 0, };
2939 GstQTMuxFormat format;
2940 AtomInfo *ext_atom = NULL;
2941 GList *ext_atom_list = NULL;
2942 gboolean sync = FALSE;
2943 int par_num, par_den;
2944 GstCaps *current_caps = NULL;
2946 /* find stream data */
2947 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2950 qtpad->prepare_buf_func = NULL;
2952 /* does not go well to renegotiate stream mid-way, unless
2953 * the old caps are a subset of the new one (this means upstream
2954 * added more info to the caps, as both should be 'fixed' caps) */
2955 if (qtpad->fourcc) {
2956 g_object_get (pad, "caps", ¤t_caps, NULL);
2957 g_assert (caps != NULL);
2959 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2960 goto refuse_renegotiation;
2962 GST_DEBUG_OBJECT (qtmux,
2963 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2964 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
2967 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2968 GST_DEBUG_PAD_NAME (pad), caps);
2970 format = qtmux_klass->format;
2971 structure = gst_caps_get_structure (caps, 0);
2972 mimetype = gst_structure_get_name (structure);
2974 /* required parts */
2975 if (!gst_structure_get_int (structure, "width", &width) ||
2976 !gst_structure_get_int (structure, "height", &height))
2981 /* works as a default timebase */
2982 framerate_num = 10000;
2984 gst_structure_get_fraction (structure, "framerate", &framerate_num,
2986 gst_structure_get_int (structure, "depth", &depth);
2987 value = gst_structure_get_value (structure, "codec_data");
2989 codec_data = gst_value_get_buffer (value);
2993 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
2996 qtpad->is_out_of_order = FALSE;
2998 /* bring frame numerator into a range that ensures both reasonable resolution
2999 * as well as a fair duration */
3000 rate = qtmux->trak_timescale ?
3001 qtmux->trak_timescale : adjust_rate (framerate_num);
3002 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
3005 /* set common properties */
3006 entry.width = width;
3007 entry.height = height;
3008 entry.par_n = par_num;
3009 entry.par_d = par_den;
3010 /* should be OK according to qt and iso spec, override if really needed */
3011 entry.color_table_id = -1;
3012 entry.frame_count = 1;
3015 /* sync entries by default */
3018 /* now map onto a fourcc, and some extra properties */
3019 if (strcmp (mimetype, "video/x-raw-rgb") == 0) {
3022 entry.fourcc = FOURCC_raw_;
3023 gst_structure_get_int (structure, "bpp", &bpp);
3026 } else if (strcmp (mimetype, "video/x-raw-yuv") == 0) {
3030 gst_structure_get_fourcc (structure, "format", &format);
3032 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
3035 entry.fourcc = FOURCC_2vuy;
3036 entry.depth = depth;
3039 } else if (strcmp (mimetype, "video/x-h263") == 0) {
3041 if (format == GST_QT_MUX_FORMAT_QT)
3042 entry.fourcc = FOURCC_h263;
3044 entry.fourcc = FOURCC_s263;
3045 ext_atom = build_h263_extension ();
3046 if (ext_atom != NULL)
3047 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3048 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
3049 strcmp (mimetype, "video/mpeg") == 0) {
3052 if (strcmp (mimetype, "video/x-divx") == 0) {
3053 gst_structure_get_int (structure, "divxversion", &version);
3054 version = version == 5 ? 1 : 0;
3056 gst_structure_get_int (structure, "mpegversion", &version);
3057 version = version == 4 ? 1 : 0;
3060 entry.fourcc = FOURCC_mp4v;
3062 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
3063 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
3064 qtpad->max_bitrate);
3065 if (ext_atom != NULL)
3066 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3068 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
3069 "output might not play in Apple QuickTime (try global-headers?)");
3071 } else if (strcmp (mimetype, "video/x-h264") == 0) {
3072 /* check if we accept these caps */
3073 if (gst_structure_has_field (structure, "stream-format")) {
3074 const gchar *format;
3075 const gchar *alignment;
3077 format = gst_structure_get_string (structure, "stream-format");
3078 alignment = gst_structure_get_string (structure, "alignment");
3080 if (strcmp (format, "avc") != 0 || alignment == NULL ||
3081 strcmp (alignment, "au") != 0) {
3082 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
3083 "avc format with AU aligned samples");
3087 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
3092 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
3096 entry.fourcc = FOURCC_avc1;
3097 if (qtpad->avg_bitrate == 0) {
3098 gint avg_bitrate = 0;
3099 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
3100 qtpad->avg_bitrate = avg_bitrate;
3102 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
3103 if (ext_atom != NULL)
3104 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3105 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
3106 if (ext_atom != NULL)
3107 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3108 } else if (strcmp (mimetype, "video/x-svq") == 0) {
3110 const GstBuffer *seqh = NULL;
3111 const GValue *seqh_value;
3114 gst_structure_get_int (structure, "svqversion", &version);
3116 entry.fourcc = FOURCC_SVQ3;
3120 seqh_value = gst_structure_get_value (structure, "seqh");
3122 seqh = gst_value_get_buffer (seqh_value);
3123 ext_atom = build_SMI_atom (seqh);
3125 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3128 /* we need to add the gamma anyway because quicktime might crash
3129 * when it doesn't find it */
3130 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
3131 /* it seems that using 0 here makes it ignored */
3134 ext_atom = build_gama_atom (gamma);
3136 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3138 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
3139 "a bug at http://bugzilla.gnome.org", version);
3141 } else if (strcmp (mimetype, "video/x-dv") == 0) {
3143 gboolean pal = TRUE;
3146 if (framerate_num != 25 || framerate_den != 1)
3148 gst_structure_get_int (structure, "dvversion", &version);
3149 /* fall back to typical one */
3155 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
3157 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
3161 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
3163 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
3166 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
3169 } else if (strcmp (mimetype, "image/jpeg") == 0) {
3170 entry.fourcc = FOURCC_jpeg;
3172 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
3173 strcmp (mimetype, "image/x-jpc") == 0) {
3175 const GValue *cmap_array;
3176 const GValue *cdef_array;
3180 if (strcmp (mimetype, "image/x-jpc") == 0) {
3181 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
3184 gst_structure_get_int (structure, "num-components", &ncomp);
3185 gst_structure_get_int (structure, "fields", &fields);
3186 cmap_array = gst_structure_get_value (structure, "component-map");
3187 cdef_array = gst_structure_get_value (structure, "channel-definitions");
3190 entry.fourcc = FOURCC_mjp2;
3192 if (gst_structure_get_fourcc (structure, "fourcc", &fourcc) &&
3194 build_jp2h_extension (qtpad->trak, width, height, fourcc, ncomp,
3195 cmap_array, cdef_array)) != NULL) {
3196 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3198 ext_atom = build_fiel_extension (fields);
3200 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3202 ext_atom = build_jp2x_extension (codec_data);
3204 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3206 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3209 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3210 entry.fourcc = FOURCC_VP80;
3212 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3213 entry.fourcc = FOURCC_drac;
3214 qtpad->have_dts = TRUE;
3215 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3218 gst_structure_get_fourcc (structure, "format", &fourcc);
3219 entry.fourcc = fourcc;
3220 qtpad->have_dts = TRUE;
3221 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3224 gst_structure_get_fourcc (structure, "format", &fourcc);
3225 entry.fourcc = fourcc;
3226 qtpad->have_dts = TRUE;
3232 /* ok, set the pad info accordingly */
3233 qtpad->fourcc = entry.fourcc;
3235 atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3238 gst_object_unref (qtmux);
3244 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3245 GST_PAD_NAME (pad), caps);
3246 gst_object_unref (qtmux);
3249 refuse_renegotiation:
3251 GST_WARNING_OBJECT (qtmux,
3252 "pad %s refused renegotiation to %" GST_PTR_FORMAT " from %"
3253 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
3254 gst_object_unref (qtmux);
3260 gst_qt_mux_sink_event (GstPad * pad, GstEvent * event)
3264 guint32 avg_bitrate = 0, max_bitrate = 0;
3266 qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3267 switch (GST_EVENT_TYPE (event)) {
3268 case GST_EVENT_TAG:{
3270 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3271 GstTagMergeMode mode;
3273 GST_OBJECT_LOCK (qtmux);
3274 mode = gst_tag_setter_get_tag_merge_mode (setter);
3276 GST_DEBUG_OBJECT (qtmux, "received tag event");
3277 gst_event_parse_tag (event, &list);
3279 gst_tag_setter_merge_tags (setter, list, mode);
3280 GST_OBJECT_UNLOCK (qtmux);
3282 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3283 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3284 GstQTPad *qtpad = gst_pad_get_element_private (pad);
3287 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3288 qtpad->avg_bitrate = avg_bitrate;
3289 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3290 qtpad->max_bitrate = max_bitrate;
3299 ret = qtmux->collect_event (pad, event);
3300 gst_object_unref (qtmux);
3306 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3308 GstQTMux *mux = GST_QT_MUX_CAST (element);
3311 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3313 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3314 GstQTPad *qtpad = (GstQTPad *) walk->data;
3315 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3316 if (qtpad->collect.pad == pad) {
3317 /* this is it, remove */
3318 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3319 gst_element_remove_pad (element, pad);
3324 gst_collect_pads_remove_pad (mux->collect, pad);
3328 gst_qt_mux_request_new_pad (GstElement * element,
3329 GstPadTemplate * templ, const gchar * req_name)
3331 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3332 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3333 GstQTPad *collect_pad;
3338 if (templ->direction != GST_PAD_SINK)
3339 goto wrong_direction;
3341 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3344 if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
3346 name = g_strdup_printf ("audio_%02d", qtmux->audio_pads++);
3347 } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
3349 name = g_strdup_printf ("video_%02d", qtmux->video_pads++);
3351 goto wrong_template;
3353 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3355 /* create pad and add to collections */
3356 newpad = gst_pad_new_from_template (templ, name);
3358 collect_pad = (GstQTPad *)
3359 gst_collect_pads_add_pad_full (qtmux->collect, newpad, sizeof (GstQTPad),
3360 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset));
3362 gst_qt_mux_pad_reset (collect_pad);
3363 collect_pad->trak = atom_trak_new (qtmux->context);
3364 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3366 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3368 /* set up pad functions */
3370 gst_pad_set_setcaps_function (newpad,
3371 GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps));
3373 gst_pad_set_setcaps_function (newpad,
3374 GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps));
3376 /* FIXME: hacked way to override/extend the event function of
3377 * GstCollectPads; because it sets its own event function giving the
3378 * element no access to events.
3380 qtmux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
3381 gst_pad_set_event_function (newpad,
3382 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event));
3384 gst_pad_set_active (newpad, TRUE);
3385 gst_element_add_pad (element, newpad);
3392 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3397 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3402 GST_WARNING_OBJECT (qtmux, "This is not our template!");
3408 gst_qt_mux_get_property (GObject * object,
3409 guint prop_id, GValue * value, GParamSpec * pspec)
3411 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3413 GST_OBJECT_LOCK (qtmux);
3415 case PROP_MOVIE_TIMESCALE:
3416 g_value_set_uint (value, qtmux->timescale);
3418 case PROP_TRAK_TIMESCALE:
3419 g_value_set_uint (value, qtmux->trak_timescale);
3422 g_value_set_boolean (value, qtmux->guess_pts);
3424 case PROP_DTS_METHOD:
3425 g_value_set_enum (value, qtmux->dts_method);
3427 case PROP_FAST_START:
3428 g_value_set_boolean (value, qtmux->fast_start);
3430 case PROP_FAST_START_TEMP_FILE:
3431 g_value_set_string (value, qtmux->fast_start_file_path);
3433 case PROP_MOOV_RECOV_FILE:
3434 g_value_set_string (value, qtmux->moov_recov_file_path);
3436 case PROP_FRAGMENT_DURATION:
3437 g_value_set_uint (value, qtmux->fragment_duration);
3439 case PROP_STREAMABLE:
3440 g_value_set_boolean (value, qtmux->streamable);
3443 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3446 GST_OBJECT_UNLOCK (qtmux);
3450 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3454 g_free (qtmux->fast_start_file_path);
3455 qtmux->fast_start_file_path = NULL;
3457 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3458 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3463 gst_qt_mux_set_property (GObject * object,
3464 guint prop_id, const GValue * value, GParamSpec * pspec)
3466 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3468 GST_OBJECT_LOCK (qtmux);
3470 case PROP_MOVIE_TIMESCALE:
3471 qtmux->timescale = g_value_get_uint (value);
3473 case PROP_TRAK_TIMESCALE:
3474 qtmux->trak_timescale = g_value_get_uint (value);
3477 qtmux->guess_pts = g_value_get_boolean (value);
3479 case PROP_DTS_METHOD:
3480 qtmux->dts_method = g_value_get_enum (value);
3482 case PROP_FAST_START:
3483 qtmux->fast_start = g_value_get_boolean (value);
3485 case PROP_FAST_START_TEMP_FILE:
3486 g_free (qtmux->fast_start_file_path);
3487 qtmux->fast_start_file_path = g_value_dup_string (value);
3488 /* NULL means to generate a random one */
3489 if (!qtmux->fast_start_file_path) {
3490 gst_qt_mux_generate_fast_start_file_path (qtmux);
3493 case PROP_MOOV_RECOV_FILE:
3494 g_free (qtmux->moov_recov_file_path);
3495 qtmux->moov_recov_file_path = g_value_dup_string (value);
3497 case PROP_FRAGMENT_DURATION:
3498 qtmux->fragment_duration = g_value_get_uint (value);
3500 case PROP_STREAMABLE:
3501 qtmux->streamable = g_value_get_boolean (value);
3504 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3507 GST_OBJECT_UNLOCK (qtmux);
3510 static GstStateChangeReturn
3511 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3513 GstStateChangeReturn ret;
3514 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3516 switch (transition) {
3517 case GST_STATE_CHANGE_NULL_TO_READY:
3519 case GST_STATE_CHANGE_READY_TO_PAUSED:
3520 gst_collect_pads_start (qtmux->collect);
3521 qtmux->state = GST_QT_MUX_STATE_STARTED;
3523 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3525 case GST_STATE_CHANGE_PAUSED_TO_READY:
3526 gst_collect_pads_stop (qtmux->collect);
3532 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3534 switch (transition) {
3535 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3537 case GST_STATE_CHANGE_PAUSED_TO_READY:
3538 gst_qt_mux_reset (qtmux, TRUE);
3540 case GST_STATE_CHANGE_READY_TO_NULL:
3550 gst_qt_mux_register (GstPlugin * plugin)
3552 GTypeInfo typeinfo = {
3553 sizeof (GstQTMuxClass),
3554 (GBaseInitFunc) gst_qt_mux_base_init,
3556 (GClassInitFunc) gst_qt_mux_class_init,
3561 (GInstanceInitFunc) gst_qt_mux_init,
3563 static const GInterfaceInfo tag_setter_info = {
3566 static const GInterfaceInfo tag_xmp_writer_info = {
3570 GstQTMuxFormat format;
3571 GstQTMuxClassParams *params;
3574 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3576 GST_LOG ("Registering muxers");
3579 GstQTMuxFormatProp *prop;
3581 prop = &gst_qt_mux_format_list[i];
3582 format = prop->format;
3583 if (format == GST_QT_MUX_FORMAT_NONE)
3586 /* create a cache for these properties */
3587 params = g_new0 (GstQTMuxClassParams, 1);
3588 params->prop = prop;
3589 params->src_caps = gst_static_caps_get (&prop->src_caps);
3590 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3591 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3593 /* create the type now */
3594 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3596 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3597 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3598 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3599 &tag_xmp_writer_info);
3601 if (!gst_element_register (plugin, prop->name, prop->rank, type))
3607 GST_LOG ("Finished registering muxers");
3609 /* FIXME: ideally classification tag should be added and
3610 registered in gstreamer core gsttaglist
3613 GST_LOG ("Registering tags");
3615 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3616 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3617 gst_tag_merge_use_first);
3619 GST_LOG ("Finished registering tags");