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., 51 Franklin St, Fifth Floor,
20 * Boston, MA 02110-1301, 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-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
102 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
105 * Last reviewed on 2010-12-03
116 #include <glib/gstdio.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/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 (GstCollectPads * pads,
230 GstCollectData * data, GstEvent * event, gpointer user_data);
232 static GstFlowReturn gst_qt_mux_handle_buffer (GstCollectPads * pads,
233 GstCollectData * 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",
256 params->prop->long_name);
257 gst_element_class_set_static_metadata (element_class, longname,
258 "Codec/Muxer", description,
259 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
261 g_free (description);
264 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
265 GST_PAD_ALWAYS, params->src_caps);
266 gst_element_class_add_pad_template (element_class, srctempl);
268 if (params->audio_sink_caps) {
269 audiosinktempl = gst_pad_template_new ("audio_%u",
270 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
271 gst_element_class_add_pad_template (element_class, audiosinktempl);
274 if (params->video_sink_caps) {
275 videosinktempl = gst_pad_template_new ("video_%u",
276 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
277 gst_element_class_add_pad_template (element_class, videosinktempl);
280 klass->format = params->prop->format;
284 gst_qt_mux_class_init (GstQTMuxClass * klass)
286 GObjectClass *gobject_class;
287 GstElementClass *gstelement_class;
289 gobject_class = (GObjectClass *) klass;
290 gstelement_class = (GstElementClass *) klass;
292 parent_class = g_type_class_peek_parent (klass);
294 gobject_class->finalize = gst_qt_mux_finalize;
295 gobject_class->get_property = gst_qt_mux_get_property;
296 gobject_class->set_property = gst_qt_mux_set_property;
298 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
299 g_param_spec_uint ("movie-timescale", "Movie timescale",
300 "Timescale to use in the movie (units per second)",
301 1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
302 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
303 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
304 g_param_spec_uint ("trak-timescale", "Track timescale",
305 "Timescale to use for the tracks (units per second, 0 is automatic)",
306 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
307 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
308 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
309 g_param_spec_boolean ("presentation-time",
310 "Include presentation-time info",
311 "Calculate and include presentation/composition time "
312 "(in addition to decoding time)", DEFAULT_DO_CTTS,
313 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
314 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
315 g_param_spec_enum ("dts-method", "dts-method",
316 "Method to determine DTS time",
317 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
318 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
319 g_object_class_install_property (gobject_class, PROP_FAST_START,
320 g_param_spec_boolean ("faststart", "Format file to faststart",
321 "If the file should be formatted for faststart (headers first)",
322 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
323 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
324 g_param_spec_string ("faststart-file", "File to use for storing buffers",
325 "File that will be used temporarily to store data from the stream "
326 "when creating a faststart file. If null a filepath will be "
327 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
328 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
329 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
330 g_param_spec_string ("moov-recovery-file",
331 "File to store data for posterior moov atom recovery",
332 "File to be used to store "
333 "data for moov atom making movie file recovery possible in case "
334 "of a crash during muxing. Null for disabled. (Experimental)",
335 DEFAULT_MOOV_RECOV_FILE,
336 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
337 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
338 g_param_spec_uint ("fragment-duration", "Fragment duration",
339 "Fragment durations in ms (produce a fragmented file if > 0)",
340 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
341 2000 : DEFAULT_FRAGMENT_DURATION,
342 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
343 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
344 g_param_spec_boolean ("streamable", "Streamable",
345 "If set to true, the output should be as if it is to be streamed "
346 "and hence no indexes written or duration written.",
348 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
350 gstelement_class->request_new_pad =
351 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
352 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
353 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
357 gst_qt_mux_pad_reset (GstQTPad * qtpad)
362 qtpad->is_out_of_order = FALSE;
363 qtpad->have_dts = FALSE;
364 qtpad->sample_size = 0;
367 qtpad->first_ts = GST_CLOCK_TIME_NONE;
368 qtpad->prepare_buf_func = NULL;
369 qtpad->avg_bitrate = 0;
370 qtpad->max_bitrate = 0;
371 qtpad->ts_n_entries = 0;
372 qtpad->total_duration = 0;
373 qtpad->total_bytes = 0;
377 for (i = 0; i < G_N_ELEMENTS (qtpad->buf_entries); i++) {
378 if (qtpad->buf_entries[i]) {
379 gst_buffer_unref (qtpad->buf_entries[i]);
380 qtpad->buf_entries[i] = NULL;
385 gst_buffer_replace (&qtpad->last_buf, NULL);
387 /* reference owned elsewhere */
391 atom_traf_free (qtpad->traf);
394 atom_array_clear (&qtpad->fragment_buffers);
396 /* reference owned elsewhere */
401 * Takes GstQTMux back to its initial state
404 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
408 qtmux->state = GST_QT_MUX_STATE_NONE;
409 qtmux->header_size = 0;
410 qtmux->mdat_size = 0;
412 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
413 qtmux->video_pads = 0;
414 qtmux->audio_pads = 0;
415 qtmux->fragment_sequence = 0;
418 atom_ftyp_free (qtmux->ftyp);
422 atom_moov_free (qtmux->moov);
426 atom_mfra_free (qtmux->mfra);
429 if (qtmux->fast_start_file) {
430 fclose (qtmux->fast_start_file);
431 g_remove (qtmux->fast_start_file_path);
432 qtmux->fast_start_file = NULL;
434 if (qtmux->moov_recov_file) {
435 fclose (qtmux->moov_recov_file);
436 qtmux->moov_recov_file = NULL;
438 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
439 AtomInfo *ainfo = (AtomInfo *) walk->data;
440 ainfo->free_func (ainfo->atom);
443 g_slist_free (qtmux->extra_atoms);
444 qtmux->extra_atoms = NULL;
446 GST_OBJECT_LOCK (qtmux);
447 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
448 GST_OBJECT_UNLOCK (qtmux);
451 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
452 GstQTPad *qtpad = (GstQTPad *) walk->data;
453 gst_qt_mux_pad_reset (qtpad);
455 /* hm, moov_free above yanked the traks away from us,
456 * so do not free, but do clear */
461 qtmux->moov = atom_moov_new (qtmux->context);
462 /* ensure all is as nice and fresh as request_new_pad would provide it */
463 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
464 GstQTPad *qtpad = (GstQTPad *) walk->data;
466 qtpad->trak = atom_trak_new (qtmux->context);
467 atom_moov_add_trak (qtmux->moov, qtpad->trak);
473 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
475 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
476 GstPadTemplate *templ;
478 templ = gst_element_class_get_pad_template (klass, "src");
479 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
480 gst_pad_use_fixed_caps (qtmux->srcpad);
481 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
483 qtmux->sinkpads = NULL;
484 qtmux->collect = gst_collect_pads_new ();
485 gst_collect_pads_set_buffer_function (qtmux->collect,
486 GST_DEBUG_FUNCPTR (gst_qt_mux_handle_buffer), qtmux);
487 gst_collect_pads_set_event_function (qtmux->collect,
488 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
489 gst_collect_pads_set_clip_function (qtmux->collect,
490 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
492 /* properties set to default upon construction */
494 /* always need this */
496 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
498 /* internals to initial state */
499 gst_qt_mux_reset (qtmux, TRUE);
504 gst_qt_mux_finalize (GObject * object)
506 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
508 gst_qt_mux_reset (qtmux, FALSE);
510 g_free (qtmux->fast_start_file_path);
511 g_free (qtmux->moov_recov_file_path);
513 atoms_context_free (qtmux->context);
514 gst_object_unref (qtmux->collect);
516 g_slist_free (qtmux->sinkpads);
518 G_OBJECT_CLASS (parent_class)->finalize (object);
522 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
529 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
534 size = gst_buffer_get_size (buf);
535 newbuf = gst_buffer_new_and_alloc (size + 8);
536 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
538 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
539 GST_WRITE_UINT32_BE (map.data, map.size);
540 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
542 gst_buffer_unmap (buf, &map);
543 gst_buffer_unref (buf);
549 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
550 const char *tag, const char *tag2, guint32 fourcc)
552 switch (gst_tag_get_type (tag)) {
558 if (!gst_tag_list_get_string (list, tag, &str) || !str)
560 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
561 GST_FOURCC_ARGS (fourcc), str);
562 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
571 if (!gst_tag_list_get_double (list, tag, &value))
573 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
574 GST_FOURCC_ARGS (fourcc), (gint) value);
575 atom_moov_add_uint_tag (qtmux->moov, fourcc, 21, (gint) value);
582 /* paired unsigned integers */
586 got_tag = gst_tag_list_get_uint (list, tag, &value);
587 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
590 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
591 GST_FOURCC_ARGS (fourcc), value, count);
592 atom_moov_add_uint_tag (qtmux->moov, fourcc, 0,
593 value << 16 | (count & 0xFFFF));
595 /* unpaired unsigned integers */
596 if (!gst_tag_list_get_uint (list, tag, &value))
598 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
599 GST_FOURCC_ARGS (fourcc), value);
600 atom_moov_add_uint_tag (qtmux->moov, fourcc, 1, value);
605 g_assert_not_reached ();
611 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
612 const char *tag, const char *tag2, guint32 fourcc)
620 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
622 if (!gst_tag_list_get_date (list, tag, &date) || !date)
625 year = g_date_get_year (date);
626 month = g_date_get_month (date);
627 day = g_date_get_day (date);
631 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
632 day == G_DATE_BAD_DAY) {
633 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
637 str = g_strdup_printf ("%u-%u-%u", year, month, day);
638 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
639 GST_FOURCC_ARGS (fourcc), str);
640 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
645 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
646 const char *tag, const char *tag2, guint32 fourcc)
648 GValue value = { 0, };
652 GstStructure *structure;
656 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
658 if (!gst_tag_list_copy_value (&value, list, tag))
661 sample = gst_value_get_sample (&value);
666 buf = gst_sample_get_buffer (sample);
670 caps = gst_sample_get_caps (sample);
672 GST_WARNING_OBJECT (qtmux, "preview image without caps");
676 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
678 structure = gst_caps_get_structure (caps, 0);
679 if (gst_structure_has_name (structure, "image/jpeg"))
681 else if (gst_structure_has_name (structure, "image/png"))
685 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
689 gst_buffer_map (buf, &map, GST_MAP_READ);
690 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
691 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
692 atom_moov_add_tag (qtmux->moov, fourcc, flags, map.data, map.size);
693 gst_buffer_unmap (buf, &map);
695 g_value_unset (&value);
699 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
700 const char *tag, const char *tag2, guint32 fourcc)
705 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
706 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
708 if (!gst_tag_list_get_string (list, tag, &str) || !str)
712 if (!gst_tag_list_get_uint (list, tag2, &number))
716 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
717 GST_FOURCC_ARGS (fourcc), str);
718 atom_moov_add_3gp_str_tag (qtmux->moov, fourcc, str);
720 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
721 GST_FOURCC_ARGS (fourcc), str, number);
722 atom_moov_add_3gp_str_int_tag (qtmux->moov, fourcc, str, number);
729 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
730 const char *tag, const char *tag2, guint32 fourcc)
735 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
737 if (!gst_tag_list_get_date (list, tag, &date) || !date)
740 year = g_date_get_year (date);
742 if (year == G_DATE_BAD_YEAR) {
743 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
747 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
748 GST_FOURCC_ARGS (fourcc), year);
749 atom_moov_add_3gp_uint_tag (qtmux->moov, fourcc, year);
753 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
754 const char *tag, const char *tag2, guint32 fourcc)
756 gdouble latitude = -360, longitude = -360, altitude = 0;
757 gchar *location = NULL;
758 guint8 *data, *ddata;
759 gint size = 0, len = 0;
760 gboolean ret = FALSE;
762 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
764 ret = gst_tag_list_get_string (list, tag, &location);
765 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
767 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
769 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
776 len = strlen (location);
779 /* role + (long, lat, alt) + body + notes */
780 size += 1 + 3 * 4 + 1 + 1;
782 data = ddata = g_malloc (size);
785 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
788 memcpy (data + 2, location, len);
789 GST_WRITE_UINT8 (data + 2 + len, 0);
792 GST_WRITE_UINT8 (data, 0);
794 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
795 QT_WRITE_SFP32 (data + 1, longitude);
796 QT_WRITE_SFP32 (data + 5, latitude);
797 QT_WRITE_SFP32 (data + 9, altitude);
798 /* neither astronomical body nor notes */
799 GST_WRITE_UINT16_BE (data + 13, 0);
801 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
802 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
807 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
808 const char *tag, const char *tag2, guint32 fourcc)
810 gchar *keywords = NULL;
811 guint8 *data, *ddata;
815 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
817 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
820 kwds = g_strsplit (keywords, ",", 0);
824 for (i = 0; kwds[i]; i++) {
825 /* size byte + null-terminator */
826 size += strlen (kwds[i]) + 1 + 1;
829 /* language tag + count + keywords */
832 data = ddata = g_malloc (size);
835 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
837 GST_WRITE_UINT8 (data + 2, i);
840 for (i = 0; kwds[i]; ++i) {
841 gint len = strlen (kwds[i]);
843 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
844 GST_FOURCC_ARGS (fourcc), kwds[i]);
846 GST_WRITE_UINT8 (data, len + 1);
847 memcpy (data + 1, kwds[i], len + 1);
853 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
858 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
859 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
867 size = strlen (input);
869 if (size < 4 + 3 + 1 + 1 + 1) {
870 /* at least the minimum xxxx://y/z */
871 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
876 /* read the fourcc */
877 memcpy (&fourcc, data, 4);
881 if (strncmp (data, "://", 3) != 0) {
887 /* read the table number */
888 if (sscanf (data, "%d", &table) != 1) {
892 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
893 ", table numbers should be positive, ignoring tag", table);
897 /* find the next / */
898 while (size > 0 && data[0] != '/') {
905 g_assert (data[0] == '/');
914 /* read up the rest of the string */
915 *p_content = g_strdup (data);
916 *p_table = (guint16) table;
922 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
923 "input (%s) didn't match the expected entitycode://table/content",
930 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
931 const char *tag, const char *tag2, guint32 fourcc)
933 gchar *clsf_data = NULL;
937 gchar *content = NULL;
940 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
942 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
945 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
946 GST_FOURCC_ARGS (fourcc), clsf_data);
948 /* parse the string, format is:
949 * entityfourcc://table/content
951 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
955 size = strlen (content) + 1;
957 /* now we have everything, build the atom
958 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
959 data = g_malloc (4 + 2 + 2 + size);
960 GST_WRITE_UINT32_LE (data, entity);
961 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
962 GST_WRITE_UINT16_BE (data + 6, 0);
963 memcpy (data + 8, content, size);
966 atom_moov_add_3gp_tag (qtmux->moov, fourcc, data, 4 + 2 + 2 + size);
970 typedef void (*GstQTMuxAddTagFunc) (GstQTMux * mux, const GstTagList * list,
971 const char *tag, const char *tag2, guint32 fourcc);
974 * Struct to record mappings from gstreamer tags to fourcc codes
976 typedef struct _GstTagToFourcc
980 const gchar *gsttag2;
981 const GstQTMuxAddTagFunc func;
984 /* tag list tags to fourcc matching */
985 static const GstTagToFourcc tag_matches_mp4[] = {
986 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
987 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
988 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
989 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
990 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
991 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
992 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
993 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
994 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
995 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
996 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
997 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
998 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
999 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1000 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1001 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1002 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1003 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1004 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1005 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1006 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1007 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1008 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1009 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1010 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1011 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1012 gst_qt_mux_add_mp4_tag},
1013 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1014 gst_qt_mux_add_mp4_tag},
1015 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1016 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1020 static const GstTagToFourcc tag_matches_3gp[] = {
1021 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1022 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1023 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1024 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1025 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1026 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1027 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1028 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1029 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1030 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1031 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1032 gst_qt_mux_add_3gp_classification},
1036 /* qtdemux produces these for atoms it cannot parse */
1037 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1040 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1042 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1043 GstBuffer *xmp = NULL;
1045 /* adobe specs only have 'quicktime' and 'mp4',
1046 * but I guess we can extrapolate to gpp.
1047 * Keep mj2 out for now as we don't add any tags for it yet.
1048 * If you have further info about xmp on these formats, please share */
1049 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1052 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1054 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1055 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1058 atom_moov_add_xmp_tags (qtmux->moov, xmp);
1061 /* for isom/mp4, it is a top level uuid atom */
1062 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1065 ainfo = build_uuid_xmp_atom (xmp);
1067 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1072 gst_buffer_unref (xmp);
1076 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list)
1078 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1081 const gchar *tag, *tag2;
1082 const GstTagToFourcc *tag_matches;
1084 switch (qtmux_klass->format) {
1085 case GST_QT_MUX_FORMAT_3GP:
1086 tag_matches = tag_matches_3gp;
1088 case GST_QT_MUX_FORMAT_MJ2:
1092 /* sort of iTunes style for mp4 and QT (?) */
1093 tag_matches = tag_matches_mp4;
1100 for (i = 0; tag_matches[i].fourcc; i++) {
1101 fourcc = tag_matches[i].fourcc;
1102 tag = tag_matches[i].gsttag;
1103 tag2 = tag_matches[i].gsttag2;
1105 g_assert (tag_matches[i].func);
1106 tag_matches[i].func (qtmux, list, tag, tag2, fourcc);
1109 /* add unparsed blobs if present */
1110 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1113 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1114 for (i = 0; i < num_tags; ++i) {
1115 GstSample *sample = NULL;
1117 const GstStructure *s;
1119 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1122 buf = gst_sample_get_buffer (sample);
1124 if (buf && (s = gst_sample_get_info (sample))) {
1125 const gchar *style = NULL;
1128 gst_buffer_map (buf, &map, GST_MAP_READ);
1129 GST_DEBUG_OBJECT (qtmux,
1130 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1131 GST_PTR_FORMAT, i, num_tags, map.size, s);
1132 if (s && (style = gst_structure_get_string (s, "style"))) {
1133 /* try to prevent some style tag ending up into another variant
1134 * (todo: make into a list if more cases) */
1135 if ((strcmp (style, "itunes") == 0 &&
1136 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1137 (strcmp (style, "iso") == 0 &&
1138 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1139 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1140 atom_moov_add_blob_tag (qtmux->moov, map.data, map.size);
1143 gst_buffer_unmap (buf, &map);
1152 * Gets the tagsetter iface taglist and puts the known tags
1153 * into the output stream
1156 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1158 const GstTagList *tags;
1160 GST_OBJECT_LOCK (qtmux);
1161 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1162 GST_OBJECT_UNLOCK (qtmux);
1164 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1166 if (tags && !gst_tag_list_is_empty (tags)) {
1167 GstTagList *copy = gst_tag_list_copy (tags);
1169 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1170 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1171 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1172 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1174 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1175 gst_qt_mux_add_metadata_tags (qtmux, copy);
1176 gst_qt_mux_add_xmp_tags (qtmux, copy);
1177 gst_tag_list_unref (copy);
1179 GST_DEBUG_OBJECT (qtmux, "No tags received");
1183 static inline GstBuffer *
1184 _gst_buffer_new_take_data (guint8 * data, guint size)
1188 buf = gst_buffer_new ();
1189 gst_buffer_append_memory (buf,
1190 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1195 static GstFlowReturn
1196 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1202 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1204 size = gst_buffer_get_size (buf);
1205 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1207 if (mind_fast && qtmux->fast_start_file) {
1211 GST_LOG_OBJECT (qtmux, "to temporary file");
1212 gst_buffer_map (buf, &map, GST_MAP_READ);
1213 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1214 gst_buffer_unmap (buf, &map);
1215 gst_buffer_unref (buf);
1221 GST_LOG_OBJECT (qtmux, "downstream");
1222 res = gst_pad_push (qtmux->srcpad, buf);
1225 if (G_LIKELY (offset))
1233 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1234 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1235 return GST_FLOW_ERROR;
1240 gst_qt_mux_seek_to_beginning (FILE * f)
1243 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1245 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1246 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1249 if (fseek (f, (long) 0, SEEK_SET) != 0)
1255 static GstFlowReturn
1256 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1258 GstFlowReturn ret = GST_FLOW_OK;
1259 GstBuffer *buf = NULL;
1261 if (fflush (qtmux->fast_start_file))
1264 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1267 /* hm, this could all take a really really long time,
1268 * but there may not be another way to get moov atom first
1269 * (somehow optimize copy?) */
1270 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1271 while (ret == GST_FLOW_OK) {
1272 const int bufsize = 4096;
1276 buf = gst_buffer_new_and_alloc (bufsize);
1277 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1278 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1280 gst_buffer_unmap (buf, &map);
1283 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1284 gst_buffer_unmap (buf, &map);
1285 if (size != bufsize)
1286 gst_buffer_set_size (buf, size);
1287 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1291 gst_buffer_unref (buf);
1293 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1295 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1303 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1304 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1305 ret = GST_FLOW_ERROR;
1310 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1311 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1312 ret = GST_FLOW_ERROR;
1317 /* clear descriptor so we don't remove temp file later on,
1318 * might be possible to recover */
1319 fclose (qtmux->fast_start_file);
1320 qtmux->fast_start_file = NULL;
1326 * Sends the initial mdat atom fields (size fields and fourcc type),
1327 * the subsequent buffers are considered part of it's data.
1328 * As we can't predict the amount of data that we are going to place in mdat
1329 * we need to record the position of the size field in the stream so we can
1330 * seek back to it later and update when the streams have finished.
1332 static GstFlowReturn
1333 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1338 guint8 *data = NULL;
1341 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1342 "size %" G_GUINT64_FORMAT, size);
1344 node_header = g_malloc0 (sizeof (Atom));
1345 node_header->type = FOURCC_mdat;
1347 /* use extended size */
1348 node_header->size = 1;
1349 node_header->extended_size = 0;
1351 node_header->extended_size = size + 16;
1353 node_header->size = size + 8;
1357 if (atom_copy_data (node_header, &data, &size, &offset) == 0)
1358 goto serialize_error;
1360 buf = _gst_buffer_new_take_data (data, offset);
1361 g_free (node_header);
1363 GST_LOG_OBJECT (qtmux, "Pushing mdat start");
1364 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1369 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1370 ("Failed to serialize mdat"));
1371 return GST_FLOW_ERROR;
1376 * We get the position of the mdat size field, seek back to it
1377 * and overwrite with the real value
1379 static GstFlowReturn
1380 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1381 guint64 mdat_size, guint64 * offset)
1384 gboolean large_file;
1388 large_file = (mdat_size > MDAT_LARGE_FILE_LIMIT);
1393 /* seek and rewrite the header */
1394 gst_segment_init (&segment, GST_FORMAT_BYTES);
1395 segment.start = mdat_pos;
1396 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1399 buf = gst_buffer_new_and_alloc (sizeof (guint64));
1400 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1401 GST_WRITE_UINT64_BE (map.data, mdat_size + 16);
1403 buf = gst_buffer_new_and_alloc (16);
1404 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1405 GST_WRITE_UINT32_BE (map.data, 8);
1406 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1407 GST_WRITE_UINT32_BE (map.data + 8, mdat_size + 8);
1408 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1410 gst_buffer_unmap (buf, &map);
1412 return gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1415 static GstFlowReturn
1416 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1419 guint64 size = 0, offset = 0;
1420 guint8 *data = NULL;
1422 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1424 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1425 goto serialize_error;
1427 buf = _gst_buffer_new_take_data (data, offset);
1429 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1430 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1435 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1436 ("Failed to serialize ftyp"));
1437 return GST_FLOW_ERROR;
1442 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1443 GstBuffer ** p_prefix)
1445 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1446 guint32 major, version;
1448 GstBuffer *prefix = NULL;
1449 AtomFTYP *ftyp = NULL;
1451 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1453 /* init and send context and ftyp based on current property state */
1454 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1455 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1456 qtmux->fast_start_file != NULL);
1457 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1464 gst_buffer_unref (prefix);
1469 static GstFlowReturn
1470 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1472 GstFlowReturn ret = GST_FLOW_OK;
1473 GstBuffer *prefix = NULL;
1475 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1477 /* init and send context and ftyp based on current property state */
1479 atom_ftyp_free (qtmux->ftyp);
1482 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1484 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1485 if (ret != GST_FLOW_OK)
1488 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1492 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1494 GstStructure *structure;
1495 GValue array = { 0 };
1496 GValue value = { 0 };
1497 GstCaps *caps, *tcaps;
1499 tcaps = gst_pad_get_current_caps (mux->srcpad);
1500 caps = gst_caps_copy (tcaps);
1501 gst_caps_unref (tcaps);
1503 structure = gst_caps_get_structure (caps, 0);
1505 g_value_init (&array, GST_TYPE_ARRAY);
1507 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1508 g_value_init (&value, GST_TYPE_BUFFER);
1509 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1510 gst_value_array_append_value (&array, &value);
1511 g_value_unset (&value);
1513 gst_structure_set_value (structure, "streamheader", &array);
1514 g_value_unset (&array);
1515 gst_pad_set_caps (mux->srcpad, caps);
1516 gst_caps_unref (caps);
1520 gst_qt_mux_configure_moov (GstQTMux * qtmux, guint32 * _timescale)
1522 gboolean fragmented;
1525 GST_OBJECT_LOCK (qtmux);
1526 timescale = qtmux->timescale;
1527 fragmented = qtmux->fragment_sequence > 0;
1528 GST_OBJECT_UNLOCK (qtmux);
1530 /* inform lower layers of our property wishes, and determine duration.
1531 * Let moov take care of this using its list of traks;
1532 * so that released pads are also included */
1533 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1535 atom_moov_update_timescale (qtmux->moov, timescale);
1536 atom_moov_set_fragmented (qtmux->moov, fragmented);
1538 atom_moov_update_duration (qtmux->moov);
1541 *_timescale = timescale;
1544 static GstFlowReturn
1545 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset, gboolean mind_fast)
1547 guint64 offset = 0, size = 0;
1550 GstFlowReturn ret = GST_FLOW_OK;
1552 /* serialize moov */
1555 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1556 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1557 goto serialize_error;
1559 buf = _gst_buffer_new_take_data (data, offset);
1560 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1561 gst_qt_mux_set_header_on_caps (qtmux, buf);
1562 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1569 return GST_FLOW_ERROR;
1573 /* either calculates size of extra atoms or pushes them */
1574 static GstFlowReturn
1575 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1579 guint64 loffset = 0, size = 0;
1581 GstFlowReturn ret = GST_FLOW_OK;
1583 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1584 AtomInfo *ainfo = (AtomInfo *) walk->data;
1588 if (!ainfo->copy_data_func (ainfo->atom,
1589 send ? &data : NULL, &size, &loffset))
1590 goto serialize_error;
1595 GST_DEBUG_OBJECT (qtmux,
1596 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1597 GST_FOURCC_ARGS (ainfo->atom->type));
1598 buf = _gst_buffer_new_take_data (data, loffset);
1599 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1600 if (ret != GST_FLOW_OK)
1613 return GST_FLOW_ERROR;
1617 static GstFlowReturn
1618 gst_qt_mux_start_file (GstQTMux * qtmux)
1620 GstFlowReturn ret = GST_FLOW_OK;
1625 GST_DEBUG_OBJECT (qtmux, "starting file");
1627 /* stream-start (FIXME: create id based on input ids) */
1628 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
1629 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
1631 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
1632 /* qtmux has structure with and without variant, remove all but the first */
1633 while (gst_caps_get_size (caps) > 1)
1634 gst_caps_remove_structure (caps, 1);
1635 gst_pad_set_caps (qtmux->srcpad, caps);
1636 gst_caps_unref (caps);
1638 /* if not streaming, check if downstream is seekable */
1639 if (!qtmux->streamable) {
1643 query = gst_query_new_seeking (GST_FORMAT_BYTES);
1644 if (gst_pad_peer_query (qtmux->srcpad, query)) {
1645 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
1646 GST_INFO_OBJECT (qtmux, "downstream is %sseekable",
1647 seekable ? "" : "not ");
1649 /* have to assume seeking is supported if query not handled downstream */
1650 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
1654 qtmux->streamable = TRUE;
1655 g_object_notify (G_OBJECT (qtmux), "streamable");
1656 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
1657 "streamable=false. Will ignore that and create streamable output "
1660 gst_query_unref (query);
1663 /* let downstream know we think in BYTES and expect to do seeking later on */
1664 gst_segment_init (&segment, GST_FORMAT_BYTES);
1665 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1667 /* initialize our moov recovery file */
1668 GST_OBJECT_LOCK (qtmux);
1669 if (qtmux->moov_recov_file_path) {
1670 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1671 qtmux->moov_recov_file_path);
1672 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1673 if (qtmux->moov_recov_file == NULL) {
1674 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1675 qtmux->moov_recov_file_path);
1678 gboolean fail = FALSE;
1679 AtomFTYP *ftyp = NULL;
1680 GstBuffer *prefix = NULL;
1682 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1684 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1685 qtmux->moov, qtmux->timescale,
1686 g_slist_length (qtmux->sinkpads))) {
1687 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1692 atom_ftyp_free (ftyp);
1694 gst_buffer_unref (prefix);
1696 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1697 GstCollectData *cdata = (GstCollectData *) walk->data;
1698 GstQTPad *qpad = (GstQTPad *) cdata;
1699 /* write info for each stream */
1700 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1702 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1708 fclose (qtmux->moov_recov_file);
1709 qtmux->moov_recov_file = NULL;
1710 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1711 "recover file, moov recovery won't work");
1715 GST_OBJECT_UNLOCK (qtmux);
1718 * send mdat header if already needed, and mark position for later update.
1719 * We don't send ftyp now if we are on fast start mode, because we can
1720 * better fine tune using the information we gather to create the whole moov
1723 if (qtmux->fast_start) {
1724 GST_OBJECT_LOCK (qtmux);
1725 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1726 if (!qtmux->fast_start_file)
1728 GST_OBJECT_UNLOCK (qtmux);
1730 /* send a dummy buffer for preroll */
1731 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1732 if (ret != GST_FLOW_OK)
1736 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1737 if (ret != GST_FLOW_OK) {
1741 /* well, it's moov pos if fragmented ... */
1742 qtmux->mdat_pos = qtmux->header_size;
1744 if (qtmux->fragment_duration) {
1745 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1746 qtmux->fragment_duration);
1747 /* also used as snapshot marker to indicate fragmented file */
1748 qtmux->fragment_sequence = 1;
1749 /* prepare moov and/or tags */
1750 gst_qt_mux_configure_moov (qtmux, NULL);
1751 gst_qt_mux_setup_metadata (qtmux);
1752 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1753 if (ret != GST_FLOW_OK)
1757 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1758 if (ret != GST_FLOW_OK)
1761 if (!qtmux->streamable)
1762 qtmux->mfra = atom_mfra_new (qtmux->context);
1764 /* extended to ensure some spare space */
1765 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1775 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1776 (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1778 GST_OBJECT_UNLOCK (qtmux);
1779 return GST_FLOW_ERROR;
1783 static GstFlowReturn
1784 gst_qt_mux_stop_file (GstQTMux * qtmux)
1786 gboolean ret = GST_FLOW_OK;
1787 guint64 offset = 0, size = 0;
1789 gboolean large_file;
1791 GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1793 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1795 /* pushing last buffers for each pad */
1796 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1797 GstCollectData *cdata = (GstCollectData *) walk->data;
1798 GstQTPad *qtpad = (GstQTPad *) cdata;
1800 /* avoid add_buffer complaining if not negotiated
1801 * in which case no buffers either, so skipping */
1802 if (!qtpad->fourcc) {
1803 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
1804 GST_PAD_NAME (qtpad->collect.pad));
1808 /* send last buffer; also flushes possibly queued buffers/ts */
1809 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1810 GST_PAD_NAME (qtpad->collect.pad));
1811 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1812 if (ret != GST_FLOW_OK) {
1813 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1814 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1815 gst_flow_get_name (ret));
1818 /* having flushed above, can check for buffers now */
1819 if (!GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
1820 GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1821 GST_PAD_NAME (qtpad->collect.pad));
1825 /* determine max stream duration */
1826 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1827 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1828 qtpad->last_dts > first_ts)) {
1829 first_ts = qtpad->last_dts;
1832 /* update average bitrate of streams if needed */
1834 guint32 avgbitrate = 0;
1835 guint32 maxbitrate = qtpad->max_bitrate;
1837 if (qtpad->avg_bitrate)
1838 avgbitrate = qtpad->avg_bitrate;
1839 else if (qtpad->total_duration > 0)
1840 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
1841 8 * GST_SECOND, qtpad->total_duration);
1843 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
1847 if (qtmux->fragment_sequence) {
1851 guint8 *data = NULL;
1855 GST_DEBUG_OBJECT (qtmux, "adding mfra");
1856 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1857 goto serialize_error;
1858 buf = _gst_buffer_new_take_data (data, offset);
1859 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1860 if (ret != GST_FLOW_OK)
1863 /* must have been streamable; no need to write duration */
1864 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1868 timescale = qtmux->timescale;
1869 /* only mvex duration is updated,
1870 * mvhd should be consistent with empty moov
1871 * (but TODO maybe some clients do not handle that well ?) */
1872 qtmux->moov->mvex.mehd.fragment_duration =
1873 gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1874 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1875 GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1876 /* seek and rewrite the header */
1877 gst_segment_init (&segment, GST_FORMAT_BYTES);
1878 segment.start = qtmux->mdat_pos;
1879 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1880 /* no need to seek back */
1881 return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1884 gst_qt_mux_configure_moov (qtmux, ×cale);
1886 /* check for late streams */
1887 first_ts = GST_CLOCK_TIME_NONE;
1888 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1889 GstCollectData *cdata = (GstCollectData *) walk->data;
1890 GstQTPad *qtpad = (GstQTPad *) cdata;
1892 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1893 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1894 qtpad->first_ts < first_ts)) {
1895 first_ts = qtpad->first_ts;
1898 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1899 GST_TIME_ARGS (first_ts));
1900 /* add EDTSs for late streams */
1901 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1902 GstCollectData *cdata = (GstCollectData *) walk->data;
1903 GstQTPad *qtpad = (GstQTPad *) cdata;
1907 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1908 qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1909 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1910 GST_PAD_NAME (qtpad->collect.pad),
1911 GST_TIME_ARGS (qtpad->first_ts - first_ts));
1912 lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1913 timescale, GST_SECOND);
1914 duration = qtpad->trak->tkhd.duration;
1915 atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1916 (guint32) (1 * 65536.0));
1917 atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1918 (guint32) (1 * 65536.0));
1920 /* need to add the empty time to the trak duration */
1921 qtpad->trak->tkhd.duration += lateness;
1925 /* tags into file metadata */
1926 gst_qt_mux_setup_metadata (qtmux);
1928 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1929 /* if faststart, update the offset of the atoms in the movie with the offset
1930 * that the movie headers before mdat will cause.
1931 * Also, send the ftyp */
1932 if (qtmux->fast_start_file) {
1933 GstFlowReturn flow_ret;
1936 flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1937 if (flow_ret != GST_FLOW_OK) {
1940 /* copy into NULL to obtain size */
1941 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1942 goto serialize_error;
1943 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1945 offset += qtmux->header_size + (large_file ? 16 : 8);
1947 /* sum up with the extra atoms size */
1948 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1949 if (ret != GST_FLOW_OK)
1952 offset = qtmux->header_size;
1954 atom_moov_chunks_add_offset (qtmux->moov, offset);
1957 /* note: as of this point, we no longer care about tracking written data size,
1958 * since there is no more use for it anyway */
1959 ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1960 if (ret != GST_FLOW_OK)
1964 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1965 if (ret != GST_FLOW_OK)
1968 /* if needed, send mdat atom and move buffered data into it */
1969 if (qtmux->fast_start_file) {
1970 /* mdat_size = accumulated (buffered data) */
1971 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1973 if (ret != GST_FLOW_OK)
1975 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1976 if (ret != GST_FLOW_OK)
1979 /* mdat needs update iff not using faststart */
1980 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1981 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1982 qtmux->mdat_size, NULL);
1983 /* note; no seeking back to the end of file is done,
1984 * since we no longer write anything anyway */
1992 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1993 ("Failed to serialize moov"));
1994 return GST_FLOW_ERROR;
1998 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1999 return GST_FLOW_ERROR;
2003 static GstFlowReturn
2004 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2005 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2006 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2008 GstFlowReturn ret = GST_FLOW_OK;
2010 /* setup if needed */
2011 if (G_UNLIKELY (!pad->traf || force))
2015 /* flush pad fragment if threshold reached,
2016 * or at new keyframe if we should be minding those in the first place */
2017 if (G_UNLIKELY (force || (sync && pad->sync) ||
2018 pad->fragment_duration < (gint64) delta)) {
2020 guint64 size = 0, offset = 0;
2021 guint8 *data = NULL;
2023 guint i, total_size;
2025 /* now we know where moof ends up, update offset in tfra */
2027 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2029 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2030 /* takes ownership */
2031 atom_moof_add_traf (moof, pad->traf);
2033 atom_moof_copy_data (moof, &data, &size, &offset);
2034 buffer = _gst_buffer_new_take_data (data, offset);
2035 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2036 gst_buffer_get_size (buffer));
2037 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2039 /* and actual data */
2041 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2043 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2046 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2047 atom_array_get_len (&pad->fragment_buffers), total_size);
2048 if (ret == GST_FLOW_OK)
2049 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2051 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2052 if (G_LIKELY (ret == GST_FLOW_OK))
2053 ret = gst_qt_mux_send_buffer (qtmux,
2054 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2057 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2060 atom_array_clear (&pad->fragment_buffers);
2061 atom_moof_free (moof);
2062 qtmux->fragment_sequence++;
2067 if (G_UNLIKELY (!pad->traf)) {
2068 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2069 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2070 atom_array_init (&pad->fragment_buffers, 512);
2071 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2072 atom_trak_get_timescale (pad->trak), 1000);
2074 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2075 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2076 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2080 /* add buffer and metadata */
2081 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2083 atom_array_append (&pad->fragment_buffers, buf, 256);
2084 pad->fragment_duration -= delta;
2087 guint32 sn = atom_traf_get_sample_num (pad->traf);
2089 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2090 atom_tfra_add_entry (pad->tfra, dts, sn);
2093 if (G_UNLIKELY (force))
2099 /* sigh, tiny list helpers to re-order stuff */
2101 gst_qt_mux_push_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2105 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2106 if (ts > pad->ts_entries[i])
2109 memmove (&pad->ts_entries[i + 1], &pad->ts_entries[i],
2110 sizeof (GstClockTime) * (pad->ts_n_entries - i));
2111 pad->ts_entries[i] = ts;
2112 pad->ts_n_entries++;
2116 check_and_subtract_ts (GstQTMux * qtmux, GstClockTime * ts_a, GstClockTime ts_b)
2118 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (*ts_a))) {
2119 if (G_LIKELY (*ts_a >= ts_b)) {
2123 GST_WARNING_OBJECT (qtmux, "Subtraction would result in negative value, "
2124 "using 0 as result");
2129 /* subtract ts from all buffers enqueued on the pad */
2131 gst_qt_mux_subtract_ts (GstQTMux * qtmux, GstQTPad * pad, GstClockTime ts)
2135 for (i = 0; (i < QTMUX_NO_OF_TS) && (i < pad->ts_n_entries); i++) {
2136 check_and_subtract_ts (qtmux, &pad->ts_entries[i], ts);
2138 for (i = 0; i < G_N_ELEMENTS (pad->buf_entries); i++) {
2139 if (pad->buf_entries[i]) {
2140 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (pad->buf_entries[i]),
2142 check_and_subtract_ts (qtmux,
2143 &GST_BUFFER_OFFSET_END (pad->buf_entries[i]), ts);
2148 /* takes ownership of @buf */
2150 gst_qt_mux_get_asc_buffer_ts (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2152 const gint wrap = G_N_ELEMENTS (pad->buf_entries);
2155 /* store buffer and ts, latter ordered */
2157 pad->buf_entries[pad->buf_tail++] = buf;
2158 pad->buf_tail %= wrap;
2159 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (buf));
2162 if (pad->ts_n_entries && (!buf || pad->ts_n_entries >= QTMUX_NO_OF_TS)) {
2163 ts = pad->ts_entries[--pad->ts_n_entries];
2164 buf = pad->buf_entries[pad->buf_head];
2165 pad->buf_entries[pad->buf_head++] = NULL;
2166 pad->buf_head %= wrap;
2167 buf = gst_buffer_make_writable (buf);
2168 /* track original ts (= pts ?) for later */
2169 GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_TIMESTAMP (buf);
2170 GST_BUFFER_TIMESTAMP (buf) = ts;
2171 GST_DEBUG_OBJECT (qtmux, "next buffer uses reordered ts %" GST_TIME_FORMAT,
2172 GST_TIME_ARGS (ts));
2181 * Here we push the buffer and update the tables in the track atoms
2183 static GstFlowReturn
2184 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
2186 GstBuffer *last_buf = NULL;
2187 GstClockTime duration;
2188 guint nsamples, sample_size;
2189 guint64 chunk_offset;
2190 gint64 last_dts, scaled_duration;
2191 gint64 pts_offset = 0;
2192 gboolean sync = FALSE, do_pts = FALSE;
2193 gboolean drain = (buf == NULL);
2194 GstFlowReturn ret = GST_FLOW_OK;
2197 goto not_negotiated;
2199 /* if this pad has a prepare function, call it */
2200 if (pad->prepare_buf_func != NULL) {
2201 buf = pad->prepare_buf_func (pad, buf, qtmux);
2204 if (G_LIKELY (buf != NULL && GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
2205 pad->first_ts != 0)) {
2206 buf = gst_buffer_make_writable (buf);
2207 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2209 /* when we obtain the first_ts we subtract from all stored buffers we have,
2210 * after that we can subtract on input */
2213 last_buf = pad->last_buf;
2214 if (qtmux->dts_method == DTS_METHOD_REORDER) {
2215 buf = gst_qt_mux_get_asc_buffer_ts (qtmux, pad, buf);
2216 if (!buf && !last_buf) {
2217 GST_DEBUG_OBJECT (qtmux, "no reordered buffer");
2222 if (last_buf == NULL) {
2223 #ifndef GST_DISABLE_GST_DEBUG
2225 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
2226 "received NULL buffer, doing nothing",
2227 GST_PAD_NAME (pad->collect.pad));
2229 GST_LOG_OBJECT (qtmux,
2230 "Pad %s has no previous buffer stored, storing now",
2231 GST_PAD_NAME (pad->collect.pad));
2234 pad->last_buf = buf;
2237 gst_buffer_ref (last_buf);
2239 /* nasty heuristic mess to guestimate dealing with DTS/PTS,
2240 * while also trying to stay close to input ts to preserve sync,
2241 * so in DTS_METHOD_DD:
2242 * - prefer using input ts where possible
2243 * - if those detected out-of-order (*), mark as out-of-order
2244 * - if in out-of-order, then
2245 * - if duration available, use that as delta
2246 * Also mind to preserve sync between streams, and adding
2247 * durations might drift, so try to resync when we expect
2248 * input ts == (sum of durations), which is at some keyframe input frame.
2249 * - if no duration available, we are actually in serious trouble and need
2250 * to hack around that, so we fail.
2251 * To remedy failure, alternatively, in DTS_METHOD_REORDER:
2252 * - collect some buffers and re-order timestamp,
2253 * then process the oldest buffer with smallest timestamps.
2254 * This should typically compensate for some codec's handywork with ts.
2255 * ... but in case this makes ts end up where not expected, in DTS_METHOD_ASC:
2256 * - keep each ts with its buffer and still keep a list of most recent X ts,
2257 * use the (ascending) minimum of those as DTS (and the difference as ts delta),
2258 * and use this DTS as a basis to obtain a (positive) CTS offset.
2259 * This should yield exact PTS == buffer ts, but it seems not all players
2260 * out there are aware of ctts pts ...
2262 * 0.11 Phew, can we (pretty) please please sort out DTS/PTS on buffers ...
2264 if (G_LIKELY (buf) && !pad->is_out_of_order) {
2265 if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (last_buf) &&
2266 GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
2267 if ((GST_BUFFER_TIMESTAMP (buf) < GST_BUFFER_TIMESTAMP (last_buf))) {
2268 GST_DEBUG_OBJECT (qtmux, "detected out-of-order input");
2269 pad->is_out_of_order = TRUE;
2272 /* this is pretty bad */
2273 GST_WARNING_OBJECT (qtmux, "missing input timestamp");
2274 /* fall back to durations */
2275 pad->is_out_of_order = TRUE;
2279 /* would have to be some unusual input, but not impossible */
2280 if (G_UNLIKELY (qtmux->dts_method == DTS_METHOD_REORDER &&
2281 pad->is_out_of_order)) {
2285 /* if this is the first buffer, store the timestamp */
2286 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2287 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (last_buf))) {
2288 pad->first_ts = GST_BUFFER_TIMESTAMP (last_buf);
2290 GST_DEBUG_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2291 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2294 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2295 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2296 GST_TIME_ARGS (pad->first_ts));
2298 gst_qt_mux_subtract_ts (qtmux, pad, pad->first_ts);
2300 GST_BUFFER_TIMESTAMP (last_buf) = 0;
2301 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (last_buf),
2304 check_and_subtract_ts (qtmux, &GST_BUFFER_TIMESTAMP (buf), pad->first_ts);
2305 check_and_subtract_ts (qtmux, &GST_BUFFER_OFFSET_END (buf),
2310 /* fall back to duration if last buffer or
2311 * out-of-order (determined previously), otherwise use input ts */
2313 (pad->is_out_of_order && qtmux->dts_method == DTS_METHOD_DD)) {
2314 if (!GST_BUFFER_DURATION_IS_VALID (last_buf)) {
2315 /* be forgiving for some possibly last upstream flushed buffer */
2318 GST_WARNING_OBJECT (qtmux, "no duration for last buffer");
2319 /* iso spec recommends some small value, try 0 */
2322 duration = GST_BUFFER_DURATION (last_buf);
2323 /* avoid drift in sum timestamps,
2324 * so use input timestamp for suitable keyframe */
2325 if (buf && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) &&
2326 GST_BUFFER_TIMESTAMP (buf) >= pad->last_dts) {
2327 GST_DEBUG_OBJECT (qtmux, "resyncing out-of-order input to ts; "
2328 "replacing %" GST_TIME_FORMAT " by %" GST_TIME_FORMAT,
2329 GST_TIME_ARGS (pad->last_dts + duration),
2330 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2331 duration = GST_BUFFER_TIMESTAMP (buf) - pad->last_dts;
2334 } else if (qtmux->dts_method != DTS_METHOD_ASC) {
2335 duration = GST_BUFFER_TIMESTAMP (buf) - GST_BUFFER_TIMESTAMP (last_buf);
2339 g_assert (qtmux->dts_method == DTS_METHOD_ASC);
2340 if (!qtmux->guess_pts)
2343 /* add timestamp to queue; keeps in descending order */
2344 gst_qt_mux_push_ts (qtmux, pad, GST_BUFFER_TIMESTAMP (last_buf));
2345 /* chuck out smallest/last one if we have enough */
2346 if (G_LIKELY (pad->ts_n_entries > QTMUX_NO_OF_TS))
2347 pad->ts_n_entries--;
2348 /* peek the now smallest timestamp */
2349 ts = pad->ts_entries[pad->ts_n_entries - 1];
2350 /* these tails are expected to be (strictly) ascending with
2351 * large enough history */
2352 GST_DEBUG_OBJECT (qtmux, "ASC method; base timestamp %" GST_TIME_FORMAT,
2353 GST_TIME_ARGS (ts));
2354 if (ts >= pad->last_dts) {
2355 duration = ts - pad->last_dts;
2357 /* fallback to previous value, negative ct offset might handle */
2358 GST_WARNING_OBJECT (qtmux, "unexpected decrease in timestamp");
2361 /* arrange for small non-zero duration/delta << expected frame time */
2362 ts = gst_util_uint64_scale (10, GST_SECOND,
2363 atom_trak_get_timescale (pad->trak));
2364 duration = MAX (duration, ts);
2367 /* for computing the avg bitrate */
2368 if (G_LIKELY (last_buf)) {
2369 pad->total_bytes += gst_buffer_get_size (last_buf);
2370 pad->total_duration += duration;
2373 gst_buffer_replace (&pad->last_buf, buf);
2375 last_dts = gst_util_uint64_scale_round (pad->last_dts,
2376 atom_trak_get_timescale (pad->trak), GST_SECOND);
2378 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2379 if (pad->sample_size && !qtmux->fragment_sequence) {
2380 /* Constant size packets: usually raw audio (with many samples per
2381 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2383 sample_size = pad->sample_size;
2384 if (gst_buffer_get_size (last_buf) % sample_size != 0)
2385 goto fragmented_sample;
2386 /* note: qt raw audio storage warps it implicitly into a timewise
2387 * perfect stream, discarding buffer times */
2388 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2389 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2390 atom_trak_get_timescale (pad->trak), GST_SECOND);
2392 nsamples = gst_buffer_get_size (last_buf) / sample_size;
2394 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2396 /* timescale = samplerate */
2397 scaled_duration = 1;
2398 pad->last_dts += duration * nsamples;
2401 sample_size = gst_buffer_get_size (last_buf);
2402 if (pad->have_dts) {
2404 pad->last_dts = GST_BUFFER_OFFSET_END (last_buf);
2405 if ((gint64) (pad->last_dts) < 0) {
2406 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2407 atom_trak_get_timescale (pad->trak), GST_SECOND);
2409 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2410 atom_trak_get_timescale (pad->trak), GST_SECOND);
2412 scaled_duration = scaled_dts - last_dts;
2413 last_dts = scaled_dts;
2415 /* first convert intended timestamp (in GstClockTime resolution) to
2416 * trak timescale, then derive delta;
2417 * this ensures sums of (scale)delta add up to converted timestamp,
2418 * which only deviates at most 1/scale from timestamp itself */
2419 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2420 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2421 pad->last_dts += duration;
2424 chunk_offset = qtmux->mdat_size;
2426 GST_LOG_OBJECT (qtmux,
2427 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2428 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2429 GST_LOG_OBJECT (qtmux,
2430 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2431 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2432 nsamples, scaled_duration, sample_size, chunk_offset);
2434 /* might be a sync sample */
2436 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2437 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2438 GST_PAD_NAME (pad->collect.pad));
2442 /* optionally calculate ctts entry values
2443 * (if composition-time expected different from decoding-time) */
2444 /* really not recommended:
2445 * - decoder typically takes care of dts/pts issues
2446 * - in case of out-of-order, dts may only be determined as above
2447 * (e.g. sum of duration), which may be totally different from
2448 * buffer timestamps in case of multiple segment, non-perfect streams
2449 * (and just perhaps maybe with some luck segment_to_running_time
2450 * or segment_to_media_time might get near to it) */
2451 if ((pad->have_dts || qtmux->guess_pts)) {
2454 pts = qtmux->dts_method == DTS_METHOD_REORDER ?
2455 GST_BUFFER_OFFSET_END (last_buf) : GST_BUFFER_TIMESTAMP (last_buf);
2456 pts = gst_util_uint64_scale_round (pts,
2457 atom_trak_get_timescale (pad->trak), GST_SECOND);
2458 pts_offset = (gint64) (pts - last_dts);
2460 GST_LOG_OBJECT (qtmux, "Adding ctts entry for pad %s: %" G_GINT64_FORMAT,
2461 GST_PAD_NAME (pad->collect.pad), pts_offset);
2465 * Each buffer starts a new chunk, so we can assume the buffer
2466 * duration is the chunk duration
2468 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2469 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2470 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2471 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2472 qtmux->longest_chunk = duration;
2475 /* now we go and register this buffer/sample all over */
2476 /* note that a new chunk is started each time (not fancy but works) */
2477 if (qtmux->moov_recov_file) {
2478 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2479 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2480 do_pts, pts_offset)) {
2481 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2482 "recovery file, disabling recovery");
2483 fclose (qtmux->moov_recov_file);
2484 qtmux->moov_recov_file = NULL;
2489 gst_buffer_unref (buf);
2491 if (qtmux->fragment_sequence) {
2492 /* ensure that always sync samples are marked as such */
2493 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2494 buf == NULL, nsamples, last_dts, (gint32) scaled_duration, sample_size,
2495 !pad->sync || sync, pts_offset);
2497 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
2498 sample_size, chunk_offset, sync, pts_offset);
2499 ret = gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2503 if (G_UNLIKELY (drain && qtmux->dts_method == DTS_METHOD_REORDER &&
2504 ret == GST_FLOW_OK)) {
2515 gst_buffer_unref (buf);
2516 gst_buffer_unref (last_buf);
2517 return GST_FLOW_ERROR;
2521 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2522 ("Received buffer without timestamp/duration. "
2523 "Using e.g. dts-method=reorder might help."));
2528 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2529 ("DTS method failed to re-order timestamps."));
2534 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2535 ("Selected DTS method also needs PTS enabled."));
2540 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2541 ("Audio buffer contains fragmented sample."));
2546 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2547 ("format wasn't negotiated before buffer flow on pad %s",
2548 GST_PAD_NAME (pad->collect.pad)));
2550 gst_buffer_unref (buf);
2551 return GST_FLOW_NOT_NEGOTIATED;
2555 static GstFlowReturn
2556 gst_qt_mux_handle_buffer (GstCollectPads * pads, GstCollectData * cdata,
2557 GstBuffer * buf, gpointer user_data)
2559 GstFlowReturn ret = GST_FLOW_OK;
2560 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2561 GstQTPad *best_pad = NULL;
2562 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2564 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2565 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2568 qtmux->state = GST_QT_MUX_STATE_DATA;
2571 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2572 return GST_FLOW_EOS;
2574 best_pad = (GstQTPad *) cdata;
2576 /* clipping already converted to running time */
2577 if (best_pad != NULL) {
2579 best_time = GST_BUFFER_TIMESTAMP (buf);
2580 GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2581 GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2582 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2584 ret = gst_qt_mux_stop_file (qtmux);
2585 if (ret == GST_FLOW_OK) {
2586 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2587 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2590 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2591 gst_flow_get_name (ret));
2593 qtmux->state = GST_QT_MUX_STATE_EOS;
2600 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2602 GstStructure *structure = (GstStructure *) user_data;
2603 const GValue *other = gst_structure_id_get_value (structure, field_id);
2606 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2610 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2613 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2614 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2616 return gst_structure_foreach (sub_s, check_field, sup_s);
2620 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2622 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2623 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2624 GstQTPad *qtpad = NULL;
2625 GstStructure *structure;
2626 const gchar *mimetype;
2627 gint rate, channels;
2628 const GValue *value = NULL;
2629 const GstBuffer *codec_data = NULL;
2630 GstQTMuxFormat format;
2631 AudioSampleEntry entry = { 0, };
2632 AtomInfo *ext_atom = NULL;
2633 gint constant_size = 0;
2634 const gchar *stream_format;
2636 /* find stream data */
2637 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2640 qtpad->prepare_buf_func = NULL;
2642 /* does not go well to renegotiate stream mid-way, unless
2643 * the old caps are a subset of the new one (this means upstream
2644 * added more info to the caps, as both should be 'fixed' caps) */
2645 if (qtpad->fourcc) {
2646 GstCaps *current_caps;
2648 current_caps = gst_pad_get_current_caps (pad);
2649 g_assert (caps != NULL);
2651 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2652 gst_caps_unref (current_caps);
2653 goto refuse_renegotiation;
2655 GST_DEBUG_OBJECT (qtmux,
2656 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2657 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2658 gst_caps_unref (current_caps);
2661 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2662 GST_DEBUG_PAD_NAME (pad), caps);
2664 format = qtmux_klass->format;
2665 structure = gst_caps_get_structure (caps, 0);
2666 mimetype = gst_structure_get_name (structure);
2669 if (!gst_structure_get_int (structure, "channels", &channels) ||
2670 !gst_structure_get_int (structure, "rate", &rate)) {
2675 value = gst_structure_get_value (structure, "codec_data");
2677 codec_data = gst_value_get_buffer (value);
2679 qtpad->is_out_of_order = FALSE;
2680 qtpad->have_dts = FALSE;
2682 /* set common properties */
2683 entry.sample_rate = rate;
2684 entry.channels = channels;
2686 entry.sample_size = 16;
2687 /* this is the typical compressed case */
2688 if (format == GST_QT_MUX_FORMAT_QT) {
2690 entry.compression_id = -2;
2693 /* now map onto a fourcc, and some extra properties */
2694 if (strcmp (mimetype, "audio/mpeg") == 0) {
2695 gint mpegversion = 0;
2698 gst_structure_get_int (structure, "mpegversion", &mpegversion);
2699 switch (mpegversion) {
2701 gst_structure_get_int (structure, "layer", &layer);
2705 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2706 if (format == GST_QT_MUX_FORMAT_QT)
2707 entry.fourcc = FOURCC__mp3;
2709 entry.fourcc = FOURCC_mp4a;
2711 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2712 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2713 qtpad->max_bitrate);
2715 entry.samples_per_packet = 1152;
2716 entry.bytes_per_sample = 2;
2722 /* check stream-format */
2723 stream_format = gst_structure_get_string (structure, "stream-format");
2724 if (stream_format) {
2725 if (strcmp (stream_format, "raw") != 0) {
2726 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2727 "please use 'raw'", stream_format);
2731 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2735 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
2736 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2740 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
2741 /* warn if not Low Complexity profile */
2744 GST_WARNING_OBJECT (qtmux,
2745 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2749 entry.fourcc = FOURCC_mp4a;
2751 if (format == GST_QT_MUX_FORMAT_QT)
2752 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2753 qtpad->avg_bitrate, qtpad->max_bitrate);
2756 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2757 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2758 qtpad->max_bitrate);
2763 } else if (strcmp (mimetype, "audio/AMR") == 0) {
2764 entry.fourcc = FOURCC_samr;
2765 entry.sample_size = 16;
2766 entry.samples_per_packet = 160;
2767 entry.bytes_per_sample = 2;
2768 ext_atom = build_amr_extension ();
2769 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2770 entry.fourcc = FOURCC_sawb;
2771 entry.sample_size = 16;
2772 entry.samples_per_packet = 320;
2773 entry.bytes_per_sample = 2;
2774 ext_atom = build_amr_extension ();
2775 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
2778 gst_audio_info_init (&info);
2779 if (!gst_audio_info_from_caps (&info, caps))
2782 /* spec has no place for a distinction in these */
2783 if (info.finfo->width != info.finfo->depth) {
2784 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2788 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
2789 if (info.finfo->endianness == G_LITTLE_ENDIAN)
2790 entry.fourcc = FOURCC_sowt;
2791 else if (info.finfo->endianness == G_BIG_ENDIAN)
2792 entry.fourcc = FOURCC_twos;
2793 /* maximum backward compatibility; only new version for > 16 bit */
2794 if (info.finfo->depth <= 16)
2796 /* not compressed in any case */
2797 entry.compression_id = 0;
2798 /* QT spec says: max at 16 bit even if sample size were actually larger,
2799 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2800 entry.sample_size = info.finfo->depth;
2801 entry.bytes_per_sample = info.finfo->depth / 8;
2802 entry.samples_per_packet = 1;
2803 entry.bytes_per_packet = info.finfo->depth / 8;
2804 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
2806 if (info.finfo->width == 8 && info.finfo->depth == 8) {
2807 /* fall back to old 8-bit version */
2808 entry.fourcc = FOURCC_raw_;
2810 entry.compression_id = 0;
2811 entry.sample_size = 8;
2813 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2817 constant_size = (info.finfo->depth / 8) * info.channels;
2818 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2819 entry.fourcc = FOURCC_alaw;
2820 entry.samples_per_packet = 1023;
2821 entry.bytes_per_sample = 2;
2822 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2823 entry.fourcc = FOURCC_ulaw;
2824 entry.samples_per_packet = 1023;
2825 entry.bytes_per_sample = 2;
2826 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2828 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2829 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2832 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2834 entry.fourcc = MS_WAVE_FOURCC (0x11);
2835 /* 4 byte header per channel (including one sample). 2 samples per byte
2836 remaining. Simplifying gives the following (samples per block per
2838 entry.samples_per_packet = 2 * blocksize / channels - 7;
2839 entry.bytes_per_sample = 2;
2841 entry.bytes_per_frame = blocksize;
2842 entry.bytes_per_packet = blocksize / channels;
2843 /* ADPCM has constant size packets */
2845 /* TODO: I don't really understand why this helps, but it does! Constant
2846 * size and compression_id of -2 seem to be incompatible, and other files
2847 * in the wild use this too. */
2848 entry.compression_id = -1;
2850 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2851 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2852 GstBuffer *codec_config;
2856 entry.fourcc = FOURCC_alac;
2857 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
2858 /* let's check if codec data already comes with 'alac' atom prefix */
2859 if (!codec_data || (len = map.size) < 28) {
2860 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2861 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2864 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
2867 gst_buffer_copy_region ((GstBuffer *) codec_data, 0, 8, len);
2869 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2871 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
2873 /* does not look good, but perhaps some trailing unneeded stuff */
2874 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2876 if (format == GST_QT_MUX_FORMAT_QT)
2877 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2879 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2880 /* set some more info */
2881 gst_buffer_map (codec_config, &map, GST_MAP_READ);
2882 entry.bytes_per_sample = 2;
2883 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
2884 gst_buffer_unmap (codec_config, &map);
2885 gst_buffer_unref (codec_config);
2891 /* ok, set the pad info accordingly */
2892 qtpad->fourcc = entry.fourcc;
2893 qtpad->sample_size = constant_size;
2894 atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2895 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2896 ext_atom, constant_size);
2898 gst_object_unref (qtmux);
2904 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2905 GST_PAD_NAME (pad), caps);
2906 gst_object_unref (qtmux);
2909 refuse_renegotiation:
2911 GST_WARNING_OBJECT (qtmux,
2912 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2913 GST_PAD_NAME (pad), caps);
2914 gst_object_unref (qtmux);
2919 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2921 adjust_rate (guint64 rate)
2926 while (rate >= 10000)
2932 return (guint32) rate;
2936 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2938 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2939 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2940 GstQTPad *qtpad = NULL;
2941 GstStructure *structure;
2942 const gchar *mimetype;
2943 gint width, height, depth = -1;
2944 gint framerate_num, framerate_den;
2946 const GValue *value = NULL;
2947 const GstBuffer *codec_data = NULL;
2948 VisualSampleEntry entry = { 0, };
2949 GstQTMuxFormat format;
2950 AtomInfo *ext_atom = NULL;
2951 GList *ext_atom_list = NULL;
2952 gboolean sync = FALSE;
2953 int par_num, par_den;
2955 /* find stream data */
2956 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2959 qtpad->prepare_buf_func = NULL;
2961 /* does not go well to renegotiate stream mid-way, unless
2962 * the old caps are a subset of the new one (this means upstream
2963 * added more info to the caps, as both should be 'fixed' caps) */
2964 if (qtpad->fourcc) {
2965 GstCaps *current_caps;
2967 current_caps = gst_pad_get_current_caps (pad);
2968 g_assert (caps != NULL);
2970 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2971 gst_caps_unref (current_caps);
2972 goto refuse_renegotiation;
2974 GST_DEBUG_OBJECT (qtmux,
2975 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2976 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
2977 gst_caps_unref (current_caps);
2980 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2981 GST_DEBUG_PAD_NAME (pad), caps);
2983 format = qtmux_klass->format;
2984 structure = gst_caps_get_structure (caps, 0);
2985 mimetype = gst_structure_get_name (structure);
2987 /* required parts */
2988 if (!gst_structure_get_int (structure, "width", &width) ||
2989 !gst_structure_get_int (structure, "height", &height))
2994 /* works as a default timebase */
2995 framerate_num = 10000;
2997 gst_structure_get_fraction (structure, "framerate", &framerate_num,
2999 gst_structure_get_int (structure, "depth", &depth);
3000 value = gst_structure_get_value (structure, "codec_data");
3002 codec_data = gst_value_get_buffer (value);
3006 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
3009 qtpad->is_out_of_order = FALSE;
3011 /* bring frame numerator into a range that ensures both reasonable resolution
3012 * as well as a fair duration */
3013 rate = qtmux->trak_timescale ?
3014 qtmux->trak_timescale : adjust_rate (framerate_num);
3015 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
3018 /* set common properties */
3019 entry.width = width;
3020 entry.height = height;
3021 entry.par_n = par_num;
3022 entry.par_d = par_den;
3023 /* should be OK according to qt and iso spec, override if really needed */
3024 entry.color_table_id = -1;
3025 entry.frame_count = 1;
3028 /* sync entries by default */
3031 /* now map onto a fourcc, and some extra properties */
3032 if (strcmp (mimetype, "video/x-raw") == 0) {
3033 const gchar *format;
3035 const GstVideoFormatInfo *vinfo;
3037 format = gst_structure_get_string (structure, "format");
3038 fmt = gst_video_format_from_string (format);
3039 vinfo = gst_video_format_get_info (fmt);
3042 case GST_VIDEO_FORMAT_UYVY:
3045 entry.fourcc = FOURCC_2vuy;
3046 entry.depth = depth;
3050 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
3051 entry.fourcc = FOURCC_raw_;
3052 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
3057 } else if (strcmp (mimetype, "video/x-h263") == 0) {
3059 if (format == GST_QT_MUX_FORMAT_QT)
3060 entry.fourcc = FOURCC_h263;
3062 entry.fourcc = FOURCC_s263;
3063 ext_atom = build_h263_extension ();
3064 if (ext_atom != NULL)
3065 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3066 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
3067 strcmp (mimetype, "video/mpeg") == 0) {
3070 if (strcmp (mimetype, "video/x-divx") == 0) {
3071 gst_structure_get_int (structure, "divxversion", &version);
3072 version = version == 5 ? 1 : 0;
3074 gst_structure_get_int (structure, "mpegversion", &version);
3075 version = version == 4 ? 1 : 0;
3078 entry.fourcc = FOURCC_mp4v;
3080 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
3081 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
3082 qtpad->max_bitrate);
3083 if (ext_atom != NULL)
3084 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3086 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
3087 "output might not play in Apple QuickTime (try global-headers?)");
3089 } else if (strcmp (mimetype, "video/x-h264") == 0) {
3090 /* check if we accept these caps */
3091 if (gst_structure_has_field (structure, "stream-format")) {
3092 const gchar *format;
3093 const gchar *alignment;
3095 format = gst_structure_get_string (structure, "stream-format");
3096 alignment = gst_structure_get_string (structure, "alignment");
3098 if (strcmp (format, "avc") != 0 || alignment == NULL ||
3099 strcmp (alignment, "au") != 0) {
3100 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
3101 "avc format with AU aligned samples");
3105 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
3110 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
3114 entry.fourcc = FOURCC_avc1;
3115 if (qtpad->avg_bitrate == 0) {
3116 gint avg_bitrate = 0;
3117 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
3118 qtpad->avg_bitrate = avg_bitrate;
3120 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
3121 if (ext_atom != NULL)
3122 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3123 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
3124 if (ext_atom != NULL)
3125 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3126 } else if (strcmp (mimetype, "video/x-svq") == 0) {
3128 const GstBuffer *seqh = NULL;
3129 const GValue *seqh_value;
3132 gst_structure_get_int (structure, "svqversion", &version);
3134 entry.fourcc = FOURCC_SVQ3;
3138 seqh_value = gst_structure_get_value (structure, "seqh");
3140 seqh = gst_value_get_buffer (seqh_value);
3141 ext_atom = build_SMI_atom (seqh);
3143 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3146 /* we need to add the gamma anyway because quicktime might crash
3147 * when it doesn't find it */
3148 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
3149 /* it seems that using 0 here makes it ignored */
3152 ext_atom = build_gama_atom (gamma);
3154 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
3156 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
3157 "a bug at http://bugzilla.gnome.org", version);
3159 } else if (strcmp (mimetype, "video/x-dv") == 0) {
3161 gboolean pal = TRUE;
3164 if (framerate_num != 25 || framerate_den != 1)
3166 gst_structure_get_int (structure, "dvversion", &version);
3167 /* fall back to typical one */
3173 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
3175 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
3179 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
3181 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
3184 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
3187 } else if (strcmp (mimetype, "image/jpeg") == 0) {
3188 entry.fourcc = FOURCC_jpeg;
3190 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
3191 strcmp (mimetype, "image/x-jpc") == 0) {
3192 const gchar *colorspace;
3193 const GValue *cmap_array;
3194 const GValue *cdef_array;
3198 if (strcmp (mimetype, "image/x-jpc") == 0) {
3199 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
3202 gst_structure_get_int (structure, "num-components", &ncomp);
3203 gst_structure_get_int (structure, "fields", &fields);
3204 cmap_array = gst_structure_get_value (structure, "component-map");
3205 cdef_array = gst_structure_get_value (structure, "channel-definitions");
3208 entry.fourcc = FOURCC_mjp2;
3211 colorspace = gst_structure_get_string (structure, "colorspace");
3214 build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
3215 cmap_array, cdef_array)) != NULL) {
3216 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3218 ext_atom = build_fiel_extension (fields);
3220 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3222 ext_atom = build_jp2x_extension (codec_data);
3224 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
3226 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
3229 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
3230 entry.fourcc = FOURCC_VP80;
3232 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
3233 entry.fourcc = FOURCC_drac;
3234 qtpad->have_dts = TRUE;
3235 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
3238 gst_structure_get_uint (structure, "format", &fourcc);
3239 entry.fourcc = fourcc;
3240 qtpad->have_dts = TRUE;
3241 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
3244 gst_structure_get_uint (structure, "format", &fourcc);
3245 entry.fourcc = fourcc;
3246 qtpad->have_dts = TRUE;
3252 /* ok, set the pad info accordingly */
3253 qtpad->fourcc = entry.fourcc;
3255 atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
3258 gst_object_unref (qtmux);
3264 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3265 GST_PAD_NAME (pad), caps);
3266 gst_object_unref (qtmux);
3269 refuse_renegotiation:
3271 GST_WARNING_OBJECT (qtmux,
3272 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
3274 gst_object_unref (qtmux);
3280 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
3281 GstEvent * event, gpointer user_data)
3284 guint32 avg_bitrate = 0, max_bitrate = 0;
3285 GstPad *pad = data->pad;
3286 gboolean ret = TRUE;
3288 qtmux = GST_QT_MUX_CAST (user_data);
3289 switch (GST_EVENT_TYPE (event)) {
3290 case GST_EVENT_CAPS:
3293 GstQTPad *collect_pad;
3295 gst_event_parse_caps (event, &caps);
3297 /* find stream data */
3298 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
3299 g_assert (collect_pad);
3300 g_assert (collect_pad->set_caps);
3302 ret = collect_pad->set_caps (pad, caps);
3303 gst_event_unref (event);
3307 case GST_EVENT_TAG:{
3309 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
3310 GstTagMergeMode mode;
3312 GST_OBJECT_LOCK (qtmux);
3313 mode = gst_tag_setter_get_tag_merge_mode (setter);
3315 gst_event_parse_tag (event, &list);
3316 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
3317 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
3319 gst_tag_setter_merge_tags (setter, list, mode);
3320 GST_OBJECT_UNLOCK (qtmux);
3322 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
3323 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
3324 GstQTPad *qtpad = gst_pad_get_element_private (pad);
3327 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
3328 qtpad->avg_bitrate = avg_bitrate;
3329 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
3330 qtpad->max_bitrate = max_bitrate;
3333 gst_event_unref (event);
3343 return gst_collect_pads_event_default (pads, data, event, FALSE);
3349 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
3351 GstQTMux *mux = GST_QT_MUX_CAST (element);
3354 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
3356 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
3357 GstQTPad *qtpad = (GstQTPad *) walk->data;
3358 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
3359 if (qtpad->collect.pad == pad) {
3360 /* this is it, remove */
3361 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
3362 gst_element_remove_pad (element, pad);
3367 gst_collect_pads_remove_pad (mux->collect, pad);
3371 gst_qt_mux_request_new_pad (GstElement * element,
3372 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
3374 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
3375 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3376 GstQTPad *collect_pad;
3382 if (templ->direction != GST_PAD_SINK)
3383 goto wrong_direction;
3385 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3388 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
3390 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
3391 name = g_strdup (req_name);
3393 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
3395 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
3397 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
3398 name = g_strdup (req_name);
3400 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
3403 goto wrong_template;
3405 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3407 /* create pad and add to collections */
3408 newpad = gst_pad_new_from_template (templ, name);
3410 collect_pad = (GstQTPad *)
3411 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
3412 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), TRUE);
3414 gst_qt_mux_pad_reset (collect_pad);
3415 collect_pad->trak = atom_trak_new (qtmux->context);
3416 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3418 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3420 /* set up pad functions */
3422 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps);
3424 collect_pad->set_caps = GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps);
3426 gst_pad_set_active (newpad, TRUE);
3427 gst_element_add_pad (element, newpad);
3434 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3439 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3444 GST_WARNING_OBJECT (qtmux, "This is not our template!");
3450 gst_qt_mux_get_property (GObject * object,
3451 guint prop_id, GValue * value, GParamSpec * pspec)
3453 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3455 GST_OBJECT_LOCK (qtmux);
3457 case PROP_MOVIE_TIMESCALE:
3458 g_value_set_uint (value, qtmux->timescale);
3460 case PROP_TRAK_TIMESCALE:
3461 g_value_set_uint (value, qtmux->trak_timescale);
3464 g_value_set_boolean (value, qtmux->guess_pts);
3466 case PROP_DTS_METHOD:
3467 g_value_set_enum (value, qtmux->dts_method);
3469 case PROP_FAST_START:
3470 g_value_set_boolean (value, qtmux->fast_start);
3472 case PROP_FAST_START_TEMP_FILE:
3473 g_value_set_string (value, qtmux->fast_start_file_path);
3475 case PROP_MOOV_RECOV_FILE:
3476 g_value_set_string (value, qtmux->moov_recov_file_path);
3478 case PROP_FRAGMENT_DURATION:
3479 g_value_set_uint (value, qtmux->fragment_duration);
3481 case PROP_STREAMABLE:
3482 g_value_set_boolean (value, qtmux->streamable);
3485 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3488 GST_OBJECT_UNLOCK (qtmux);
3492 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3496 g_free (qtmux->fast_start_file_path);
3497 qtmux->fast_start_file_path = NULL;
3499 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3500 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3505 gst_qt_mux_set_property (GObject * object,
3506 guint prop_id, const GValue * value, GParamSpec * pspec)
3508 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3510 GST_OBJECT_LOCK (qtmux);
3512 case PROP_MOVIE_TIMESCALE:
3513 qtmux->timescale = g_value_get_uint (value);
3515 case PROP_TRAK_TIMESCALE:
3516 qtmux->trak_timescale = g_value_get_uint (value);
3519 qtmux->guess_pts = g_value_get_boolean (value);
3521 case PROP_DTS_METHOD:
3522 qtmux->dts_method = g_value_get_enum (value);
3524 case PROP_FAST_START:
3525 qtmux->fast_start = g_value_get_boolean (value);
3527 case PROP_FAST_START_TEMP_FILE:
3528 g_free (qtmux->fast_start_file_path);
3529 qtmux->fast_start_file_path = g_value_dup_string (value);
3530 /* NULL means to generate a random one */
3531 if (!qtmux->fast_start_file_path) {
3532 gst_qt_mux_generate_fast_start_file_path (qtmux);
3535 case PROP_MOOV_RECOV_FILE:
3536 g_free (qtmux->moov_recov_file_path);
3537 qtmux->moov_recov_file_path = g_value_dup_string (value);
3539 case PROP_FRAGMENT_DURATION:
3540 qtmux->fragment_duration = g_value_get_uint (value);
3542 case PROP_STREAMABLE:
3543 qtmux->streamable = g_value_get_boolean (value);
3546 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3549 GST_OBJECT_UNLOCK (qtmux);
3552 static GstStateChangeReturn
3553 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3555 GstStateChangeReturn ret;
3556 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3558 switch (transition) {
3559 case GST_STATE_CHANGE_NULL_TO_READY:
3561 case GST_STATE_CHANGE_READY_TO_PAUSED:
3562 gst_collect_pads_start (qtmux->collect);
3563 qtmux->state = GST_QT_MUX_STATE_STARTED;
3565 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3567 case GST_STATE_CHANGE_PAUSED_TO_READY:
3568 gst_collect_pads_stop (qtmux->collect);
3574 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3576 switch (transition) {
3577 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3579 case GST_STATE_CHANGE_PAUSED_TO_READY:
3580 gst_qt_mux_reset (qtmux, TRUE);
3582 case GST_STATE_CHANGE_READY_TO_NULL:
3592 gst_qt_mux_register (GstPlugin * plugin)
3594 GTypeInfo typeinfo = {
3595 sizeof (GstQTMuxClass),
3596 (GBaseInitFunc) gst_qt_mux_base_init,
3598 (GClassInitFunc) gst_qt_mux_class_init,
3603 (GInstanceInitFunc) gst_qt_mux_init,
3605 static const GInterfaceInfo tag_setter_info = {
3608 static const GInterfaceInfo tag_xmp_writer_info = {
3612 GstQTMuxFormat format;
3613 GstQTMuxClassParams *params;
3616 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3618 GST_LOG ("Registering muxers");
3621 GstQTMuxFormatProp *prop;
3623 prop = &gst_qt_mux_format_list[i];
3624 format = prop->format;
3625 if (format == GST_QT_MUX_FORMAT_NONE)
3628 /* create a cache for these properties */
3629 params = g_new0 (GstQTMuxClassParams, 1);
3630 params->prop = prop;
3631 params->src_caps = gst_static_caps_get (&prop->src_caps);
3632 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3633 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3635 /* create the type now */
3636 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3638 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3639 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3640 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
3641 &tag_xmp_writer_info);
3643 if (!gst_element_register (plugin, prop->name, prop->rank, type))
3649 GST_LOG ("Finished registering muxers");
3651 /* FIXME: ideally classification tag should be added and
3652 registered in gstreamer core gsttaglist
3655 GST_LOG ("Registering tags");
3657 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3658 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3659 gst_tag_merge_use_first);
3661 GST_LOG ("Finished registering tags");