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,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/gstcollectpads2.h>
120 #include <gst/audio/audio.h>
121 #include <gst/video/video.h>
122 #include <gst/tag/xmpwriter.h>
124 #include <sys/types.h>
126 #include <io.h> /* lseek, open, close, read */
128 #define lseek _lseeki64
130 #define off_t guint64
134 #define ftruncate g_win32_ftruncate
141 #include "gstqtmux.h"
143 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
144 #define GST_CAT_DEFAULT gst_qt_mux_debug
154 gst_qt_mux_dts_method_get_type (void)
156 static GType gst_qt_mux_dts_method = 0;
158 if (!gst_qt_mux_dts_method) {
159 static const GEnumValue dts_methods[] = {
160 {DTS_METHOD_DD, "delta/duration", "dd"},
161 {DTS_METHOD_REORDER, "reorder", "reorder"},
162 {DTS_METHOD_ASC, "ascending", "asc"},
166 gst_qt_mux_dts_method =
167 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
170 return gst_qt_mux_dts_method;
173 #define GST_TYPE_QT_MUX_DTS_METHOD \
174 (gst_qt_mux_dts_method_get_type ())
176 /* QTMux signals and args */
186 PROP_MOVIE_TIMESCALE,
189 PROP_FAST_START_TEMP_FILE,
190 PROP_MOOV_RECOV_FILE,
191 PROP_FRAGMENT_DURATION,
197 /* some spare for header size as well */
198 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
199 #define MAX_TOLERATED_LATENESS (GST_SECOND / 10)
201 #define DEFAULT_MOVIE_TIMESCALE 1000
202 #define DEFAULT_TRAK_TIMESCALE 0
203 #define DEFAULT_DO_CTTS TRUE
204 #define DEFAULT_FAST_START FALSE
205 #define DEFAULT_FAST_START_TEMP_FILE NULL
206 #define DEFAULT_MOOV_RECOV_FILE NULL
207 #define DEFAULT_FRAGMENT_DURATION 0
208 #define DEFAULT_STREAMABLE FALSE
209 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
212 static void gst_qt_mux_finalize (GObject * object);
214 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
215 GstStateChange transition);
217 /* property functions */
218 static void gst_qt_mux_set_property (GObject * object,
219 guint prop_id, const GValue * value, GParamSpec * pspec);
220 static void gst_qt_mux_get_property (GObject * object,
221 guint prop_id, GValue * value, GParamSpec * pspec);
224 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
225 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
226 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
229 static gboolean gst_qt_mux_sink_event (GstCollectPads2 * pads,
230 GstCollectData2 * data, GstEvent * event, gpointer user_data);
232 static GstFlowReturn gst_qt_mux_handle_buffer (GstCollectPads2 * pads,
233 GstCollectData2 * cdata, GstBuffer * buf, gpointer user_data);
234 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
237 static GstElementClass *parent_class = NULL;
240 gst_qt_mux_base_init (gpointer g_class)
242 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
243 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
244 GstQTMuxClassParams *params;
245 GstPadTemplate *videosinktempl, *audiosinktempl, *srctempl;
246 gchar *longname, *description;
249 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
250 GST_QT_MUX_PARAMS_QDATA);
251 g_assert (params != NULL);
253 /* construct the element details struct */
254 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
255 description = g_strdup_printf ("Multiplex audio and video into a %s file%s",
256 params->prop->long_name,
257 (params->prop->rank == GST_RANK_NONE) ? " (deprecated)" : "");
258 gst_element_class_set_static_metadata (element_class, longname,
259 "Codec/Muxer", description,
260 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
262 g_free (description);
265 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
266 GST_PAD_ALWAYS, params->src_caps);
267 gst_element_class_add_pad_template (element_class, srctempl);
269 if (params->audio_sink_caps) {
270 audiosinktempl = gst_pad_template_new ("audio_%u",
271 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
272 gst_element_class_add_pad_template (element_class, audiosinktempl);
275 if (params->video_sink_caps) {
276 videosinktempl = gst_pad_template_new ("video_%u",
277 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
278 gst_element_class_add_pad_template (element_class, videosinktempl);
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_pads2_new ();
486 gst_collect_pads2_set_buffer_function (qtmux->collect,
487 GST_DEBUG_FUNCPTR (gst_qt_mux_handle_buffer), qtmux);
488 gst_collect_pads2_set_event_function (qtmux->collect,
489 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
490 gst_collect_pads2_set_clip_function (qtmux->collect,
491 GST_DEBUG_FUNCPTR (gst_collect_pads2_clip_running_time), qtmux);
493 /* properties set to default upon construction */
495 /* always need this */
497 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
499 /* internals to initial state */
500 gst_qt_mux_reset (qtmux, TRUE);
505 gst_qt_mux_finalize (GObject * object)
507 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
509 gst_qt_mux_reset (qtmux, FALSE);
511 g_free (qtmux->fast_start_file_path);
512 g_free (qtmux->moov_recov_file_path);
514 atoms_context_free (qtmux->context);
515 gst_object_unref (qtmux->collect);
517 g_slist_free (qtmux->sinkpads);
519 G_OBJECT_CLASS (parent_class)->finalize (object);
523 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
530 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
535 size = gst_buffer_get_size (buf);
536 newbuf = gst_buffer_new_and_alloc (size + 8);
537 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
539 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
540 GST_WRITE_UINT32_BE (map.data, map.size);
541 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
543 gst_buffer_unmap (buf, &map);
544 gst_buffer_unref (buf);
550 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
551 const char *tag, const char *tag2, guint32 fourcc)
553 switch (gst_tag_get_type (tag)) {
559 if (!gst_tag_list_get_string (list, tag, &str) || !str)
561 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
562 GST_FOURCC_ARGS (fourcc), str);
563 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
572 if (!gst_tag_list_get_double (list, tag, &value))
574 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
575 GST_FOURCC_ARGS (fourcc), (gint) value);
576 atom_moov_add_uint_tag (qtmux->moov, fourcc, 21, (gint) value);
583 /* paired unsigned integers */
587 got_tag = gst_tag_list_get_uint (list, tag, &value);
588 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
591 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
592 GST_FOURCC_ARGS (fourcc), value, count);
593 atom_moov_add_uint_tag (qtmux->moov, fourcc, 0,
594 value << 16 | (count & 0xFFFF));
596 /* unpaired unsigned integers */
597 if (!gst_tag_list_get_uint (list, tag, &value))
599 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
600 GST_FOURCC_ARGS (fourcc), value);
601 atom_moov_add_uint_tag (qtmux->moov, fourcc, 1, value);
606 g_assert_not_reached ();
612 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
613 const char *tag, const char *tag2, guint32 fourcc)
621 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
623 if (!gst_tag_list_get_date (list, tag, &date) || !date)
626 year = g_date_get_year (date);
627 month = g_date_get_month (date);
628 day = g_date_get_day (date);
632 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
633 day == G_DATE_BAD_DAY) {
634 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
638 str = g_strdup_printf ("%u-%u-%u", year, month, day);
639 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
640 GST_FOURCC_ARGS (fourcc), str);
641 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
646 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
647 const char *tag, const char *tag2, guint32 fourcc)
649 GValue value = { 0, };
653 GstStructure *structure;
657 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
659 if (!gst_tag_list_copy_value (&value, list, tag))
662 sample = gst_value_get_sample (&value);
667 buf = gst_sample_get_buffer (sample);
671 caps = gst_sample_get_caps (sample);
673 GST_WARNING_OBJECT (qtmux, "preview image without caps");
677 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
679 structure = gst_caps_get_structure (caps, 0);
680 if (gst_structure_has_name (structure, "image/jpeg"))
682 else if (gst_structure_has_name (structure, "image/png"))
686 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
690 gst_buffer_map (buf, &map, GST_MAP_READ);
691 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
692 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
693 atom_moov_add_tag (qtmux->moov, fourcc, flags, map.data, map.size);
694 gst_buffer_unmap (buf, &map);
696 g_value_unset (&value);
700 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
701 const char *tag, const char *tag2, guint32 fourcc)
706 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
707 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
709 if (!gst_tag_list_get_string (list, tag, &str) || !str)
713 if (!gst_tag_list_get_uint (list, tag2, &number))
717 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
718 GST_FOURCC_ARGS (fourcc), str);
719 atom_moov_add_3gp_str_tag (qtmux->moov, fourcc, str);
721 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
722 GST_FOURCC_ARGS (fourcc), str, number);
723 atom_moov_add_3gp_str_int_tag (qtmux->moov, fourcc, str, number);
730 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
731 const char *tag, const char *tag2, guint32 fourcc)
736 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
738 if (!gst_tag_list_get_date (list, tag, &date) || !date)
741 year = g_date_get_year (date);
743 if (year == G_DATE_BAD_YEAR) {
744 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
748 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
749 GST_FOURCC_ARGS (fourcc), year);
750 atom_moov_add_3gp_uint_tag (qtmux->moov, fourcc, year);
754 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
755 const char *tag, const char *tag2, guint32 fourcc)
757 gdouble latitude = -360, longitude = -360, altitude = 0;
758 gchar *location = NULL;
759 guint8 *data, *ddata;
760 gint size = 0, len = 0;
761 gboolean ret = FALSE;
763 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
765 ret = gst_tag_list_get_string (list, tag, &location);
766 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
768 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
770 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
777 len = strlen (location);
780 /* role + (long, lat, alt) + body + notes */
781 size += 1 + 3 * 4 + 1 + 1;
783 data = ddata = g_malloc (size);
786 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
789 memcpy (data + 2, location, len);
790 GST_WRITE_UINT8 (data + 2 + len, 0);
793 GST_WRITE_UINT8 (data, 0);
795 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
796 QT_WRITE_SFP32 (data + 1, longitude);
797 QT_WRITE_SFP32 (data + 5, latitude);
798 QT_WRITE_SFP32 (data + 9, altitude);
799 /* neither astronomical body nor notes */
800 GST_WRITE_UINT16_BE (data + 13, 0);
802 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
803 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
808 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
809 const char *tag, const char *tag2, guint32 fourcc)
811 gchar *keywords = NULL;
812 guint8 *data, *ddata;
816 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
818 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
821 kwds = g_strsplit (keywords, ",", 0);
825 for (i = 0; kwds[i]; i++) {
826 /* size byte + null-terminator */
827 size += strlen (kwds[i]) + 1 + 1;
830 /* language tag + count + keywords */
833 data = ddata = g_malloc (size);
836 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
838 GST_WRITE_UINT8 (data + 2, i);
841 for (i = 0; kwds[i]; ++i) {
842 gint len = strlen (kwds[i]);
844 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
845 GST_FOURCC_ARGS (fourcc), kwds[i]);
847 GST_WRITE_UINT8 (data, len + 1);
848 memcpy (data + 1, kwds[i], len + 1);
854 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
859 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
860 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
868 size = strlen (input);
870 if (size < 4 + 3 + 1 + 1 + 1) {
871 /* at least the minimum xxxx://y/z */
872 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
877 /* read the fourcc */
878 memcpy (&fourcc, data, 4);
882 if (strncmp (data, "://", 3) != 0) {
888 /* read the table number */
889 if (sscanf (data, "%d", &table) != 1) {
893 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
894 ", table numbers should be positive, ignoring tag", table);
898 /* find the next / */
899 while (size > 0 && data[0] != '/') {
906 g_assert (data[0] == '/');
915 /* read up the rest of the string */
916 *p_content = g_strdup (data);
917 *p_table = (guint16) table;
923 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
924 "input (%s) didn't match the expected entitycode://table/content",
931 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
932 const char *tag, const char *tag2, guint32 fourcc)
934 gchar *clsf_data = NULL;
938 gchar *content = NULL;
941 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
943 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
946 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
947 GST_FOURCC_ARGS (fourcc), clsf_data);
949 /* parse the string, format is:
950 * entityfourcc://table/content
952 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
956 size = strlen (content) + 1;
958 /* now we have everything, build the atom
959 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
960 data = g_malloc (4 + 2 + 2 + size);
961 GST_WRITE_UINT32_LE (data, entity);
962 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
963 GST_WRITE_UINT16_BE (data + 6, 0);
964 memcpy (data + 8, content, size);
967 atom_moov_add_3gp_tag (qtmux->moov, fourcc, data, 4 + 2 + 2 + size);
971 typedef void (*GstQTMuxAddTagFunc) (GstQTMux * mux, const GstTagList * list,
972 const char *tag, const char *tag2, guint32 fourcc);
975 * Struct to record mappings from gstreamer tags to fourcc codes
977 typedef struct _GstTagToFourcc
981 const gchar *gsttag2;
982 const GstQTMuxAddTagFunc func;
985 /* tag list tags to fourcc matching */
986 static const GstTagToFourcc tag_matches_mp4[] = {
987 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
988 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
989 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
990 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
991 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
992 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
993 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
994 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
995 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
996 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
997 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
998 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
999 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1000 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1001 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1002 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1003 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1004 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1005 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1006 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1007 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1008 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1009 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1010 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1011 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1012 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1013 gst_qt_mux_add_mp4_tag},
1014 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1015 gst_qt_mux_add_mp4_tag},
1016 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1017 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1021 static const GstTagToFourcc tag_matches_3gp[] = {
1022 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1023 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1024 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1025 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1026 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1027 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1028 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1029 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1030 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1031 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1032 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1033 gst_qt_mux_add_3gp_classification},
1037 /* qtdemux produces these for atoms it cannot parse */
1038 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1041 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1043 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1044 GstBuffer *xmp = NULL;
1046 /* adobe specs only have 'quicktime' and 'mp4',
1047 * but I guess we can extrapolate to gpp.
1048 * Keep mj2 out for now as we don't add any tags for it yet.
1049 * If you have further info about xmp on these formats, please share */
1050 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1053 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1055 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1056 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1059 atom_moov_add_xmp_tags (qtmux->moov, xmp);
1062 /* for isom/mp4, it is a top level uuid atom */
1063 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1066 ainfo = build_uuid_xmp_atom (xmp);
1068 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1073 gst_buffer_unref (xmp);
1077 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list)
1079 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1082 const gchar *tag, *tag2;
1083 const GstTagToFourcc *tag_matches;
1085 switch (qtmux_klass->format) {
1086 case GST_QT_MUX_FORMAT_3GP:
1087 tag_matches = tag_matches_3gp;
1089 case GST_QT_MUX_FORMAT_MJ2:
1093 /* sort of iTunes style for mp4 and QT (?) */
1094 tag_matches = tag_matches_mp4;
1101 for (i = 0; tag_matches[i].fourcc; i++) {
1102 fourcc = tag_matches[i].fourcc;
1103 tag = tag_matches[i].gsttag;
1104 tag2 = tag_matches[i].gsttag2;
1106 g_assert (tag_matches[i].func);
1107 tag_matches[i].func (qtmux, list, tag, tag2, fourcc);
1110 /* add unparsed blobs if present */
1111 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1114 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1115 for (i = 0; i < num_tags; ++i) {
1118 GstCaps *caps = NULL;
1120 val = gst_tag_list_get_value_index (list, GST_QT_DEMUX_PRIVATE_TAG, i);
1121 buf = (GstBuffer *) gst_value_get_buffer (val);
1124 if (buf && (caps = NULL /*gst_buffer_get_caps (buf) */ )) {
1126 const gchar *style = NULL;
1129 gst_buffer_map (buf, &map, GST_MAP_READ);
1130 GST_DEBUG_OBJECT (qtmux,
1131 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", caps %"
1132 GST_PTR_FORMAT, i, num_tags, map.size, caps);
1133 s = gst_caps_get_structure (caps, 0);
1134 if (s && (style = gst_structure_get_string (s, "style"))) {
1135 /* try to prevent some style tag ending up into another variant
1136 * (todo: make into a list if more cases) */
1137 if ((strcmp (style, "itunes") == 0 &&
1138 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1139 (strcmp (style, "iso") == 0 &&
1140 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1141 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1142 atom_moov_add_blob_tag (qtmux->moov, map.data, map.size);
1145 gst_buffer_unmap (buf, &map);
1146 gst_caps_unref (caps);
1155 * Gets the tagsetter iface taglist and puts the known tags
1156 * into the output stream
1159 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1161 const GstTagList *tags;
1163 GST_OBJECT_LOCK (qtmux);
1164 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1165 GST_OBJECT_UNLOCK (qtmux);
1167 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1169 if (tags && !gst_tag_list_is_empty (tags)) {
1170 GstTagList *copy = gst_tag_list_copy (tags);
1172 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1173 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1174 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1175 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1177 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1178 gst_qt_mux_add_metadata_tags (qtmux, copy);
1179 gst_qt_mux_add_xmp_tags (qtmux, copy);
1180 gst_tag_list_free (copy);
1182 GST_DEBUG_OBJECT (qtmux, "No tags received");
1186 static inline GstBuffer *
1187 _gst_buffer_new_take_data (guint8 * data, guint size)
1191 buf = gst_buffer_new ();
1192 gst_buffer_append_memory (buf,
1193 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1198 static GstFlowReturn
1199 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1205 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1207 size = gst_buffer_get_size (buf);
1208 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1210 if (mind_fast && qtmux->fast_start_file) {
1214 GST_LOG_OBJECT (qtmux, "to temporary file");
1215 gst_buffer_map (buf, &map, GST_MAP_READ);
1216 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1217 gst_buffer_unmap (buf, &map);
1218 gst_buffer_unref (buf);
1224 GST_LOG_OBJECT (qtmux, "downstream");
1225 res = gst_pad_push (qtmux->srcpad, buf);
1228 if (G_LIKELY (offset))
1236 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1237 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1238 return GST_FLOW_ERROR;
1243 gst_qt_mux_seek_to_beginning (FILE * f)
1246 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1248 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1249 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1252 if (fseek (f, (long) 0, SEEK_SET) != 0)
1258 static GstFlowReturn
1259 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1261 GstFlowReturn ret = GST_FLOW_OK;
1262 GstBuffer *buf = NULL;
1264 if (fflush (qtmux->fast_start_file))
1267 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1270 /* hm, this could all take a really really long time,
1271 * but there may not be another way to get moov atom first
1272 * (somehow optimize copy?) */
1273 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1274 while (ret == GST_FLOW_OK) {
1275 const int bufsize = 4096;
1279 buf = gst_buffer_new_and_alloc (bufsize);
1280 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1281 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1283 gst_buffer_unmap (buf, &map);
1286 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d",
1288 gst_buffer_unmap (buf, &map);
1289 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1293 gst_buffer_unref (buf);
1295 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1297 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1305 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1306 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1307 ret = GST_FLOW_ERROR;
1312 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1313 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1314 ret = GST_FLOW_ERROR;
1319 /* clear descriptor so we don't remove temp file later on,
1320 * might be possible to recover */
1321 fclose (qtmux->fast_start_file);
1322 qtmux->fast_start_file = NULL;
1328 * Sends the initial mdat atom fields (size fields and fourcc type),
1329 * the subsequent buffers are considered part of it's data.
1330 * As we can't predict the amount of data that we are going to place in mdat
1331 * we need to record the position of the size field in the stream so we can
1332 * seek back to it later and update when the streams have finished.
1334 static GstFlowReturn
1335 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1340 guint8 *data = NULL;
1343 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1344 "size %" G_GUINT64_FORMAT, size);
1346 node_header = g_malloc0 (sizeof (Atom));
1347 node_header->type = FOURCC_mdat;
1349 /* use extended size */
1350 node_header->size = 1;
1351 node_header->extended_size = 0;
1353 node_header->extended_size = size + 16;
1355 node_header->size = size + 8;
1359 if (atom_copy_data (node_header, &data, &size, &offset) == 0)
1360 goto serialize_error;
1362 buf = _gst_buffer_new_take_data (data, offset);
1363 g_free (node_header);
1365 GST_LOG_OBJECT (qtmux, "Pushing mdat start");
1366 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1371 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1372 ("Failed to serialize mdat"));
1373 return GST_FLOW_ERROR;
1378 * We get the position of the mdat size field, seek back to it
1379 * and overwrite with the real value
1381 static GstFlowReturn
1382 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1383 guint64 mdat_size, guint64 * offset)
1386 gboolean large_file;
1390 large_file = (mdat_size > MDAT_LARGE_FILE_LIMIT);
1395 /* seek and rewrite the header */
1396 gst_segment_init (&segment, GST_FORMAT_BYTES);
1397 segment.start = mdat_pos;
1398 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1401 buf = gst_buffer_new_and_alloc (sizeof (guint64));
1402 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1403 GST_WRITE_UINT64_BE (map.data, mdat_size + 16);
1405 buf = gst_buffer_new_and_alloc (16);
1406 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1407 GST_WRITE_UINT32_BE (map.data, 8);
1408 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1409 GST_WRITE_UINT32_BE (map.data + 8, mdat_size + 8);
1410 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1412 gst_buffer_unmap (buf, &map);
1414 return gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1417 static GstFlowReturn
1418 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1421 guint64 size = 0, offset = 0;
1422 guint8 *data = NULL;
1424 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1426 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1427 goto serialize_error;
1429 buf = _gst_buffer_new_take_data (data, offset);
1431 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1432 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1437 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1438 ("Failed to serialize ftyp"));
1439 return GST_FLOW_ERROR;
1444 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1445 GstBuffer ** p_prefix)
1447 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1448 guint32 major, version;
1450 GstBuffer *prefix = NULL;
1451 AtomFTYP *ftyp = NULL;
1453 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1455 /* init and send context and ftyp based on current property state */
1456 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1457 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1458 qtmux->fast_start_file != NULL);
1459 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1466 gst_buffer_unref (prefix);
1471 static GstFlowReturn
1472 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1474 GstFlowReturn ret = GST_FLOW_OK;
1475 GstBuffer *prefix = NULL;
1477 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1479 /* init and send context and ftyp based on current property state */
1481 atom_ftyp_free (qtmux->ftyp);
1484 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1486 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1487 if (ret != GST_FLOW_OK)
1490 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1494 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1496 GstStructure *structure;
1497 GValue array = { 0 };
1498 GValue value = { 0 };
1499 GstCaps *caps, *tcaps;
1501 tcaps = gst_pad_get_current_caps (mux->srcpad);
1502 caps = gst_caps_copy (tcaps);
1503 gst_caps_unref (tcaps);
1505 structure = gst_caps_get_structure (caps, 0);
1507 g_value_init (&array, GST_TYPE_ARRAY);
1509 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1510 g_value_init (&value, GST_TYPE_BUFFER);
1511 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1512 gst_value_array_append_value (&array, &value);
1513 g_value_unset (&value);
1515 gst_structure_set_value (structure, "streamheader", &array);
1516 g_value_unset (&array);
1517 gst_pad_set_caps (mux->srcpad, caps);
1518 gst_caps_unref (caps);
1522 gst_qt_mux_configure_moov (GstQTMux * qtmux, guint32 * _timescale)
1524 gboolean fragmented;
1527 GST_OBJECT_LOCK (qtmux);
1528 timescale = qtmux->timescale;
1529 fragmented = qtmux->fragment_sequence > 0;
1530 GST_OBJECT_UNLOCK (qtmux);
1532 /* inform lower layers of our property wishes, and determine duration.
1533 * Let moov take care of this using its list of traks;
1534 * so that released pads are also included */
1535 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1537 atom_moov_update_timescale (qtmux->moov, timescale);
1538 atom_moov_set_fragmented (qtmux->moov, fragmented);
1540 atom_moov_update_duration (qtmux->moov);
1543 *_timescale = timescale;
1546 static GstFlowReturn
1547 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset, gboolean mind_fast)
1549 guint64 offset = 0, size = 0;
1552 GstFlowReturn ret = GST_FLOW_OK;
1554 /* serialize moov */
1557 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1558 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1559 goto serialize_error;
1561 buf = _gst_buffer_new_take_data (data, offset);
1562 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1563 gst_qt_mux_set_header_on_caps (qtmux, buf);
1564 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1571 return GST_FLOW_ERROR;
1575 /* either calculates size of extra atoms or pushes them */
1576 static GstFlowReturn
1577 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1581 guint64 loffset = 0, size = 0;
1583 GstFlowReturn ret = GST_FLOW_OK;
1585 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1586 AtomInfo *ainfo = (AtomInfo *) walk->data;
1590 if (!ainfo->copy_data_func (ainfo->atom,
1591 send ? &data : NULL, &size, &loffset))
1592 goto serialize_error;
1597 GST_DEBUG_OBJECT (qtmux,
1598 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1599 GST_FOURCC_ARGS (ainfo->atom->type));
1600 buf = _gst_buffer_new_take_data (data, loffset);
1601 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1602 if (ret != GST_FLOW_OK)
1615 return GST_FLOW_ERROR;
1619 static GstFlowReturn
1620 gst_qt_mux_start_file (GstQTMux * qtmux)
1622 GstFlowReturn ret = GST_FLOW_OK;
1626 GST_DEBUG_OBJECT (qtmux, "starting file");
1628 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
1629 /* qtmux has structure with and without variant, remove all but the first */
1630 while (gst_caps_get_size (caps) > 1)
1631 gst_caps_remove_structure (caps, 1);
1632 gst_pad_set_caps (qtmux->srcpad, caps);
1633 gst_caps_unref (caps);
1635 /* if not streaming, check if downstream is seekable */
1636 if (!qtmux->streamable) {
1640 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1641 if (gst_pad_peer_query (qtmux->srcpad, query)) {
1642 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1643 GST_INFO_OBJECT (qtmux, "downstream is %sseekable",
1644 seekable ? "" : "not ");
1646 /* have to assume seeking is supported if query not handled downstream */
1647 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
1651 qtmux->streamable = TRUE;
1652 g_object_notify (G_OBJECT (qtmux), "streamable");
1653 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
1654 "streamable=false. Will ignore that and create streamable output "
1657 gst_query_unref (query);
1660 /* let downstream know we think in BYTES and expect to do seeking later on */
1661 gst_segment_init (&segment, GST_FORMAT_BYTES);
1662 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1664 /* initialize our moov recovery file */
1665 GST_OBJECT_LOCK (qtmux);
1666 if (qtmux->moov_recov_file_path) {
1667 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1668 qtmux->moov_recov_file_path);
1669 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1670 if (qtmux->moov_recov_file == NULL) {
1671 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1672 qtmux->moov_recov_file_path);
1675 gboolean fail = FALSE;
1676 AtomFTYP *ftyp = NULL;
1677 GstBuffer *prefix = NULL;
1679 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1681 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1682 qtmux->moov, qtmux->timescale,
1683 g_slist_length (qtmux->sinkpads))) {
1684 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1689 atom_ftyp_free (ftyp);
1691 gst_buffer_unref (prefix);
1693 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1694 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1695 GstQTPad *qpad = (GstQTPad *) cdata;
1696 /* write info for each stream */
1697 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1699 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1705 fclose (qtmux->moov_recov_file);
1706 qtmux->moov_recov_file = NULL;
1707 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1708 "recover file, moov recovery won't work");
1712 GST_OBJECT_UNLOCK (qtmux);
1715 * send mdat header if already needed, and mark position for later update.
1716 * We don't send ftyp now if we are on fast start mode, because we can
1717 * better fine tune using the information we gather to create the whole moov
1720 if (qtmux->fast_start) {
1721 GST_OBJECT_LOCK (qtmux);
1722 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1723 if (!qtmux->fast_start_file)
1725 GST_OBJECT_UNLOCK (qtmux);
1727 /* send a dummy buffer for preroll */
1728 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1729 if (ret != GST_FLOW_OK)
1733 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1734 if (ret != GST_FLOW_OK) {
1738 /* well, it's moov pos if fragmented ... */
1739 qtmux->mdat_pos = qtmux->header_size;
1741 if (qtmux->fragment_duration) {
1742 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1743 qtmux->fragment_duration);
1744 /* also used as snapshot marker to indicate fragmented file */
1745 qtmux->fragment_sequence = 1;
1746 /* prepare moov and/or tags */
1747 gst_qt_mux_configure_moov (qtmux, NULL);
1748 gst_qt_mux_setup_metadata (qtmux);
1749 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1750 if (ret != GST_FLOW_OK)
1754 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1755 if (ret != GST_FLOW_OK)
1758 if (!qtmux->streamable)
1759 qtmux->mfra = atom_mfra_new (qtmux->context);
1761 /* extended to ensure some spare space */
1762 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1772 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1773 (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1775 GST_OBJECT_UNLOCK (qtmux);
1776 return GST_FLOW_ERROR;
1780 static GstFlowReturn
1781 gst_qt_mux_stop_file (GstQTMux * qtmux)
1783 gboolean ret = GST_FLOW_OK;
1784 guint64 offset = 0, size = 0;
1786 gboolean large_file;
1788 GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1790 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1792 /* pushing last buffers for each pad */
1793 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1794 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1795 GstQTPad *qtpad = (GstQTPad *) cdata;
1797 /* avoid add_buffer complaining if not negotiated
1798 * in which case no buffers either, so skipping */
1799 if (!qtpad->fourcc) {
1800 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
1801 GST_PAD_NAME (qtpad->collect.pad));
1805 /* send last buffer; also flushes possibly queued buffers/ts */
1806 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1807 GST_PAD_NAME (qtpad->collect.pad));
1808 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1809 if (ret != GST_FLOW_OK) {
1810 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1811 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1812 gst_flow_get_name (ret));
1815 /* having flushed above, can check for buffers now */
1816 if (!GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
1817 GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1818 GST_PAD_NAME (qtpad->collect.pad));
1822 /* determine max stream duration */
1823 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1824 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1825 qtpad->last_dts > first_ts)) {
1826 first_ts = qtpad->last_dts;
1829 /* update average bitrate of streams if needed */
1831 guint32 avgbitrate = 0;
1832 guint32 maxbitrate = qtpad->max_bitrate;
1834 if (qtpad->avg_bitrate)
1835 avgbitrate = qtpad->avg_bitrate;
1836 else if (qtpad->total_duration > 0)
1837 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
1838 8 * GST_SECOND, qtpad->total_duration);
1840 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
1844 if (qtmux->fragment_sequence) {
1848 guint8 *data = NULL;
1852 GST_DEBUG_OBJECT (qtmux, "adding mfra");
1853 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1854 goto serialize_error;
1855 buf = _gst_buffer_new_take_data (data, offset);
1856 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1857 if (ret != GST_FLOW_OK)
1860 /* must have been streamable; no need to write duration */
1861 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1865 timescale = qtmux->timescale;
1866 /* only mvex duration is updated,
1867 * mvhd should be consistent with empty moov
1868 * (but TODO maybe some clients do not handle that well ?) */
1869 qtmux->moov->mvex.mehd.fragment_duration =
1870 gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1871 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1872 GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1873 /* seek and rewrite the header */
1874 gst_segment_init (&segment, GST_FORMAT_BYTES);
1875 segment.start = qtmux->mdat_pos;
1876 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1877 /* no need to seek back */
1878 return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1881 gst_qt_mux_configure_moov (qtmux, ×cale);
1883 /* check for late streams */
1884 first_ts = GST_CLOCK_TIME_NONE;
1885 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1886 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1887 GstQTPad *qtpad = (GstQTPad *) cdata;
1889 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1890 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1891 qtpad->first_ts < first_ts)) {
1892 first_ts = qtpad->first_ts;
1895 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1896 GST_TIME_ARGS (first_ts));
1897 /* add EDTSs for late streams */
1898 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1899 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1900 GstQTPad *qtpad = (GstQTPad *) cdata;
1904 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1905 qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1906 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1907 GST_PAD_NAME (qtpad->collect.pad),
1908 GST_TIME_ARGS (qtpad->first_ts - first_ts));
1909 lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1910 timescale, GST_SECOND);
1911 duration = qtpad->trak->tkhd.duration;
1912 atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1913 (guint32) (1 * 65536.0));
1914 atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1915 (guint32) (1 * 65536.0));
1917 /* need to add the empty time to the trak duration */
1918 qtpad->trak->tkhd.duration += lateness;
1922 /* tags into file metadata */
1923 gst_qt_mux_setup_metadata (qtmux);
1925 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1926 /* if faststart, update the offset of the atoms in the movie with the offset
1927 * that the movie headers before mdat will cause.
1928 * Also, send the ftyp */
1929 if (qtmux->fast_start_file) {
1930 GstFlowReturn flow_ret;
1933 flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1934 if (flow_ret != GST_FLOW_OK) {
1937 /* copy into NULL to obtain size */
1938 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1939 goto serialize_error;
1940 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1942 offset += qtmux->header_size + (large_file ? 16 : 8);
1944 /* sum up with the extra atoms size */
1945 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1946 if (ret != GST_FLOW_OK)
1949 offset = qtmux->header_size;
1951 atom_moov_chunks_add_offset (qtmux->moov, offset);
1954 /* note: as of this point, we no longer care about tracking written data size,
1955 * since there is no more use for it anyway */
1956 ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1957 if (ret != GST_FLOW_OK)
1961 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1962 if (ret != GST_FLOW_OK)
1965 /* if needed, send mdat atom and move buffered data into it */
1966 if (qtmux->fast_start_file) {
1967 /* mdat_size = accumulated (buffered data) */
1968 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1970 if (ret != GST_FLOW_OK)
1972 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1973 if (ret != GST_FLOW_OK)
1976 /* mdat needs update iff not using faststart */
1977 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1978 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1979 qtmux->mdat_size, NULL);
1980 /* note; no seeking back to the end of file is done,
1981 * since we no longer write anything anyway */
1989 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1990 ("Failed to serialize moov"));
1991 return GST_FLOW_ERROR;
1995 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1996 return GST_FLOW_ERROR;
2000 static GstFlowReturn
2001 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2002 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2003 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2005 GstFlowReturn ret = GST_FLOW_OK;
2007 /* setup if needed */
2008 if (G_UNLIKELY (!pad->traf || force))
2012 /* flush pad fragment if threshold reached,
2013 * or at new keyframe if we should be minding those in the first place */
2014 if (G_UNLIKELY (force || (sync && pad->sync) ||
2015 pad->fragment_duration < (gint64) delta)) {
2017 guint64 size = 0, offset = 0;
2018 guint8 *data = NULL;
2020 guint i, total_size;
2022 /* now we know where moof ends up, update offset in tfra */
2024 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2026 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2027 /* takes ownership */
2028 atom_moof_add_traf (moof, pad->traf);
2030 atom_moof_copy_data (moof, &data, &size, &offset);
2031 buffer = _gst_buffer_new_take_data (data, offset);
2032 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2033 gst_buffer_get_size (buffer));
2034 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2036 /* and actual data */
2038 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2040 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2043 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2044 atom_array_get_len (&pad->fragment_buffers), total_size);
2045 if (ret == GST_FLOW_OK)
2046 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2048 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2049 if (G_LIKELY (ret == GST_FLOW_OK))
2050 ret = gst_qt_mux_send_buffer (qtmux,
2051 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2054 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2057 atom_array_clear (&pad->fragment_buffers);
2058 atom_moof_free (moof);
2059 qtmux->fragment_sequence++;
2064 if (G_UNLIKELY (!pad->traf)) {
2065 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2066 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2067 atom_array_init (&pad->fragment_buffers, 512);
2068 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2069 atom_trak_get_timescale (pad->trak), 1000);
2071 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2072 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2073 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2077 /* add buffer and metadata */
2078 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2080 atom_array_append (&pad->fragment_buffers, buf, 256);
2081 pad->fragment_duration -= delta;
2084 guint32 sn = atom_traf_get_sample_num (pad->traf);
2086 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2087 atom_tfra_add_entry (pad->tfra, dts, sn);
2090 if (G_UNLIKELY (force))
2096 /* sigh, tiny list helpers to re-order stuff */
2098 gst_qt_mux_push_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2102 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2103 if (ts > pad->ts_entries[i])
2106 memmove (&pad->ts_entries[i + 1], &pad->ts_entries[i],
2107 sizeof (GstClockTime) * (pad->ts_n_entries - i));
2108 pad->ts_entries[i] = ts;
2109 pad->ts_n_entries++;
2113 check_and_subtract_ts (GstQTMux * qtmux, GstClockTime * ts_a, GstClockTime ts_b)
2115 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (*ts_a))) {
2116 if (G_LIKELY (*ts_a > ts_b)) {
2120 GST_WARNING_OBJECT (qtmux, "Subtraction would result in negative value, "
2121 "using 0 as result");
2126 /* subtract ts from all buffers enqueued on the pad */
2128 gst_qt_mux_subtract_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2132 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2133 check_and_subtract_ts (qtmux, &pad->ts_entries[i], ts);
2135 for (i = 0; i < G_N_ELEMENTS (pad->buf_entries); i++) {
2136 if (pad->buf_entries[i]) {
2137 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (pad->buf_entries[i]),
2139 check_and_subtract_ts (qtmux,
2140 &GST_BUFFER_OFFSET_END (pad->buf_entries[i]), ts);
2145 /* takes ownership of @buf */
2147 gst_qt_mux_get_asc_buffer_ts (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2149 const gint wrap = G_N_ELEMENTS (pad->buf_entries);
2152 /* store buffer and ts, latter ordered */
2154 pad->buf_entries[pad->buf_tail++] = buf;
2155 pad->buf_tail %= wrap;
2156 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (buf));
2159 if (pad->ts_n_entries && (!buf || pad->ts_n_entries >= QTMUX_NO_OF_TS)) {
2160 ts = pad->ts_entries[--pad->ts_n_entries];
2161 buf = pad->buf_entries[pad->buf_head];
2162 pad->buf_entries[pad->buf_head++] = NULL;
2163 pad->buf_head %= wrap;
2164 buf = gst_buffer_make_writable (buf);
2165 /* track original ts (= pts ?) for later */
2166 GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_TIMESTAMP (buf);
2167 GST_BUFFER_TIMESTAMP (buf) = ts;
2168 GST_DEBUG_OBJECT (qtmux, "next buffer uses reordered ts %" GST_TIME_FORMAT,
2169 GST_TIME_ARGS (ts));
2178 * Here we push the buffer and update the tables in the track atoms
2180 static GstFlowReturn
2181 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2183 GstBuffer *last_buf = NULL;
2184 GstClockTime duration;
2185 guint nsamples, sample_size;
2186 guint64 chunk_offset;
2187 gint64 last_dts, scaled_duration;
2188 gint64 pts_offset = 0;
2189 gboolean sync = FALSE, do_pts = FALSE;
2190 gboolean drain = (buf == NULL);
2191 GstFlowReturn ret = GST_FLOW_OK;
2194 goto not_negotiated;
2196 /* if this pad has a prepare function, call it */
2197 if (pad->prepare_buf_func != NULL) {
2198 buf = pad->prepare_buf_func (pad, buf, qtmux);
2201 if (G_LIKELY (buf != NULL && GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
2202 pad->first_ts != 0)) {
2203 buf = gst_buffer_make_writable (buf);
2204 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2206 /* when we obtain the first_ts we subtract from all stored buffers we have,
2207 * after that we can subtract on input */
2210 last_buf = pad->last_buf;
2211 if (qtmux->dts_method == DTS_METHOD_REORDER) {
2212 buf = gst_qt_mux_get_asc_buffer_ts (qtmux, pad, buf);
2213 if (!buf && !last_buf) {
2214 GST_DEBUG_OBJECT (qtmux, "no reordered buffer");
2219 if (last_buf == NULL) {
2220 #ifndef GST_DISABLE_GST_DEBUG
2222 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
2223 "received NULL buffer, doing nothing",
2224 GST_PAD_NAME (pad->collect.pad));
2226 GST_LOG_OBJECT (qtmux,
2227 "Pad %s has no previous buffer stored, storing now",
2228 GST_PAD_NAME (pad->collect.pad));
2231 pad->last_buf = buf;
2234 gst_buffer_ref (last_buf);
2236 /* nasty heuristic mess to guestimate dealing with DTS/PTS,
2237 * while also trying to stay close to input ts to preserve sync,
2238 * so in DTS_METHOD_DD:
2239 * - prefer using input ts where possible
2240 * - if those detected out-of-order (*), mark as out-of-order
2241 * - if in out-of-order, then
2242 * - if duration available, use that as delta
2243 * Also mind to preserve sync between streams, and adding
2244 * durations might drift, so try to resync when we expect
2245 * input ts == (sum of durations), which is at some keyframe input frame.
2246 * - if no duration available, we are actually in serious trouble and need
2247 * to hack around that, so we fail.
2248 * To remedy failure, alternatively, in DTS_METHOD_REORDER:
2249 * - collect some buffers and re-order timestamp,
2250 * then process the oldest buffer with smallest timestamps.
2251 * This should typically compensate for some codec's handywork with ts.
2252 * ... but in case this makes ts end up where not expected, in DTS_METHOD_ASC:
2253 * - keep each ts with its buffer and still keep a list of most recent X ts,
2254 * use the (ascending) minimum of those as DTS (and the difference as ts delta),
2255 * and use this DTS as a basis to obtain a (positive) CTS offset.
2256 * This should yield exact PTS == buffer ts, but it seems not all players
2257 * out there are aware of ctts pts ...
2259 * 0.11 Phew, can we (pretty) please please sort out DTS/PTS on buffers ...
2261 if (G_LIKELY (buf) && !pad->is_out_of_order) {
2262 if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (last_buf) &&
2263 GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
2264 if ((GST_BUFFER_TIMESTAMP (buf) < GST_BUFFER_TIMESTAMP (last_buf))) {
2265 GST_DEBUG_OBJECT (qtmux, "detected out-of-order input");
2266 pad->is_out_of_order = TRUE;
2269 /* this is pretty bad */
2270 GST_WARNING_OBJECT (qtmux, "missing input timestamp");
2271 /* fall back to durations */
2272 pad->is_out_of_order = TRUE;
2276 /* would have to be some unusual input, but not impossible */
2277 if (G_UNLIKELY (qtmux->dts_method == DTS_METHOD_REORDER &&
2278 pad->is_out_of_order)) {
2282 /* if this is the first buffer, store the timestamp */
2283 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2284 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (last_buf))) {
2285 pad->first_ts = GST_BUFFER_TIMESTAMP (last_buf);
2287 GST_DEBUG_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2288 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2291 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2292 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2293 GST_TIME_ARGS (pad->first_ts));
2295 gst_qt_mux_subtract_ts (qtmux, pad, pad->first_ts);
2297 GST_BUFFER_TIMESTAMP (last_buf) = 0;
2298 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (last_buf),
2301 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2302 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (buf),
2307 /* fall back to duration if last buffer or
2308 * out-of-order (determined previously), otherwise use input ts */
2310 (pad->is_out_of_order && qtmux->dts_method == DTS_METHOD_DD)) {
2311 if (!GST_BUFFER_DURATION_IS_VALID (last_buf)) {
2312 /* be forgiving for some possibly last upstream flushed buffer */
2315 GST_WARNING_OBJECT (qtmux, "no duration for last buffer");
2316 /* iso spec recommends some small value, try 0 */
2319 duration = GST_BUFFER_DURATION (last_buf);
2320 /* avoid drift in sum timestamps,
2321 * so use input timestamp for suitable keyframe */
2322 if (buf && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) &&
2323 GST_BUFFER_TIMESTAMP (buf) >= pad->last_dts) {
2324 GST_DEBUG_OBJECT (qtmux, "resyncing out-of-order input to ts; "
2325 "replacing %" GST_TIME_FORMAT " by %" GST_TIME_FORMAT,
2326 GST_TIME_ARGS (pad->last_dts + duration),
2327 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2328 duration = GST_BUFFER_TIMESTAMP (buf) - pad->last_dts;
2331 } else if (qtmux->dts_method != DTS_METHOD_ASC) {
2332 duration = GST_BUFFER_TIMESTAMP (buf) - GST_BUFFER_TIMESTAMP (last_buf);
2336 g_assert (qtmux->dts_method == DTS_METHOD_ASC);
2337 if (!qtmux->guess_pts)
2340 /* add timestamp to queue; keeps in descending order */
2341 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (last_buf));
2342 /* chuck out smallest/last one if we have enough */
2343 if (G_LIKELY (pad->ts_n_entries > QTMUX_NO_OF_TS))
2344 pad->ts_n_entries--;
2345 /* peek the now smallest timestamp */
2346 ts = pad->ts_entries[pad->ts_n_entries - 1];
2347 /* these tails are expected to be (strictly) ascending with
2348 * large enough history */
2349 GST_DEBUG_OBJECT (qtmux, "ASC method; base timestamp %" GST_TIME_FORMAT,
2350 GST_TIME_ARGS (ts));
2351 if (ts >= pad->last_dts) {
2352 duration = ts - pad->last_dts;
2354 /* fallback to previous value, negative ct offset might handle */
2355 GST_WARNING_OBJECT (qtmux, "unexpected decrease in timestamp");
2358 /* arrange for small non-zero duration/delta << expected frame time */
2359 ts = gst_util_uint64_scale (10, GST_SECOND,
2360 atom_trak_get_timescale (pad->trak));
2361 duration = MAX (duration, ts);
2364 /* for computing the avg bitrate */
2365 if (G_LIKELY (last_buf)) {
2366 pad->total_bytes += gst_buffer_get_size (last_buf);
2367 pad->total_duration += duration;
2370 gst_buffer_replace (&pad->last_buf, buf);
2372 last_dts = gst_util_uint64_scale_round (pad->last_dts,
2373 atom_trak_get_timescale (pad->trak), GST_SECOND);
2375 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2376 if (pad->sample_size && !qtmux->fragment_sequence) {
2377 /* Constant size packets: usually raw audio (with many samples per
2378 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2380 sample_size = pad->sample_size;
2381 if (gst_buffer_get_size (last_buf) % sample_size != 0)
2382 goto fragmented_sample;
2383 /* note: qt raw audio storage warps it implicitly into a timewise
2384 * perfect stream, discarding buffer times */
2385 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2386 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2387 atom_trak_get_timescale (pad->trak), GST_SECOND);
2389 nsamples = gst_buffer_get_size (last_buf) / sample_size;
2391 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2393 /* timescale = samplerate */
2394 scaled_duration = 1;
2395 pad->last_dts += duration * nsamples;
2398 sample_size = gst_buffer_get_size (last_buf);
2399 if (pad->have_dts) {
2401 pad->last_dts = GST_BUFFER_OFFSET_END (last_buf);
2402 if ((gint64) (pad->last_dts) < 0) {
2403 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2404 atom_trak_get_timescale (pad->trak), GST_SECOND);
2406 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2407 atom_trak_get_timescale (pad->trak), GST_SECOND);
2409 scaled_duration = scaled_dts - last_dts;
2410 last_dts = scaled_dts;
2412 /* first convert intended timestamp (in GstClockTime resolution) to
2413 * trak timescale, then derive delta;
2414 * this ensures sums of (scale)delta add up to converted timestamp,
2415 * which only deviates at most 1/scale from timestamp itself */
2416 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2417 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2418 pad->last_dts += duration;
2421 chunk_offset = qtmux->mdat_size;
2423 GST_LOG_OBJECT (qtmux,
2424 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2425 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2426 GST_LOG_OBJECT (qtmux,
2427 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2428 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2429 nsamples, scaled_duration, sample_size, chunk_offset);
2431 /* might be a sync sample */
2433 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2434 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2435 GST_PAD_NAME (pad->collect.pad));
2439 /* optionally calculate ctts entry values
2440 * (if composition-time expected different from decoding-time) */
2441 /* really not recommended:
2442 * - decoder typically takes care of dts/pts issues
2443 * - in case of out-of-order, dts may only be determined as above
2444 * (e.g. sum of duration), which may be totally different from
2445 * buffer timestamps in case of multiple segment, non-perfect streams
2446 * (and just perhaps maybe with some luck segment_to_running_time
2447 * or segment_to_media_time might get near to it) */
2448 if ((pad->have_dts || qtmux->guess_pts)) {
2451 pts = qtmux->dts_method == DTS_METHOD_REORDER ?
2452 GST_BUFFER_OFFSET_END (last_buf) : GST_BUFFER_TIMESTAMP (last_buf);
2453 pts = gst_util_uint64_scale_round (pts,
2454 atom_trak_get_timescale (pad->trak), GST_SECOND);
2455 pts_offset = (gint64) (pts - last_dts);
2457 GST_LOG_OBJECT (qtmux, "Adding ctts entry for pad %s: %" G_GINT64_FORMAT,
2458 GST_PAD_NAME (pad->collect.pad), pts_offset);
2462 * Each buffer starts a new chunk, so we can assume the buffer
2463 * duration is the chunk duration
2465 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2466 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2467 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2468 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2469 qtmux->longest_chunk = duration;
2472 /* now we go and register this buffer/sample all over */
2473 /* note that a new chunk is started each time (not fancy but works) */
2474 if (qtmux->moov_recov_file) {
2475 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2476 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2477 do_pts, pts_offset)) {
2478 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2479 "recovery file, disabling recovery");
2480 fclose (qtmux->moov_recov_file);
2481 qtmux->moov_recov_file = NULL;
2486 gst_buffer_unref (buf);
2488 if (qtmux->fragment_sequence) {
2489 /* ensure that always sync samples are marked as such */
2490 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2491 buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2492 !pad->sync || sync, pts_offset);
2494 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2495 sample_size, chunk_offset, sync, pts_offset);
2496 ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2500 if (G_UNLIKELY (drain && qtmux->dts_method == DTS_METHOD_REORDER &&
2501 ret == GST_FLOW_OK)) {
2512 gst_buffer_unref (buf);
2513 gst_buffer_unref (last_buf);
2514 return GST_FLOW_ERROR;
2518 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2519 ("Received buffer without timestamp/duration. "
2520 "Using e.g. dts-method=reorder might help."));
2525 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2526 ("DTS method failed to re-order timestamps."));
2531 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2532 ("Selected DTS method also needs PTS enabled."));
2537 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2538 ("Audio buffer contains fragmented sample."));
2543 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2544 ("format wasn't negotiated before buffer flow on pad %s",
2545 GST_PAD_NAME (pad->collect.pad)));
2547 gst_buffer_unref (buf);
2548 return GST_FLOW_NOT_NEGOTIATED;
2552 static GstFlowReturn
2553 gst_qt_mux_handle_buffer (GstCollectPads2 * pads, GstCollectData2 * cdata,
2554 GstBuffer * buf, gpointer user_data)
2556 GstFlowReturn ret = GST_FLOW_OK;
2557 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2558 GstQTPad *best_pad = NULL;
2559 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2561 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2562 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2565 qtmux->state = GST_QT_MUX_STATE_DATA;
2568 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2569 return GST_FLOW_EOS;
2571 best_pad = (GstQTPad *) cdata;
2573 /* clipping already converted to running time */
2574 if (best_pad != NULL) {
2576 best_time = GST_BUFFER_TIMESTAMP (buf);
2577 GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2578 GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2579 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2581 ret = gst_qt_mux_stop_file (qtmux);
2582 if (ret == GST_FLOW_OK) {
2583 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2584 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2587 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2588 gst_flow_get_name (ret));
2590 qtmux->state = GST_QT_MUX_STATE_EOS;
2597 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2599 GstStructure *structure = (GstStructure *) user_data;
2600 const GValue *other = gst_structure_id_get_value (structure, field_id);
2603 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2607 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2610 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2611 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2613 return gst_structure_foreach (sub_s, check_field, sup_s);
2617 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2619 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2620 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2621 GstQTPad *qtpad = NULL;
2622 GstStructure *structure;
2623 const gchar *mimetype;
2624 gint rate, channels;
2625 const GValue *value = NULL;
2626 const GstBuffer *codec_data = NULL;
2627 GstQTMuxFormat format;
2628 AudioSampleEntry entry = { 0, };
2629 AtomInfo *ext_atom = NULL;
2630 gint constant_size = 0;
2631 const gchar *stream_format;
2633 /* find stream data */
2634 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2637 qtpad->prepare_buf_func = NULL;
2639 /* does not go well to renegotiate stream mid-way, unless
2640 * the old caps are a subset of the new one (this means upstream
2641 * added more info to the caps, as both should be 'fixed' caps) */
2642 if (qtpad->fourcc) {
2643 GstCaps *current_caps;
2645 current_caps = gst_pad_get_current_caps (pad);
2646 g_assert (caps != NULL);
2648 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2649 gst_caps_unref (current_caps);
2650 goto refuse_renegotiation;
2652 GST_DEBUG_OBJECT (qtmux,
2653 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2654 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2655 gst_caps_unref (current_caps);
2658 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2659 GST_DEBUG_PAD_NAME (pad), caps);
2661 format = qtmux_klass->format;
2662 structure = gst_caps_get_structure (caps, 0);
2663 mimetype = gst_structure_get_name (structure);
2666 if (!gst_structure_get_int (structure, "channels", &channels) ||
2667 !gst_structure_get_int (structure, "rate", &rate)) {
2672 value = gst_structure_get_value (structure, "codec_data");
2674 codec_data = gst_value_get_buffer (value);
2676 qtpad->is_out_of_order = FALSE;
2677 qtpad->have_dts = FALSE;
2679 /* set common properties */
2680 entry.sample_rate = rate;
2681 entry.channels = channels;
2683 entry.sample_size = 16;
2684 /* this is the typical compressed case */
2685 if (format == GST_QT_MUX_FORMAT_QT) {
2687 entry.compression_id = -2;
2690 /* now map onto a fourcc, and some extra properties */
2691 if (strcmp (mimetype, "audio/mpeg") == 0) {
2692 gint mpegversion = 0;
2695 gst_structure_get_int (structure, "mpegversion", &mpegversion);
2696 switch (mpegversion) {
2698 gst_structure_get_int (structure, "layer", &layer);
2702 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2703 if (format == GST_QT_MUX_FORMAT_QT)
2704 entry.fourcc = FOURCC__mp3;
2706 entry.fourcc = FOURCC_mp4a;
2708 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2709 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2710 qtpad->max_bitrate);
2712 entry.samples_per_packet = 1152;
2713 entry.bytes_per_sample = 2;
2719 /* check stream-format */
2720 stream_format = gst_structure_get_string (structure, "stream-format");
2721 if (stream_format) {
2722 if (strcmp (stream_format, "raw") != 0) {
2723 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2724 "please use 'raw'", stream_format);
2728 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2732 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
2733 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2737 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
2738 /* warn if not Low Complexity profile */
2741 GST_WARNING_OBJECT (qtmux,
2742 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2746 entry.fourcc = FOURCC_mp4a;
2748 if (format == GST_QT_MUX_FORMAT_QT)
2749 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2750 qtpad->avg_bitrate, qtpad->max_bitrate);
2753 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2754 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2755 qtpad->max_bitrate);
2760 } else if (strcmp (mimetype, "audio/AMR") == 0) {
2761 entry.fourcc = FOURCC_samr;
2762 entry.sample_size = 16;
2763 entry.samples_per_packet = 160;
2764 entry.bytes_per_sample = 2;
2765 ext_atom = build_amr_extension ();
2766 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2767 entry.fourcc = FOURCC_sawb;
2768 entry.sample_size = 16;
2769 entry.samples_per_packet = 320;
2770 entry.bytes_per_sample = 2;
2771 ext_atom = build_amr_extension ();
2772 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
2775 gst_audio_info_init (&info);
2776 if (!gst_audio_info_from_caps (&info, caps))
2779 /* spec has no place for a distinction in these */
2780 if (info.finfo->width != info.finfo->depth) {
2781 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2785 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
2786 if (info.finfo->endianness == G_LITTLE_ENDIAN)
2787 entry.fourcc = FOURCC_sowt;
2788 else if (info.finfo->endianness == G_BIG_ENDIAN)
2789 entry.fourcc = FOURCC_twos;
2790 /* maximum backward compatibility; only new version for > 16 bit */
2791 if (info.finfo->depth <= 16)
2793 /* not compressed in any case */
2794 entry.compression_id = 0;
2795 /* QT spec says: max at 16 bit even if sample size were actually larger,
2796 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2797 entry.sample_size = info.finfo->depth;
2798 entry.bytes_per_sample = info.finfo->depth / 8;
2799 entry.samples_per_packet = 1;
2800 entry.bytes_per_packet = info.finfo->depth / 8;
2801 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
2803 if (info.finfo->width == 8 && info.finfo->depth == 8) {
2804 /* fall back to old 8-bit version */
2805 entry.fourcc = FOURCC_raw_;
2807 entry.compression_id = 0;
2808 entry.sample_size = 8;
2810 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2814 constant_size = (info.finfo->depth / 8) * info.channels;
2815 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2816 entry.fourcc = FOURCC_alaw;
2817 entry.samples_per_packet = 1023;
2818 entry.bytes_per_sample = 2;
2819 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2820 entry.fourcc = FOURCC_ulaw;
2821 entry.samples_per_packet = 1023;
2822 entry.bytes_per_sample = 2;
2823 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2825 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2826 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2829 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2831 entry.fourcc = MS_WAVE_FOURCC (0x11);
2832 /* 4 byte header per channel (including one sample). 2 samples per byte
2833 remaining. Simplifying gives the following (samples per block per
2835 entry.samples_per_packet = 2 * blocksize / channels - 7;
2836 entry.bytes_per_sample = 2;
2838 entry.bytes_per_frame = blocksize;
2839 entry.bytes_per_packet = blocksize / channels;
2840 /* ADPCM has constant size packets */
2842 /* TODO: I don't really understand why this helps, but it does! Constant
2843 * size and compression_id of -2 seem to be incompatible, and other files
2844 * in the wild use this too. */
2845 entry.compression_id = -1;
2847 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2848 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2849 GstBuffer *codec_config;
2853 entry.fourcc = FOURCC_alac;
2854 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
2855 /* let's check if codec data already comes with 'alac' atom prefix */
2856 if (!codec_data || (len = map.size) < 28) {
2857 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2858 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2861 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
2864 gst_buffer_copy_region ((GstBuffer *) codec_data, 0, 8, len);
2866 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2868 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2870 /* does not look good, but perhaps some trailing unneeded stuff */
2871 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2873 if (format == GST_QT_MUX_FORMAT_QT)
2874 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2876 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2877 /* set some more info */
2878 gst_buffer_map (codec_config, &map, GST_MAP_READ);
2879 entry.bytes_per_sample = 2;
2880 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
2881 gst_buffer_unmap (codec_config, &map);
2882 gst_buffer_unref (codec_config);
2888 /* ok, set the pad info accordingly */
2889 qtpad->fourcc = entry.fourcc;
2890 qtpad->sample_size = constant_size;
2891 atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2892 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2893 ext_atom, constant_size);
2895 gst_object_unref (qtmux);
2901 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2902 GST_PAD_NAME (pad), caps);
2903 gst_object_unref (qtmux);
2906 refuse_renegotiation:
2908 GST_WARNING_OBJECT (qtmux,
2909 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2910 GST_PAD_NAME (pad), caps);
2911 gst_object_unref (qtmux);
2916 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2918 adjust_rate (guint64 rate)
2923 while (rate >= 10000)
2929 return (guint32) rate;
2933 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2935 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2936 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2937 GstQTPad *qtpad = NULL;
2938 GstStructure *structure;
2939 const gchar *mimetype;
2940 gint width, height, depth = -1;
2941 gint framerate_num, framerate_den;
2943 const GValue *value = NULL;
2944 const GstBuffer *codec_data = NULL;
2945 VisualSampleEntry entry = { 0, };
2946 GstQTMuxFormat format;
2947 AtomInfo *ext_atom = NULL;
2948 GList *ext_atom_list = NULL;
2949 gboolean sync = FALSE;
2950 int par_num, par_den;
2952 /* find stream data */
2953 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2956 qtpad->prepare_buf_func = NULL;
2958 /* does not go well to renegotiate stream mid-way, unless
2959 * the old caps are a subset of the new one (this means upstream
2960 * added more info to the caps, as both should be 'fixed' caps) */
2961 if (qtpad->fourcc) {
2962 GstCaps *current_caps;
2964 current_caps = gst_pad_get_current_caps (pad);
2965 g_assert (caps != NULL);
2967 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2968 gst_caps_unref (current_caps);
2969 goto refuse_renegotiation;
2971 GST_DEBUG_OBJECT (qtmux,
2972 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2973 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2974 gst_caps_unref (current_caps);
2977 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2978 GST_DEBUG_PAD_NAME (pad), caps);
2980 format = qtmux_klass->format;
2981 structure = gst_caps_get_structure (caps, 0);
2982 mimetype = gst_structure_get_name (structure);
2984 /* required parts */
2985 if (!gst_structure_get_int (structure, "width", &width) ||
2986 !gst_structure_get_int (structure, "height", &height))
2991 /* works as a default timebase */
2992 framerate_num = 10000;
2994 gst_structure_get_fraction (structure, "framerate", &framerate_num,
2996 gst_structure_get_int (structure, "depth", &depth);
2997 value = gst_structure_get_value (structure, "codec_data");
2999 codec_data = gst_value_get_buffer (value);
3003 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
3006 qtpad->is_out_of_order = FALSE;
3008 /* bring frame numerator into a range that ensures both reasonable resolution
3009 * as well as a fair duration */
3010 rate = qtmux->trak_timescale ?
3011 qtmux->trak_timescale : adjust_rate (framerate_num);
3012 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
3015 /* set common properties */
3016 entry.width = width;
3017 entry.height = height;
3018 entry.par_n = par_num;
3019 entry.par_d = par_den;
3020 /* should be OK according to qt and iso spec, override if really needed */
3021 entry.color_table_id = -1;
3022 entry.frame_count = 1;
3025 /* sync entries by default */
3028 /* now map onto a fourcc, and some extra properties */
3029 if (strcmp (mimetype, "video/x-raw") == 0) {
3030 const gchar *format;
3032 const GstVideoFormatInfo *vinfo;
3034 format = gst_structure_get_string (structure, "format");
3035 fmt = gst_video_format_from_string (format);
3036 vinfo = gst_video_format_get_info (fmt);
3039 case GST_VIDEO_FORMAT_UYVY:
3042 entry.fourcc = FOURCC_2vuy;
3043 entry.depth = depth;
3047 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
3048 entry.fourcc = FOURCC_raw_;
3049 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
3054 } else if (strcmp (mimetype, "video/x-h263") == 0) {
3056 if (format == GST_QT_MUX_FORMAT_QT)
3057 entry.fourcc = FOURCC_h263;
3059 entry.fourcc = FOURCC_s263;
3060 ext_atom = build_h263_extension ();
3061 if (ext_atom != NULL)
3062 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3063 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
3064 strcmp (mimetype, "video/mpeg") == 0) {
3067 if (strcmp (mimetype, "video/x-divx") == 0) {
3068 gst_structure_get_int (structure, "divxversion", &version);
3069 version = version == 5 ? 1 : 0;
3071 gst_structure_get_int (structure, "mpegversion", &version);
3072 version = version == 4 ? 1 : 0;
3075 entry.fourcc = FOURCC_mp4v;
3077 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
3078 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
3079 qtpad->max_bitrate);
3080 if (ext_atom != NULL)
3081 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3083 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
3084 "output might not play in Apple QuickTime (try global-headers?)");
3086 } else if (strcmp (mimetype, "video/x-h264") == 0) {
3087 /* check if we accept these caps */
3088 if (gst_structure_has_field (structure, "stream-format")) {
3089 const gchar *format;
3090 const gchar *alignment;
3092 format = gst_structure_get_string (structure, "stream-format");
3093 alignment = gst_structure_get_string (structure, "alignment");
3095 if (strcmp (format, "avc") != 0 || alignment == NULL ||
3096 strcmp (alignment, "au") != 0) {
3097 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
3098 "avc format with AU aligned samples");
3102 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
3107 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
3111 entry.fourcc = FOURCC_avc1;
3112 if (qtpad->avg_bitrate == 0) {
3113 gint avg_bitrate = 0;
3114 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
3115 qtpad->avg_bitrate = avg_bitrate;
3117 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
3118 if (ext_atom != NULL)
3119 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3120 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
3121 if (ext_atom != NULL)
3122 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3123 } else if (strcmp (mimetype, "video/x-svq") == 0) {
3125 const GstBuffer *seqh = NULL;
3126 const GValue *seqh_value;
3129 gst_structure_get_int (structure, "svqversion", &version);
3131 entry.fourcc = FOURCC_SVQ3;
3135 seqh_value = gst_structure_get_value (structure, "seqh");
3137 seqh = gst_value_get_buffer (seqh_value);
3138 ext_atom = build_SMI_atom (seqh);
3140 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3143 /* we need to add the gamma anyway because quicktime might crash
3144 * when it doesn't find it */
3145 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
3146 /* it seems that using 0 here makes it ignored */
3149 ext_atom = build_gama_atom (gamma);
3151 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3153 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
3154 "a bug at http://bugzilla.gnome.org", version);
3156 } else if (strcmp (mimetype, "video/x-dv") == 0) {
3158 gboolean pal = TRUE;
3161 if (framerate_num != 25 || framerate_den != 1)
3163 gst_structure_get_int (structure, "dvversion", &version);
3164 /* fall back to typical one */
3170 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
3172 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
3176 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
3178 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
3181 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
3184 } else if (strcmp (mimetype, "image/jpeg") == 0) {
3185 entry.fourcc = FOURCC_jpeg;
3187 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
3188 strcmp (mimetype, "image/x-jpc") == 0) {
3189 const gchar *colorspace;
3190 const GValue *cmap_array;
3191 const GValue *cdef_array;
3195 if (strcmp (mimetype, "image/x-jpc") == 0) {
3196 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
3199 gst_structure_get_int (structure, "num-components", &ncomp);
3200 gst_structure_get_int (structure, "fields", &fields);
3201 cmap_array = gst_structure_get_value (structure, "component-map");
3202 cdef_array = gst_structure_get_value (structure, "channel-definitions");
3205 entry.fourcc = FOURCC_mjp2;
3208 colorspace = gst_structure_get_string (structure, "colorspace");
3211 build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
3212 cmap_array, cdef_array)) != NULL) {
3213 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3215 ext_atom = build_fiel_extension (fields);
3217 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3219 ext_atom = build_jp2x_extension (codec_data);
3221 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3223 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3226 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3227 entry.fourcc = FOURCC_VP80;
3229 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3230 entry.fourcc = FOURCC_drac;
3231 qtpad->have_dts = TRUE;
3232 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3235 gst_structure_get_uint (structure, "format", &fourcc);
3236 entry.fourcc = fourcc;
3237 qtpad->have_dts = TRUE;
3238 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3241 gst_structure_get_uint (structure, "format", &fourcc);
3242 entry.fourcc = fourcc;
3243 qtpad->have_dts = TRUE;
3249 /* ok, set the pad info accordingly */
3250 qtpad->fourcc = entry.fourcc;
3252 atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3255 gst_object_unref (qtmux);
3261 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3262 GST_PAD_NAME (pad), caps);
3263 gst_object_unref (qtmux);
3266 refuse_renegotiation:
3268 GST_WARNING_OBJECT (qtmux,
3269 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
3271 gst_object_unref (qtmux);
3277 gst_qt_mux_sink_event (GstCollectPads2 * pads, GstCollectData2 * data,
3278 GstEvent * event, gpointer user_data)
3281 guint32 avg_bitrate = 0, max_bitrate = 0;
3282 GstPad *pad = data->pad;
3283 gboolean ret = FALSE;
3285 qtmux = GST_QT_MUX_CAST (user_data);
3286 switch (GST_EVENT_TYPE (event)) {
3287 case GST_EVENT_CAPS:
3290 GstQTPad *collect_pad;
3292 gst_event_parse_caps (event, &caps);
3294 /* find stream data */
3295 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
3296 g_assert (collect_pad);
3297 g_assert (collect_pad->set_caps);
3299 ret = collect_pad->set_caps (pad, caps);
3300 gst_event_unref (event);
3303 case GST_EVENT_TAG:{
3305 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3306 GstTagMergeMode mode;
3308 GST_OBJECT_LOCK (qtmux);
3309 mode = gst_tag_setter_get_tag_merge_mode (setter);
3311 gst_event_parse_tag (event, &list);
3312 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
3313 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
3315 gst_tag_setter_merge_tags (setter, list, mode);
3316 GST_OBJECT_UNLOCK (qtmux);
3318 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3319 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3320 GstQTPad *qtpad = gst_pad_get_element_private (pad);
3323 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3324 qtpad->avg_bitrate = avg_bitrate;
3325 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3326 qtpad->max_bitrate = max_bitrate;
3329 gst_event_unref (event);
3334 ret = gst_pad_event_default (data->pad, GST_OBJECT (qtmux), event);
3337 case GST_EVENT_SEGMENT:
3338 gst_event_unref (event);
3347 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3349 GstQTMux *mux = GST_QT_MUX_CAST (element);
3352 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3354 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3355 GstQTPad *qtpad = (GstQTPad *) walk->data;
3356 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3357 if (qtpad->collect.pad == pad) {
3358 /* this is it, remove */
3359 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3360 gst_element_remove_pad (element, pad);
3365 gst_collect_pads2_remove_pad (mux->collect, pad);
3369 gst_qt_mux_request_new_pad (GstElement * element,
3370 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
3372 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3373 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3374 GstQTPad *collect_pad;
3380 if (templ->direction != GST_PAD_SINK)
3381 goto wrong_direction;
3383 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3386 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
3388 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
3389 name = g_strdup (req_name);
3391 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
3393 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
3395 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
3396 name = g_strdup (req_name);
3398 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
3401 goto wrong_template;
3403 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3405 /* create pad and add to collections */
3406 newpad = gst_pad_new_from_template (templ, name);
3408 collect_pad = (GstQTPad *)
3409 gst_collect_pads2_add_pad_full (qtmux->collect, newpad, sizeof (GstQTPad),
3410 (GstCollectData2DestroyNotify) (gst_qt_mux_pad_reset), TRUE);
3412 gst_qt_mux_pad_reset (collect_pad);
3413 collect_pad->trak = atom_trak_new (qtmux->context);
3414 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3416 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3418 /* set up pad functions */
3420 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps);
3422 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps);
3424 gst_pad_set_active (newpad, TRUE);
3425 gst_element_add_pad (element, newpad);
3432 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3437 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3442 GST_WARNING_OBJECT (qtmux, "This is not our template!");
3448 gst_qt_mux_get_property (GObject * object,
3449 guint prop_id, GValue * value, GParamSpec * pspec)
3451 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3453 GST_OBJECT_LOCK (qtmux);
3455 case PROP_MOVIE_TIMESCALE:
3456 g_value_set_uint (value, qtmux->timescale);
3458 case PROP_TRAK_TIMESCALE:
3459 g_value_set_uint (value, qtmux->trak_timescale);
3462 g_value_set_boolean (value, qtmux->guess_pts);
3464 case PROP_DTS_METHOD:
3465 g_value_set_enum (value, qtmux->dts_method);
3467 case PROP_FAST_START:
3468 g_value_set_boolean (value, qtmux->fast_start);
3470 case PROP_FAST_START_TEMP_FILE:
3471 g_value_set_string (value, qtmux->fast_start_file_path);
3473 case PROP_MOOV_RECOV_FILE:
3474 g_value_set_string (value, qtmux->moov_recov_file_path);
3476 case PROP_FRAGMENT_DURATION:
3477 g_value_set_uint (value, qtmux->fragment_duration);
3479 case PROP_STREAMABLE:
3480 g_value_set_boolean (value, qtmux->streamable);
3483 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3486 GST_OBJECT_UNLOCK (qtmux);
3490 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3494 g_free (qtmux->fast_start_file_path);
3495 qtmux->fast_start_file_path = NULL;
3497 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3498 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3503 gst_qt_mux_set_property (GObject * object,
3504 guint prop_id, const GValue * value, GParamSpec * pspec)
3506 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3508 GST_OBJECT_LOCK (qtmux);
3510 case PROP_MOVIE_TIMESCALE:
3511 qtmux->timescale = g_value_get_uint (value);
3513 case PROP_TRAK_TIMESCALE:
3514 qtmux->trak_timescale = g_value_get_uint (value);
3517 qtmux->guess_pts = g_value_get_boolean (value);
3519 case PROP_DTS_METHOD:
3520 qtmux->dts_method = g_value_get_enum (value);
3522 case PROP_FAST_START:
3523 qtmux->fast_start = g_value_get_boolean (value);
3525 case PROP_FAST_START_TEMP_FILE:
3526 g_free (qtmux->fast_start_file_path);
3527 qtmux->fast_start_file_path = g_value_dup_string (value);
3528 /* NULL means to generate a random one */
3529 if (!qtmux->fast_start_file_path) {
3530 gst_qt_mux_generate_fast_start_file_path (qtmux);
3533 case PROP_MOOV_RECOV_FILE:
3534 g_free (qtmux->moov_recov_file_path);
3535 qtmux->moov_recov_file_path = g_value_dup_string (value);
3537 case PROP_FRAGMENT_DURATION:
3538 qtmux->fragment_duration = g_value_get_uint (value);
3540 case PROP_STREAMABLE:
3541 qtmux->streamable = g_value_get_boolean (value);
3544 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3547 GST_OBJECT_UNLOCK (qtmux);
3550 static GstStateChangeReturn
3551 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3553 GstStateChangeReturn ret;
3554 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3556 switch (transition) {
3557 case GST_STATE_CHANGE_NULL_TO_READY:
3559 case GST_STATE_CHANGE_READY_TO_PAUSED:
3560 gst_collect_pads2_start (qtmux->collect);
3561 qtmux->state = GST_QT_MUX_STATE_STARTED;
3563 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3565 case GST_STATE_CHANGE_PAUSED_TO_READY:
3566 gst_collect_pads2_stop (qtmux->collect);
3572 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3574 switch (transition) {
3575 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3577 case GST_STATE_CHANGE_PAUSED_TO_READY:
3578 gst_qt_mux_reset (qtmux, TRUE);
3580 case GST_STATE_CHANGE_READY_TO_NULL:
3590 gst_qt_mux_register (GstPlugin * plugin)
3592 GTypeInfo typeinfo = {
3593 sizeof (GstQTMuxClass),
3594 (GBaseInitFunc) gst_qt_mux_base_init,
3596 (GClassInitFunc) gst_qt_mux_class_init,
3601 (GInstanceInitFunc) gst_qt_mux_init,
3603 static const GInterfaceInfo tag_setter_info = {
3606 static const GInterfaceInfo tag_xmp_writer_info = {
3610 GstQTMuxFormat format;
3611 GstQTMuxClassParams *params;
3614 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3616 GST_LOG ("Registering muxers");
3619 GstQTMuxFormatProp *prop;
3621 prop = &gst_qt_mux_format_list[i];
3622 format = prop->format;
3623 if (format == GST_QT_MUX_FORMAT_NONE)
3626 /* create a cache for these properties */
3627 params = g_new0 (GstQTMuxClassParams, 1);
3628 params->prop = prop;
3629 params->src_caps = gst_static_caps_get (&prop->src_caps);
3630 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3631 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3633 /* create the type now */
3634 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3636 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3637 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3638 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3639 &tag_xmp_writer_info);
3641 if (!gst_element_register (plugin, prop->name, prop->rank, type))
3647 GST_LOG ("Finished registering muxers");
3649 /* FIXME: ideally classification tag should be added and
3650 registered in gstreamer core gsttaglist
3653 GST_LOG ("Registering tags");
3655 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3656 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3657 gst_tag_merge_use_first);
3659 GST_LOG ("Finished registering tags");