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_details_simple (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_take_memory (buf, -1,
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 "
1659 /* let downstream know we think in BYTES and expect to do seeking later on */
1660 gst_segment_init (&segment, GST_FORMAT_BYTES);
1661 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1663 /* initialize our moov recovery file */
1664 GST_OBJECT_LOCK (qtmux);
1665 if (qtmux->moov_recov_file_path) {
1666 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1667 qtmux->moov_recov_file_path);
1668 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1669 if (qtmux->moov_recov_file == NULL) {
1670 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1671 qtmux->moov_recov_file_path);
1674 gboolean fail = FALSE;
1675 AtomFTYP *ftyp = NULL;
1676 GstBuffer *prefix = NULL;
1678 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1680 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1681 qtmux->moov, qtmux->timescale,
1682 g_slist_length (qtmux->sinkpads))) {
1683 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1688 atom_ftyp_free (ftyp);
1690 gst_buffer_unref (prefix);
1692 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1693 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1694 GstQTPad *qpad = (GstQTPad *) cdata;
1695 /* write info for each stream */
1696 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1698 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1704 fclose (qtmux->moov_recov_file);
1705 qtmux->moov_recov_file = NULL;
1706 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1707 "recover file, moov recovery won't work");
1711 GST_OBJECT_UNLOCK (qtmux);
1714 * send mdat header if already needed, and mark position for later update.
1715 * We don't send ftyp now if we are on fast start mode, because we can
1716 * better fine tune using the information we gather to create the whole moov
1719 if (qtmux->fast_start) {
1720 GST_OBJECT_LOCK (qtmux);
1721 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1722 if (!qtmux->fast_start_file)
1724 GST_OBJECT_UNLOCK (qtmux);
1726 /* send a dummy buffer for preroll */
1727 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1728 if (ret != GST_FLOW_OK)
1732 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1733 if (ret != GST_FLOW_OK) {
1737 /* well, it's moov pos if fragmented ... */
1738 qtmux->mdat_pos = qtmux->header_size;
1740 if (qtmux->fragment_duration) {
1741 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1742 qtmux->fragment_duration);
1743 /* also used as snapshot marker to indicate fragmented file */
1744 qtmux->fragment_sequence = 1;
1745 /* prepare moov and/or tags */
1746 gst_qt_mux_configure_moov (qtmux, NULL);
1747 gst_qt_mux_setup_metadata (qtmux);
1748 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1749 if (ret != GST_FLOW_OK)
1753 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1754 if (ret != GST_FLOW_OK)
1757 if (!qtmux->streamable)
1758 qtmux->mfra = atom_mfra_new (qtmux->context);
1760 /* extended to ensure some spare space */
1761 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1771 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1772 (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1774 GST_OBJECT_UNLOCK (qtmux);
1775 return GST_FLOW_ERROR;
1779 static GstFlowReturn
1780 gst_qt_mux_stop_file (GstQTMux * qtmux)
1782 gboolean ret = GST_FLOW_OK;
1783 guint64 offset = 0, size = 0;
1785 gboolean large_file;
1787 GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1789 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1791 /* pushing last buffers for each pad */
1792 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1793 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1794 GstQTPad *qtpad = (GstQTPad *) cdata;
1796 /* avoid add_buffer complaining if not negotiated
1797 * in which case no buffers either, so skipping */
1798 if (!qtpad->fourcc) {
1799 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
1800 GST_PAD_NAME (qtpad->collect.pad));
1804 /* send last buffer; also flushes possibly queued buffers/ts */
1805 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1806 GST_PAD_NAME (qtpad->collect.pad));
1807 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1808 if (ret != GST_FLOW_OK) {
1809 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1810 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1811 gst_flow_get_name (ret));
1814 /* having flushed above, can check for buffers now */
1815 if (!GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
1816 GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1817 GST_PAD_NAME (qtpad->collect.pad));
1821 /* determine max stream duration */
1822 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1823 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1824 qtpad->last_dts > first_ts)) {
1825 first_ts = qtpad->last_dts;
1828 /* update average bitrate of streams if needed */
1830 guint32 avgbitrate = 0;
1831 guint32 maxbitrate = qtpad->max_bitrate;
1833 if (qtpad->avg_bitrate)
1834 avgbitrate = qtpad->avg_bitrate;
1835 else if (qtpad->total_duration > 0)
1836 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
1837 8 * GST_SECOND, qtpad->total_duration);
1839 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
1843 if (qtmux->fragment_sequence) {
1847 guint8 *data = NULL;
1851 GST_DEBUG_OBJECT (qtmux, "adding mfra");
1852 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1853 goto serialize_error;
1854 buf = _gst_buffer_new_take_data (data, offset);
1855 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1856 if (ret != GST_FLOW_OK)
1859 /* must have been streamable; no need to write duration */
1860 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1864 timescale = qtmux->timescale;
1865 /* only mvex duration is updated,
1866 * mvhd should be consistent with empty moov
1867 * (but TODO maybe some clients do not handle that well ?) */
1868 qtmux->moov->mvex.mehd.fragment_duration =
1869 gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1870 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1871 GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1872 /* seek and rewrite the header */
1873 gst_segment_init (&segment, GST_FORMAT_BYTES);
1874 segment.start = qtmux->mdat_pos;
1875 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1876 /* no need to seek back */
1877 return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1880 gst_qt_mux_configure_moov (qtmux, ×cale);
1882 /* check for late streams */
1883 first_ts = GST_CLOCK_TIME_NONE;
1884 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1885 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1886 GstQTPad *qtpad = (GstQTPad *) cdata;
1888 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1889 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1890 qtpad->first_ts < first_ts)) {
1891 first_ts = qtpad->first_ts;
1894 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1895 GST_TIME_ARGS (first_ts));
1896 /* add EDTSs for late streams */
1897 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1898 GstCollectData2 *cdata = (GstCollectData2 *) walk->data;
1899 GstQTPad *qtpad = (GstQTPad *) cdata;
1903 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1904 qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1905 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1906 GST_PAD_NAME (qtpad->collect.pad),
1907 GST_TIME_ARGS (qtpad->first_ts - first_ts));
1908 lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1909 timescale, GST_SECOND);
1910 duration = qtpad->trak->tkhd.duration;
1911 atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1912 (guint32) (1 * 65536.0));
1913 atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1914 (guint32) (1 * 65536.0));
1916 /* need to add the empty time to the trak duration */
1917 qtpad->trak->tkhd.duration += lateness;
1921 /* tags into file metadata */
1922 gst_qt_mux_setup_metadata (qtmux);
1924 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1925 /* if faststart, update the offset of the atoms in the movie with the offset
1926 * that the movie headers before mdat will cause.
1927 * Also, send the ftyp */
1928 if (qtmux->fast_start_file) {
1929 GstFlowReturn flow_ret;
1932 flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1933 if (flow_ret != GST_FLOW_OK) {
1936 /* copy into NULL to obtain size */
1937 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1938 goto serialize_error;
1939 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1941 offset += qtmux->header_size + (large_file ? 16 : 8);
1943 /* sum up with the extra atoms size */
1944 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1945 if (ret != GST_FLOW_OK)
1948 offset = qtmux->header_size;
1950 atom_moov_chunks_add_offset (qtmux->moov, offset);
1953 /* note: as of this point, we no longer care about tracking written data size,
1954 * since there is no more use for it anyway */
1955 ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1956 if (ret != GST_FLOW_OK)
1960 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1961 if (ret != GST_FLOW_OK)
1964 /* if needed, send mdat atom and move buffered data into it */
1965 if (qtmux->fast_start_file) {
1966 /* mdat_size = accumulated (buffered data) */
1967 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1969 if (ret != GST_FLOW_OK)
1971 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1972 if (ret != GST_FLOW_OK)
1975 /* mdat needs update iff not using faststart */
1976 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1977 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1978 qtmux->mdat_size, NULL);
1979 /* note; no seeking back to the end of file is done,
1980 * since we no longer write anything anyway */
1988 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1989 ("Failed to serialize moov"));
1990 return GST_FLOW_ERROR;
1994 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1995 return GST_FLOW_ERROR;
1999 static GstFlowReturn
2000 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2001 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2002 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2004 GstFlowReturn ret = GST_FLOW_OK;
2006 /* setup if needed */
2007 if (G_UNLIKELY (!pad->traf || force))
2011 /* flush pad fragment if threshold reached,
2012 * or at new keyframe if we should be minding those in the first place */
2013 if (G_UNLIKELY (force || (sync && pad->sync) ||
2014 pad->fragment_duration < (gint64) delta)) {
2016 guint64 size = 0, offset = 0;
2017 guint8 *data = NULL;
2019 guint i, total_size;
2021 /* now we know where moof ends up, update offset in tfra */
2023 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2025 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2026 /* takes ownership */
2027 atom_moof_add_traf (moof, pad->traf);
2029 atom_moof_copy_data (moof, &data, &size, &offset);
2030 buffer = _gst_buffer_new_take_data (data, offset);
2031 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2032 gst_buffer_get_size (buffer));
2033 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2035 /* and actual data */
2037 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2039 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2042 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2043 atom_array_get_len (&pad->fragment_buffers), total_size);
2044 if (ret == GST_FLOW_OK)
2045 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2047 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2048 if (G_LIKELY (ret == GST_FLOW_OK))
2049 ret = gst_qt_mux_send_buffer (qtmux,
2050 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2053 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2056 atom_array_clear (&pad->fragment_buffers);
2057 atom_moof_free (moof);
2058 qtmux->fragment_sequence++;
2063 if (G_UNLIKELY (!pad->traf)) {
2064 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2065 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2066 atom_array_init (&pad->fragment_buffers, 512);
2067 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2068 atom_trak_get_timescale (pad->trak), 1000);
2070 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2071 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2072 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2076 /* add buffer and metadata */
2077 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2079 atom_array_append (&pad->fragment_buffers, buf, 256);
2080 pad->fragment_duration -= delta;
2083 guint32 sn = atom_traf_get_sample_num (pad->traf);
2085 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2086 atom_tfra_add_entry (pad->tfra, dts, sn);
2089 if (G_UNLIKELY (force))
2095 /* sigh, tiny list helpers to re-order stuff */
2097 gst_qt_mux_push_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2101 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2102 if (ts > pad->ts_entries[i])
2105 memmove (&pad->ts_entries[i + 1], &pad->ts_entries[i],
2106 sizeof (GstClockTime) * (pad->ts_n_entries - i));
2107 pad->ts_entries[i] = ts;
2108 pad->ts_n_entries++;
2112 check_and_subtract_ts (GstQTMux * qtmux, GstClockTime * ts_a, GstClockTime ts_b)
2114 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (*ts_a))) {
2115 if (G_LIKELY (*ts_a > ts_b)) {
2119 GST_WARNING_OBJECT (qtmux, "Subtraction would result in negative value, "
2120 "using 0 as result");
2125 /* subtract ts from all buffers enqueued on the pad */
2127 gst_qt_mux_subtract_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2131 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2132 check_and_subtract_ts (qtmux, &pad->ts_entries[i], ts);
2134 for (i = 0; i < G_N_ELEMENTS (pad->buf_entries); i++) {
2135 if (pad->buf_entries[i]) {
2136 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (pad->buf_entries[i]),
2138 check_and_subtract_ts (qtmux,
2139 &GST_BUFFER_OFFSET_END (pad->buf_entries[i]), ts);
2144 /* takes ownership of @buf */
2146 gst_qt_mux_get_asc_buffer_ts (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2148 const gint wrap = G_N_ELEMENTS (pad->buf_entries);
2151 /* store buffer and ts, latter ordered */
2153 pad->buf_entries[pad->buf_tail++] = buf;
2154 pad->buf_tail %= wrap;
2155 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (buf));
2158 if (pad->ts_n_entries && (!buf || pad->ts_n_entries >= QTMUX_NO_OF_TS)) {
2159 ts = pad->ts_entries[--pad->ts_n_entries];
2160 buf = pad->buf_entries[pad->buf_head];
2161 pad->buf_entries[pad->buf_head++] = NULL;
2162 pad->buf_head %= wrap;
2163 buf = gst_buffer_make_writable (buf);
2164 /* track original ts (= pts ?) for later */
2165 GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_TIMESTAMP (buf);
2166 GST_BUFFER_TIMESTAMP (buf) = ts;
2167 GST_DEBUG_OBJECT (qtmux, "next buffer uses reordered ts %" GST_TIME_FORMAT,
2168 GST_TIME_ARGS (ts));
2177 * Here we push the buffer and update the tables in the track atoms
2179 static GstFlowReturn
2180 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2182 GstBuffer *last_buf = NULL;
2183 GstClockTime duration;
2184 guint nsamples, sample_size;
2185 guint64 chunk_offset;
2186 gint64 last_dts, scaled_duration;
2187 gint64 pts_offset = 0;
2188 gboolean sync = FALSE, do_pts = FALSE;
2189 gboolean drain = (buf == NULL);
2190 GstFlowReturn ret = GST_FLOW_OK;
2193 goto not_negotiated;
2195 /* if this pad has a prepare function, call it */
2196 if (pad->prepare_buf_func != NULL) {
2197 buf = pad->prepare_buf_func (pad, buf, qtmux);
2200 if (G_LIKELY (buf != NULL && GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
2201 pad->first_ts != 0)) {
2202 buf = gst_buffer_make_writable (buf);
2203 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2205 /* when we obtain the first_ts we subtract from all stored buffers we have,
2206 * after that we can subtract on input */
2209 last_buf = pad->last_buf;
2210 if (qtmux->dts_method == DTS_METHOD_REORDER) {
2211 buf = gst_qt_mux_get_asc_buffer_ts (qtmux, pad, buf);
2212 if (!buf && !last_buf) {
2213 GST_DEBUG_OBJECT (qtmux, "no reordered buffer");
2218 if (last_buf == NULL) {
2219 #ifndef GST_DISABLE_GST_DEBUG
2221 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
2222 "received NULL buffer, doing nothing",
2223 GST_PAD_NAME (pad->collect.pad));
2225 GST_LOG_OBJECT (qtmux,
2226 "Pad %s has no previous buffer stored, storing now",
2227 GST_PAD_NAME (pad->collect.pad));
2230 pad->last_buf = buf;
2233 gst_buffer_ref (last_buf);
2235 /* nasty heuristic mess to guestimate dealing with DTS/PTS,
2236 * while also trying to stay close to input ts to preserve sync,
2237 * so in DTS_METHOD_DD:
2238 * - prefer using input ts where possible
2239 * - if those detected out-of-order (*), mark as out-of-order
2240 * - if in out-of-order, then
2241 * - if duration available, use that as delta
2242 * Also mind to preserve sync between streams, and adding
2243 * durations might drift, so try to resync when we expect
2244 * input ts == (sum of durations), which is at some keyframe input frame.
2245 * - if no duration available, we are actually in serious trouble and need
2246 * to hack around that, so we fail.
2247 * To remedy failure, alternatively, in DTS_METHOD_REORDER:
2248 * - collect some buffers and re-order timestamp,
2249 * then process the oldest buffer with smallest timestamps.
2250 * This should typically compensate for some codec's handywork with ts.
2251 * ... but in case this makes ts end up where not expected, in DTS_METHOD_ASC:
2252 * - keep each ts with its buffer and still keep a list of most recent X ts,
2253 * use the (ascending) minimum of those as DTS (and the difference as ts delta),
2254 * and use this DTS as a basis to obtain a (positive) CTS offset.
2255 * This should yield exact PTS == buffer ts, but it seems not all players
2256 * out there are aware of ctts pts ...
2258 * 0.11 Phew, can we (pretty) please please sort out DTS/PTS on buffers ...
2260 if (G_LIKELY (buf) && !pad->is_out_of_order) {
2261 if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (last_buf) &&
2262 GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
2263 if ((GST_BUFFER_TIMESTAMP (buf) < GST_BUFFER_TIMESTAMP (last_buf))) {
2264 GST_DEBUG_OBJECT (qtmux, "detected out-of-order input");
2265 pad->is_out_of_order = TRUE;
2268 /* this is pretty bad */
2269 GST_WARNING_OBJECT (qtmux, "missing input timestamp");
2270 /* fall back to durations */
2271 pad->is_out_of_order = TRUE;
2275 /* would have to be some unusual input, but not impossible */
2276 if (G_UNLIKELY (qtmux->dts_method == DTS_METHOD_REORDER &&
2277 pad->is_out_of_order)) {
2281 /* if this is the first buffer, store the timestamp */
2282 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2283 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (last_buf))) {
2284 pad->first_ts = GST_BUFFER_TIMESTAMP (last_buf);
2286 GST_DEBUG_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2287 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2290 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2291 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2292 GST_TIME_ARGS (pad->first_ts));
2294 gst_qt_mux_subtract_ts (qtmux, pad, pad->first_ts);
2296 GST_BUFFER_TIMESTAMP (last_buf) = 0;
2297 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (last_buf),
2300 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2301 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (buf),
2306 /* fall back to duration if last buffer or
2307 * out-of-order (determined previously), otherwise use input ts */
2309 (pad->is_out_of_order && qtmux->dts_method == DTS_METHOD_DD)) {
2310 if (!GST_BUFFER_DURATION_IS_VALID (last_buf)) {
2311 /* be forgiving for some possibly last upstream flushed buffer */
2314 GST_WARNING_OBJECT (qtmux, "no duration for last buffer");
2315 /* iso spec recommends some small value, try 0 */
2318 duration = GST_BUFFER_DURATION (last_buf);
2319 /* avoid drift in sum timestamps,
2320 * so use input timestamp for suitable keyframe */
2321 if (buf && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) &&
2322 GST_BUFFER_TIMESTAMP (buf) >= pad->last_dts) {
2323 GST_DEBUG_OBJECT (qtmux, "resyncing out-of-order input to ts; "
2324 "replacing %" GST_TIME_FORMAT " by %" GST_TIME_FORMAT,
2325 GST_TIME_ARGS (pad->last_dts + duration),
2326 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2327 duration = GST_BUFFER_TIMESTAMP (buf) - pad->last_dts;
2330 } else if (qtmux->dts_method != DTS_METHOD_ASC) {
2331 duration = GST_BUFFER_TIMESTAMP (buf) - GST_BUFFER_TIMESTAMP (last_buf);
2335 g_assert (qtmux->dts_method == DTS_METHOD_ASC);
2336 if (!qtmux->guess_pts)
2339 /* add timestamp to queue; keeps in descending order */
2340 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (last_buf));
2341 /* chuck out smallest/last one if we have enough */
2342 if (G_LIKELY (pad->ts_n_entries > QTMUX_NO_OF_TS))
2343 pad->ts_n_entries--;
2344 /* peek the now smallest timestamp */
2345 ts = pad->ts_entries[pad->ts_n_entries - 1];
2346 /* these tails are expected to be (strictly) ascending with
2347 * large enough history */
2348 GST_DEBUG_OBJECT (qtmux, "ASC method; base timestamp %" GST_TIME_FORMAT,
2349 GST_TIME_ARGS (ts));
2350 if (ts >= pad->last_dts) {
2351 duration = ts - pad->last_dts;
2353 /* fallback to previous value, negative ct offset might handle */
2354 GST_WARNING_OBJECT (qtmux, "unexpected decrease in timestamp");
2357 /* arrange for small non-zero duration/delta << expected frame time */
2358 ts = gst_util_uint64_scale (10, GST_SECOND,
2359 atom_trak_get_timescale (pad->trak));
2360 duration = MAX (duration, ts);
2363 /* for computing the avg bitrate */
2364 if (G_LIKELY (last_buf)) {
2365 pad->total_bytes += gst_buffer_get_size (last_buf);
2366 pad->total_duration += duration;
2369 gst_buffer_replace (&pad->last_buf, buf);
2371 last_dts = gst_util_uint64_scale_round (pad->last_dts,
2372 atom_trak_get_timescale (pad->trak), GST_SECOND);
2374 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2375 if (pad->sample_size && !qtmux->fragment_sequence) {
2376 /* Constant size packets: usually raw audio (with many samples per
2377 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2379 sample_size = pad->sample_size;
2380 if (gst_buffer_get_size (last_buf) % sample_size != 0)
2381 goto fragmented_sample;
2382 /* note: qt raw audio storage warps it implicitly into a timewise
2383 * perfect stream, discarding buffer times */
2384 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2385 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2386 atom_trak_get_timescale (pad->trak), GST_SECOND);
2388 nsamples = gst_buffer_get_size (last_buf) / sample_size;
2390 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2392 /* timescale = samplerate */
2393 scaled_duration = 1;
2394 pad->last_dts += duration * nsamples;
2397 sample_size = gst_buffer_get_size (last_buf);
2398 if (pad->have_dts) {
2400 pad->last_dts = GST_BUFFER_OFFSET_END (last_buf);
2401 if ((gint64) (pad->last_dts) < 0) {
2402 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2403 atom_trak_get_timescale (pad->trak), GST_SECOND);
2405 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2406 atom_trak_get_timescale (pad->trak), GST_SECOND);
2408 scaled_duration = scaled_dts - last_dts;
2409 last_dts = scaled_dts;
2411 /* first convert intended timestamp (in GstClockTime resolution) to
2412 * trak timescale, then derive delta;
2413 * this ensures sums of (scale)delta add up to converted timestamp,
2414 * which only deviates at most 1/scale from timestamp itself */
2415 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2416 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2417 pad->last_dts += duration;
2420 chunk_offset = qtmux->mdat_size;
2422 GST_LOG_OBJECT (qtmux,
2423 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2424 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2425 GST_LOG_OBJECT (qtmux,
2426 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2427 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2428 nsamples, scaled_duration, sample_size, chunk_offset);
2430 /* might be a sync sample */
2432 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2433 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2434 GST_PAD_NAME (pad->collect.pad));
2438 /* optionally calculate ctts entry values
2439 * (if composition-time expected different from decoding-time) */
2440 /* really not recommended:
2441 * - decoder typically takes care of dts/pts issues
2442 * - in case of out-of-order, dts may only be determined as above
2443 * (e.g. sum of duration), which may be totally different from
2444 * buffer timestamps in case of multiple segment, non-perfect streams
2445 * (and just perhaps maybe with some luck segment_to_running_time
2446 * or segment_to_media_time might get near to it) */
2447 if ((pad->have_dts || qtmux->guess_pts)) {
2450 pts = qtmux->dts_method == DTS_METHOD_REORDER ?
2451 GST_BUFFER_OFFSET_END (last_buf) : GST_BUFFER_TIMESTAMP (last_buf);
2452 pts = gst_util_uint64_scale_round (pts,
2453 atom_trak_get_timescale (pad->trak), GST_SECOND);
2454 pts_offset = (gint64) (pts - last_dts);
2456 GST_LOG_OBJECT (qtmux, "Adding ctts entry for pad %s: %" G_GINT64_FORMAT,
2457 GST_PAD_NAME (pad->collect.pad), pts_offset);
2461 * Each buffer starts a new chunk, so we can assume the buffer
2462 * duration is the chunk duration
2464 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2465 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2466 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2467 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2468 qtmux->longest_chunk = duration;
2471 /* now we go and register this buffer/sample all over */
2472 /* note that a new chunk is started each time (not fancy but works) */
2473 if (qtmux->moov_recov_file) {
2474 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2475 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2476 do_pts, pts_offset)) {
2477 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2478 "recovery file, disabling recovery");
2479 fclose (qtmux->moov_recov_file);
2480 qtmux->moov_recov_file = NULL;
2485 gst_buffer_unref (buf);
2487 if (qtmux->fragment_sequence) {
2488 /* ensure that always sync samples are marked as such */
2489 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2490 buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2491 !pad->sync || sync, pts_offset);
2493 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2494 sample_size, chunk_offset, sync, pts_offset);
2495 ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2499 if (G_UNLIKELY (drain && qtmux->dts_method == DTS_METHOD_REORDER &&
2500 ret == GST_FLOW_OK)) {
2511 gst_buffer_unref (buf);
2512 gst_buffer_unref (last_buf);
2513 return GST_FLOW_ERROR;
2517 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2518 ("Received buffer without timestamp/duration. "
2519 "Using e.g. dts-method=reorder might help."));
2524 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2525 ("DTS method failed to re-order timestamps."));
2530 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2531 ("Selected DTS method also needs PTS enabled."));
2536 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2537 ("Audio buffer contains fragmented sample."));
2542 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2543 ("format wasn't negotiated before buffer flow on pad %s",
2544 GST_PAD_NAME (pad->collect.pad)));
2546 gst_buffer_unref (buf);
2547 return GST_FLOW_NOT_NEGOTIATED;
2551 static GstFlowReturn
2552 gst_qt_mux_handle_buffer (GstCollectPads2 * pads, GstCollectData2 * cdata,
2553 GstBuffer * buf, gpointer user_data)
2555 GstFlowReturn ret = GST_FLOW_OK;
2556 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2557 GstQTPad *best_pad = NULL;
2558 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2560 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2561 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2564 qtmux->state = GST_QT_MUX_STATE_DATA;
2567 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2568 return GST_FLOW_EOS;
2570 best_pad = (GstQTPad *) cdata;
2572 /* clipping already converted to running time */
2573 if (best_pad != NULL) {
2575 best_time = GST_BUFFER_TIMESTAMP (buf);
2576 GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2577 GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2578 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2580 ret = gst_qt_mux_stop_file (qtmux);
2581 if (ret == GST_FLOW_OK) {
2582 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2583 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2586 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2587 gst_flow_get_name (ret));
2589 qtmux->state = GST_QT_MUX_STATE_EOS;
2596 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2598 GstStructure *structure = (GstStructure *) user_data;
2599 const GValue *other = gst_structure_id_get_value (structure, field_id);
2602 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2606 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2609 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2610 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2612 return gst_structure_foreach (sub_s, check_field, sup_s);
2616 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2618 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2619 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2620 GstQTPad *qtpad = NULL;
2621 GstStructure *structure;
2622 const gchar *mimetype;
2623 gint rate, channels;
2624 const GValue *value = NULL;
2625 const GstBuffer *codec_data = NULL;
2626 GstQTMuxFormat format;
2627 AudioSampleEntry entry = { 0, };
2628 AtomInfo *ext_atom = NULL;
2629 gint constant_size = 0;
2630 const gchar *stream_format;
2632 /* find stream data */
2633 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2636 qtpad->prepare_buf_func = NULL;
2638 /* does not go well to renegotiate stream mid-way, unless
2639 * the old caps are a subset of the new one (this means upstream
2640 * added more info to the caps, as both should be 'fixed' caps) */
2641 if (qtpad->fourcc) {
2642 GstCaps *current_caps;
2644 current_caps = gst_pad_get_current_caps (pad);
2645 g_assert (caps != NULL);
2647 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2648 gst_caps_unref (current_caps);
2649 goto refuse_renegotiation;
2651 GST_DEBUG_OBJECT (qtmux,
2652 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2653 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2654 gst_caps_unref (current_caps);
2657 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2658 GST_DEBUG_PAD_NAME (pad), caps);
2660 format = qtmux_klass->format;
2661 structure = gst_caps_get_structure (caps, 0);
2662 mimetype = gst_structure_get_name (structure);
2665 if (!gst_structure_get_int (structure, "channels", &channels) ||
2666 !gst_structure_get_int (structure, "rate", &rate)) {
2671 value = gst_structure_get_value (structure, "codec_data");
2673 codec_data = gst_value_get_buffer (value);
2675 qtpad->is_out_of_order = FALSE;
2676 qtpad->have_dts = FALSE;
2678 /* set common properties */
2679 entry.sample_rate = rate;
2680 entry.channels = channels;
2682 entry.sample_size = 16;
2683 /* this is the typical compressed case */
2684 if (format == GST_QT_MUX_FORMAT_QT) {
2686 entry.compression_id = -2;
2689 /* now map onto a fourcc, and some extra properties */
2690 if (strcmp (mimetype, "audio/mpeg") == 0) {
2691 gint mpegversion = 0;
2694 gst_structure_get_int (structure, "mpegversion", &mpegversion);
2695 switch (mpegversion) {
2697 gst_structure_get_int (structure, "layer", &layer);
2701 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2702 if (format == GST_QT_MUX_FORMAT_QT)
2703 entry.fourcc = FOURCC__mp3;
2705 entry.fourcc = FOURCC_mp4a;
2707 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2708 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2709 qtpad->max_bitrate);
2711 entry.samples_per_packet = 1152;
2712 entry.bytes_per_sample = 2;
2718 /* check stream-format */
2719 stream_format = gst_structure_get_string (structure, "stream-format");
2720 if (stream_format) {
2721 if (strcmp (stream_format, "raw") != 0) {
2722 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2723 "please use 'raw'", stream_format);
2727 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2731 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
2732 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2736 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
2737 /* warn if not Low Complexity profile */
2740 GST_WARNING_OBJECT (qtmux,
2741 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2745 entry.fourcc = FOURCC_mp4a;
2747 if (format == GST_QT_MUX_FORMAT_QT)
2748 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2749 qtpad->avg_bitrate, qtpad->max_bitrate);
2752 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2753 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2754 qtpad->max_bitrate);
2759 } else if (strcmp (mimetype, "audio/AMR") == 0) {
2760 entry.fourcc = FOURCC_samr;
2761 entry.sample_size = 16;
2762 entry.samples_per_packet = 160;
2763 entry.bytes_per_sample = 2;
2764 ext_atom = build_amr_extension ();
2765 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2766 entry.fourcc = FOURCC_sawb;
2767 entry.sample_size = 16;
2768 entry.samples_per_packet = 320;
2769 entry.bytes_per_sample = 2;
2770 ext_atom = build_amr_extension ();
2771 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
2774 gst_audio_info_init (&info);
2775 if (!gst_audio_info_from_caps (&info, caps))
2778 /* spec has no place for a distinction in these */
2779 if (info.finfo->width != info.finfo->depth) {
2780 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2784 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
2785 if (info.finfo->endianness == G_LITTLE_ENDIAN)
2786 entry.fourcc = FOURCC_sowt;
2787 else if (info.finfo->endianness == G_BIG_ENDIAN)
2788 entry.fourcc = FOURCC_twos;
2789 /* maximum backward compatibility; only new version for > 16 bit */
2790 if (info.finfo->depth <= 16)
2792 /* not compressed in any case */
2793 entry.compression_id = 0;
2794 /* QT spec says: max at 16 bit even if sample size were actually larger,
2795 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2796 entry.sample_size = info.finfo->depth;
2797 entry.bytes_per_sample = info.finfo->depth / 8;
2798 entry.samples_per_packet = 1;
2799 entry.bytes_per_packet = info.finfo->depth / 8;
2800 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
2802 if (info.finfo->width == 8 && info.finfo->depth == 8) {
2803 /* fall back to old 8-bit version */
2804 entry.fourcc = FOURCC_raw_;
2806 entry.compression_id = 0;
2807 entry.sample_size = 8;
2809 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2813 constant_size = (info.finfo->depth / 8) * info.channels;
2814 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2815 entry.fourcc = FOURCC_alaw;
2816 entry.samples_per_packet = 1023;
2817 entry.bytes_per_sample = 2;
2818 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2819 entry.fourcc = FOURCC_ulaw;
2820 entry.samples_per_packet = 1023;
2821 entry.bytes_per_sample = 2;
2822 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2824 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2825 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2828 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2830 entry.fourcc = MS_WAVE_FOURCC (0x11);
2831 /* 4 byte header per channel (including one sample). 2 samples per byte
2832 remaining. Simplifying gives the following (samples per block per
2834 entry.samples_per_packet = 2 * blocksize / channels - 7;
2835 entry.bytes_per_sample = 2;
2837 entry.bytes_per_frame = blocksize;
2838 entry.bytes_per_packet = blocksize / channels;
2839 /* ADPCM has constant size packets */
2841 /* TODO: I don't really understand why this helps, but it does! Constant
2842 * size and compression_id of -2 seem to be incompatible, and other files
2843 * in the wild use this too. */
2844 entry.compression_id = -1;
2846 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2847 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2848 GstBuffer *codec_config;
2852 entry.fourcc = FOURCC_alac;
2853 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
2854 /* let's check if codec data already comes with 'alac' atom prefix */
2855 if (!codec_data || (len = map.size) < 28) {
2856 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2857 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2860 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
2863 gst_buffer_copy_region ((GstBuffer *) codec_data, 0, 8, len);
2865 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2867 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2869 /* does not look good, but perhaps some trailing unneeded stuff */
2870 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2872 if (format == GST_QT_MUX_FORMAT_QT)
2873 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2875 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2876 /* set some more info */
2877 gst_buffer_map (codec_config, &map, GST_MAP_READ);
2878 entry.bytes_per_sample = 2;
2879 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
2880 gst_buffer_unmap (codec_config, &map);
2881 gst_buffer_unref (codec_config);
2887 /* ok, set the pad info accordingly */
2888 qtpad->fourcc = entry.fourcc;
2889 qtpad->sample_size = constant_size;
2890 atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2891 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2892 ext_atom, constant_size);
2894 gst_object_unref (qtmux);
2900 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2901 GST_PAD_NAME (pad), caps);
2902 gst_object_unref (qtmux);
2905 refuse_renegotiation:
2907 GST_WARNING_OBJECT (qtmux,
2908 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2909 GST_PAD_NAME (pad), caps);
2910 gst_object_unref (qtmux);
2915 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2917 adjust_rate (guint64 rate)
2922 while (rate >= 10000)
2928 return (guint32) rate;
2932 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2934 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2935 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2936 GstQTPad *qtpad = NULL;
2937 GstStructure *structure;
2938 const gchar *mimetype;
2939 gint width, height, depth = -1;
2940 gint framerate_num, framerate_den;
2942 const GValue *value = NULL;
2943 const GstBuffer *codec_data = NULL;
2944 VisualSampleEntry entry = { 0, };
2945 GstQTMuxFormat format;
2946 AtomInfo *ext_atom = NULL;
2947 GList *ext_atom_list = NULL;
2948 gboolean sync = FALSE;
2949 int par_num, par_den;
2951 /* find stream data */
2952 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2955 qtpad->prepare_buf_func = NULL;
2957 /* does not go well to renegotiate stream mid-way, unless
2958 * the old caps are a subset of the new one (this means upstream
2959 * added more info to the caps, as both should be 'fixed' caps) */
2960 if (qtpad->fourcc) {
2961 GstCaps *current_caps;
2963 current_caps = gst_pad_get_current_caps (pad);
2964 g_assert (caps != NULL);
2966 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2967 gst_caps_unref (current_caps);
2968 goto refuse_renegotiation;
2970 GST_DEBUG_OBJECT (qtmux,
2971 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2972 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2973 gst_caps_unref (current_caps);
2976 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2977 GST_DEBUG_PAD_NAME (pad), caps);
2979 format = qtmux_klass->format;
2980 structure = gst_caps_get_structure (caps, 0);
2981 mimetype = gst_structure_get_name (structure);
2983 /* required parts */
2984 if (!gst_structure_get_int (structure, "width", &width) ||
2985 !gst_structure_get_int (structure, "height", &height))
2990 /* works as a default timebase */
2991 framerate_num = 10000;
2993 gst_structure_get_fraction (structure, "framerate", &framerate_num,
2995 gst_structure_get_int (structure, "depth", &depth);
2996 value = gst_structure_get_value (structure, "codec_data");
2998 codec_data = gst_value_get_buffer (value);
3002 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
3005 qtpad->is_out_of_order = FALSE;
3007 /* bring frame numerator into a range that ensures both reasonable resolution
3008 * as well as a fair duration */
3009 rate = qtmux->trak_timescale ?
3010 qtmux->trak_timescale : adjust_rate (framerate_num);
3011 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
3014 /* set common properties */
3015 entry.width = width;
3016 entry.height = height;
3017 entry.par_n = par_num;
3018 entry.par_d = par_den;
3019 /* should be OK according to qt and iso spec, override if really needed */
3020 entry.color_table_id = -1;
3021 entry.frame_count = 1;
3024 /* sync entries by default */
3027 /* now map onto a fourcc, and some extra properties */
3028 if (strcmp (mimetype, "video/x-raw") == 0) {
3029 const gchar *format;
3031 const GstVideoFormatInfo *vinfo;
3033 format = gst_structure_get_string (structure, "format");
3034 fmt = gst_video_format_from_string (format);
3035 vinfo = gst_video_format_get_info (fmt);
3038 case GST_VIDEO_FORMAT_UYVY:
3041 entry.fourcc = FOURCC_2vuy;
3042 entry.depth = depth;
3046 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
3047 entry.fourcc = FOURCC_raw_;
3048 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
3053 } else if (strcmp (mimetype, "video/x-h263") == 0) {
3055 if (format == GST_QT_MUX_FORMAT_QT)
3056 entry.fourcc = FOURCC_h263;
3058 entry.fourcc = FOURCC_s263;
3059 ext_atom = build_h263_extension ();
3060 if (ext_atom != NULL)
3061 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3062 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
3063 strcmp (mimetype, "video/mpeg") == 0) {
3066 if (strcmp (mimetype, "video/x-divx") == 0) {
3067 gst_structure_get_int (structure, "divxversion", &version);
3068 version = version == 5 ? 1 : 0;
3070 gst_structure_get_int (structure, "mpegversion", &version);
3071 version = version == 4 ? 1 : 0;
3074 entry.fourcc = FOURCC_mp4v;
3076 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
3077 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
3078 qtpad->max_bitrate);
3079 if (ext_atom != NULL)
3080 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3082 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
3083 "output might not play in Apple QuickTime (try global-headers?)");
3085 } else if (strcmp (mimetype, "video/x-h264") == 0) {
3086 /* check if we accept these caps */
3087 if (gst_structure_has_field (structure, "stream-format")) {
3088 const gchar *format;
3089 const gchar *alignment;
3091 format = gst_structure_get_string (structure, "stream-format");
3092 alignment = gst_structure_get_string (structure, "alignment");
3094 if (strcmp (format, "avc") != 0 || alignment == NULL ||
3095 strcmp (alignment, "au") != 0) {
3096 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
3097 "avc format with AU aligned samples");
3101 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
3106 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
3110 entry.fourcc = FOURCC_avc1;
3111 if (qtpad->avg_bitrate == 0) {
3112 gint avg_bitrate = 0;
3113 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
3114 qtpad->avg_bitrate = avg_bitrate;
3116 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
3117 if (ext_atom != NULL)
3118 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3119 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
3120 if (ext_atom != NULL)
3121 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3122 } else if (strcmp (mimetype, "video/x-svq") == 0) {
3124 const GstBuffer *seqh = NULL;
3125 const GValue *seqh_value;
3128 gst_structure_get_int (structure, "svqversion", &version);
3130 entry.fourcc = FOURCC_SVQ3;
3134 seqh_value = gst_structure_get_value (structure, "seqh");
3136 seqh = gst_value_get_buffer (seqh_value);
3137 ext_atom = build_SMI_atom (seqh);
3139 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3142 /* we need to add the gamma anyway because quicktime might crash
3143 * when it doesn't find it */
3144 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
3145 /* it seems that using 0 here makes it ignored */
3148 ext_atom = build_gama_atom (gamma);
3150 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3152 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
3153 "a bug at http://bugzilla.gnome.org", version);
3155 } else if (strcmp (mimetype, "video/x-dv") == 0) {
3157 gboolean pal = TRUE;
3160 if (framerate_num != 25 || framerate_den != 1)
3162 gst_structure_get_int (structure, "dvversion", &version);
3163 /* fall back to typical one */
3169 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
3171 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
3175 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
3177 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
3180 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
3183 } else if (strcmp (mimetype, "image/jpeg") == 0) {
3184 entry.fourcc = FOURCC_jpeg;
3186 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
3187 strcmp (mimetype, "image/x-jpc") == 0) {
3188 const gchar *colorspace;
3189 const GValue *cmap_array;
3190 const GValue *cdef_array;
3194 if (strcmp (mimetype, "image/x-jpc") == 0) {
3195 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
3198 gst_structure_get_int (structure, "num-components", &ncomp);
3199 gst_structure_get_int (structure, "fields", &fields);
3200 cmap_array = gst_structure_get_value (structure, "component-map");
3201 cdef_array = gst_structure_get_value (structure, "channel-definitions");
3204 entry.fourcc = FOURCC_mjp2;
3207 colorspace = gst_structure_get_string (structure, "colorspace");
3210 build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
3211 cmap_array, cdef_array)) != NULL) {
3212 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3214 ext_atom = build_fiel_extension (fields);
3216 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3218 ext_atom = build_jp2x_extension (codec_data);
3220 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3222 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3225 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3226 entry.fourcc = FOURCC_VP80;
3228 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3229 entry.fourcc = FOURCC_drac;
3230 qtpad->have_dts = TRUE;
3231 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3234 gst_structure_get_uint (structure, "format", &fourcc);
3235 entry.fourcc = fourcc;
3236 qtpad->have_dts = TRUE;
3237 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3240 gst_structure_get_uint (structure, "format", &fourcc);
3241 entry.fourcc = fourcc;
3242 qtpad->have_dts = TRUE;
3248 /* ok, set the pad info accordingly */
3249 qtpad->fourcc = entry.fourcc;
3251 atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3254 gst_object_unref (qtmux);
3260 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3261 GST_PAD_NAME (pad), caps);
3262 gst_object_unref (qtmux);
3265 refuse_renegotiation:
3267 GST_WARNING_OBJECT (qtmux,
3268 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
3270 gst_object_unref (qtmux);
3276 gst_qt_mux_sink_event (GstCollectPads2 * pads, GstCollectData2 * data,
3277 GstEvent * event, gpointer user_data)
3280 guint32 avg_bitrate = 0, max_bitrate = 0;
3281 GstPad *pad = data->pad;
3282 gboolean ret = FALSE;
3284 qtmux = GST_QT_MUX_CAST (user_data);
3285 switch (GST_EVENT_TYPE (event)) {
3286 case GST_EVENT_CAPS:
3289 GstQTPad *collect_pad;
3291 gst_event_parse_caps (event, &caps);
3293 /* find stream data */
3294 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
3295 g_assert (collect_pad);
3296 g_assert (collect_pad->set_caps);
3298 ret = collect_pad->set_caps (pad, caps);
3299 gst_event_unref (event);
3302 case GST_EVENT_TAG:{
3304 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3305 GstTagMergeMode mode;
3307 GST_OBJECT_LOCK (qtmux);
3308 mode = gst_tag_setter_get_tag_merge_mode (setter);
3310 gst_event_parse_tag (event, &list);
3311 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
3312 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
3314 gst_tag_setter_merge_tags (setter, list, mode);
3315 GST_OBJECT_UNLOCK (qtmux);
3317 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3318 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3319 GstQTPad *qtpad = gst_pad_get_element_private (pad);
3322 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3323 qtpad->avg_bitrate = avg_bitrate;
3324 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3325 qtpad->max_bitrate = max_bitrate;
3328 gst_event_unref (event);
3333 ret = gst_pad_event_default (data->pad, GST_OBJECT (qtmux), event);
3336 case GST_EVENT_SEGMENT:
3337 gst_event_unref (event);
3346 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3348 GstQTMux *mux = GST_QT_MUX_CAST (element);
3351 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3353 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3354 GstQTPad *qtpad = (GstQTPad *) walk->data;
3355 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3356 if (qtpad->collect.pad == pad) {
3357 /* this is it, remove */
3358 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3359 gst_element_remove_pad (element, pad);
3364 gst_collect_pads2_remove_pad (mux->collect, pad);
3368 gst_qt_mux_request_new_pad (GstElement * element,
3369 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
3371 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3372 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3373 GstQTPad *collect_pad;
3379 if (templ->direction != GST_PAD_SINK)
3380 goto wrong_direction;
3382 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3385 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
3387 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
3388 name = g_strdup (req_name);
3390 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
3392 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
3394 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
3395 name = g_strdup (req_name);
3397 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
3400 goto wrong_template;
3402 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3404 /* create pad and add to collections */
3405 newpad = gst_pad_new_from_template (templ, name);
3407 collect_pad = (GstQTPad *)
3408 gst_collect_pads2_add_pad_full (qtmux->collect, newpad, sizeof (GstQTPad),
3409 (GstCollectData2DestroyNotify) (gst_qt_mux_pad_reset), TRUE);
3411 gst_qt_mux_pad_reset (collect_pad);
3412 collect_pad->trak = atom_trak_new (qtmux->context);
3413 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3415 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3417 /* set up pad functions */
3419 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps);
3421 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps);
3423 gst_pad_set_active (newpad, TRUE);
3424 gst_element_add_pad (element, newpad);
3431 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3436 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3441 GST_WARNING_OBJECT (qtmux, "This is not our template!");
3447 gst_qt_mux_get_property (GObject * object,
3448 guint prop_id, GValue * value, GParamSpec * pspec)
3450 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3452 GST_OBJECT_LOCK (qtmux);
3454 case PROP_MOVIE_TIMESCALE:
3455 g_value_set_uint (value, qtmux->timescale);
3457 case PROP_TRAK_TIMESCALE:
3458 g_value_set_uint (value, qtmux->trak_timescale);
3461 g_value_set_boolean (value, qtmux->guess_pts);
3463 case PROP_DTS_METHOD:
3464 g_value_set_enum (value, qtmux->dts_method);
3466 case PROP_FAST_START:
3467 g_value_set_boolean (value, qtmux->fast_start);
3469 case PROP_FAST_START_TEMP_FILE:
3470 g_value_set_string (value, qtmux->fast_start_file_path);
3472 case PROP_MOOV_RECOV_FILE:
3473 g_value_set_string (value, qtmux->moov_recov_file_path);
3475 case PROP_FRAGMENT_DURATION:
3476 g_value_set_uint (value, qtmux->fragment_duration);
3478 case PROP_STREAMABLE:
3479 g_value_set_boolean (value, qtmux->streamable);
3482 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3485 GST_OBJECT_UNLOCK (qtmux);
3489 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3493 g_free (qtmux->fast_start_file_path);
3494 qtmux->fast_start_file_path = NULL;
3496 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3497 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3502 gst_qt_mux_set_property (GObject * object,
3503 guint prop_id, const GValue * value, GParamSpec * pspec)
3505 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3507 GST_OBJECT_LOCK (qtmux);
3509 case PROP_MOVIE_TIMESCALE:
3510 qtmux->timescale = g_value_get_uint (value);
3512 case PROP_TRAK_TIMESCALE:
3513 qtmux->trak_timescale = g_value_get_uint (value);
3516 qtmux->guess_pts = g_value_get_boolean (value);
3518 case PROP_DTS_METHOD:
3519 qtmux->dts_method = g_value_get_enum (value);
3521 case PROP_FAST_START:
3522 qtmux->fast_start = g_value_get_boolean (value);
3524 case PROP_FAST_START_TEMP_FILE:
3525 g_free (qtmux->fast_start_file_path);
3526 qtmux->fast_start_file_path = g_value_dup_string (value);
3527 /* NULL means to generate a random one */
3528 if (!qtmux->fast_start_file_path) {
3529 gst_qt_mux_generate_fast_start_file_path (qtmux);
3532 case PROP_MOOV_RECOV_FILE:
3533 g_free (qtmux->moov_recov_file_path);
3534 qtmux->moov_recov_file_path = g_value_dup_string (value);
3536 case PROP_FRAGMENT_DURATION:
3537 qtmux->fragment_duration = g_value_get_uint (value);
3539 case PROP_STREAMABLE:
3540 qtmux->streamable = g_value_get_boolean (value);
3543 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3546 GST_OBJECT_UNLOCK (qtmux);
3549 static GstStateChangeReturn
3550 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3552 GstStateChangeReturn ret;
3553 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3555 switch (transition) {
3556 case GST_STATE_CHANGE_NULL_TO_READY:
3558 case GST_STATE_CHANGE_READY_TO_PAUSED:
3559 gst_collect_pads2_start (qtmux->collect);
3560 qtmux->state = GST_QT_MUX_STATE_STARTED;
3562 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3564 case GST_STATE_CHANGE_PAUSED_TO_READY:
3565 gst_collect_pads2_stop (qtmux->collect);
3571 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3573 switch (transition) {
3574 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3576 case GST_STATE_CHANGE_PAUSED_TO_READY:
3577 gst_qt_mux_reset (qtmux, TRUE);
3579 case GST_STATE_CHANGE_READY_TO_NULL:
3589 gst_qt_mux_register (GstPlugin * plugin)
3591 GTypeInfo typeinfo = {
3592 sizeof (GstQTMuxClass),
3593 (GBaseInitFunc) gst_qt_mux_base_init,
3595 (GClassInitFunc) gst_qt_mux_class_init,
3600 (GInstanceInitFunc) gst_qt_mux_init,
3602 static const GInterfaceInfo tag_setter_info = {
3605 static const GInterfaceInfo tag_xmp_writer_info = {
3609 GstQTMuxFormat format;
3610 GstQTMuxClassParams *params;
3613 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3615 GST_LOG ("Registering muxers");
3618 GstQTMuxFormatProp *prop;
3620 prop = &gst_qt_mux_format_list[i];
3621 format = prop->format;
3622 if (format == GST_QT_MUX_FORMAT_NONE)
3625 /* create a cache for these properties */
3626 params = g_new0 (GstQTMuxClassParams, 1);
3627 params->prop = prop;
3628 params->src_caps = gst_static_caps_get (&prop->src_caps);
3629 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3630 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3632 /* create the type now */
3633 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3635 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3636 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3637 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3638 &tag_xmp_writer_info);
3640 if (!gst_element_register (plugin, prop->name, prop->rank, type))
3646 GST_LOG ("Finished registering muxers");
3648 /* FIXME: ideally classification tag should be added and
3649 registered in gstreamer core gsttaglist
3652 GST_LOG ("Registering tags");
3654 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3655 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3656 gst_tag_merge_use_first);
3658 GST_LOG ("Finished registering tags");