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>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
21 * Unless otherwise indicated, Source Code is licensed under MIT license.
22 * See further explanation attached in License Statement (distributed in the file
25 * Permission is hereby granted, free of charge, to any person obtaining a copy of
26 * this software and associated documentation files (the "Software"), to deal in
27 * the Software without restriction, including without limitation the rights to
28 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
29 * of the Software, and to permit persons to whom the Software is furnished to do
30 * so, subject to the following conditions:
32 * The above copyright notice and this permission notice shall be included in all
33 * copies or substantial portions of the Software.
35 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
46 * SECTION:element-qtmux
47 * @short_description: Muxer for quicktime(.mov) files
49 * This element merges streams (audio and video) into QuickTime(.mov) files.
51 * The following background intends to explain why various similar muxers
52 * are present in this plugin.
54 * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
55 * QuickTime file format specification</ulink> served as basis for the MP4 file
56 * format specification (mp4mux), and as such the QuickTime file structure is
57 * nearly identical to the so-called ISO Base Media file format defined in
58 * ISO 14496-12 (except for some media specific parts).
59 * In turn, the latter ISO Base Media format was further specialized as a
60 * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
61 * and in various 3GPP(2) specs (gppmux).
62 * The fragmented file features defined (only) in ISO Base Media are used by
63 * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
66 * <title>Example pipelines</title>
68 * gst-launch v4l2src num-buffers=500 ! video/x-raw-yuv,width=320,height=240 ! ffmpegcolorspace ! qtmux ! filesink location=video.mov
70 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
73 * Last reviewed on 2010-12-03
84 #include <glib/gstdio.h>
87 #include <gst/base/gstcollectpads.h>
89 #include <sys/types.h>
91 #include <io.h> /* lseek, open, close, read */
93 #define lseek _lseeki64
99 #define ftruncate g_win32_ftruncate
106 #include "gstqtmux.h"
108 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
109 #define GST_CAT_DEFAULT gst_qt_mux_debug
111 /* QTMux signals and args */
122 PROP_MOVIE_TIMESCALE,
126 PROP_FAST_START_TEMP_FILE,
127 PROP_MOOV_RECOV_FILE,
128 PROP_FRAGMENT_DURATION,
132 /* some spare for header size as well */
133 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
134 #define MAX_TOLERATED_LATENESS (GST_SECOND / 10)
136 #define DEFAULT_LARGE_FILE FALSE
137 #define DEFAULT_MOVIE_TIMESCALE 1000
138 #define DEFAULT_TRAK_TIMESCALE 0
139 #define DEFAULT_DO_CTTS FALSE
140 #define DEFAULT_FAST_START FALSE
141 #define DEFAULT_FAST_START_TEMP_FILE NULL
142 #define DEFAULT_MOOV_RECOV_FILE NULL
143 #define DEFAULT_FRAGMENT_DURATION 0
144 #define DEFAULT_STREAMABLE FALSE
147 static void gst_qt_mux_finalize (GObject * object);
149 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
150 GstStateChange transition);
152 /* property functions */
153 static void gst_qt_mux_set_property (GObject * object,
154 guint prop_id, const GValue * value, GParamSpec * pspec);
155 static void gst_qt_mux_get_property (GObject * object,
156 guint prop_id, GValue * value, GParamSpec * pspec);
159 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
160 GstPadTemplate * templ, const gchar * name);
161 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
164 static gboolean gst_qt_mux_sink_event (GstPad * pad, GstEvent * event);
166 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
168 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
171 static GstElementClass *parent_class = NULL;
174 gst_qt_mux_base_init (gpointer g_class)
176 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
177 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
178 GstQTMuxClassParams *params;
179 GstPadTemplate *videosinktempl, *audiosinktempl, *srctempl;
180 gchar *longname, *description;
183 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
184 GST_QT_MUX_PARAMS_QDATA);
185 g_assert (params != NULL);
187 /* construct the element details struct */
188 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
189 description = g_strdup_printf ("Multiplex audio and video into a %s file",
190 params->prop->long_name);
191 gst_element_class_set_details_simple (element_class, longname,
192 "Codec/Muxer", description,
193 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
195 g_free (description);
198 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
199 GST_PAD_ALWAYS, params->src_caps);
200 gst_element_class_add_pad_template (element_class, srctempl);
202 if (params->audio_sink_caps) {
203 audiosinktempl = gst_pad_template_new ("audio_%d",
204 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
205 gst_element_class_add_pad_template (element_class, audiosinktempl);
208 if (params->video_sink_caps) {
209 videosinktempl = gst_pad_template_new ("video_%d",
210 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
211 gst_element_class_add_pad_template (element_class, videosinktempl);
214 klass->format = params->prop->format;
218 gst_qt_mux_class_init (GstQTMuxClass * klass)
220 GObjectClass *gobject_class;
221 GstElementClass *gstelement_class;
223 gobject_class = (GObjectClass *) klass;
224 gstelement_class = (GstElementClass *) klass;
226 parent_class = g_type_class_peek_parent (klass);
228 gobject_class->finalize = gst_qt_mux_finalize;
229 gobject_class->get_property = gst_qt_mux_get_property;
230 gobject_class->set_property = gst_qt_mux_set_property;
232 g_object_class_install_property (gobject_class, PROP_LARGE_FILE,
233 g_param_spec_boolean ("large-file", "Support for large files",
234 "Uses 64bits to some fields instead of 32bits, "
235 "providing support for large files",
236 DEFAULT_LARGE_FILE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
237 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
238 g_param_spec_uint ("movie-timescale", "Movie timescale",
239 "Timescale to use in the movie (units per second)",
240 1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
241 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
242 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
243 g_param_spec_uint ("trak-timescale", "Track timescale",
244 "Timescale to use for the tracks (units per second, 0 is automatic)",
245 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
246 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
247 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
248 g_param_spec_boolean ("presentation-time",
249 "Include presentation-time info",
250 "Calculate and include presentation/composition time "
251 "(in addition to decoding time) (use with caution)",
253 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
254 g_object_class_install_property (gobject_class, PROP_FAST_START,
255 g_param_spec_boolean ("faststart", "Format file to faststart",
256 "If the file should be formated for faststart (headers first). ",
257 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
259 g_param_spec_string ("faststart-file", "File to use for storing buffers",
260 "File that will be used temporarily to store data from the stream "
261 "when creating a faststart file. If null a filepath will be "
262 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
263 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
264 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
265 g_param_spec_string ("moov-recovery-file",
266 "File to store data for posterior moov atom recovery",
267 "File to be used to store "
268 "data for moov atom making movie file recovery possible in case "
269 "of a crash during muxing. Null for disabled. (Experimental)",
270 DEFAULT_MOOV_RECOV_FILE,
271 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
272 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
273 g_param_spec_uint ("fragment-duration", "Fragment duration",
274 "Fragment durations in ms (produce a fragmented file if > 0)",
275 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
276 2000 : DEFAULT_FRAGMENT_DURATION,
277 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
278 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
279 g_param_spec_boolean ("streamable", "Streamable",
280 "If set to true, the output should be as if it is to be streamed "
281 "and hence no indexes written or duration written.",
283 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
285 gstelement_class->request_new_pad =
286 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
287 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
288 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
292 gst_qt_mux_pad_reset (GstQTPad * qtpad)
295 qtpad->is_out_of_order = FALSE;
296 qtpad->have_dts = FALSE;
297 qtpad->sample_size = 0;
300 qtpad->first_ts = GST_CLOCK_TIME_NONE;
301 qtpad->prepare_buf_func = NULL;
302 qtpad->avg_bitrate = 0;
303 qtpad->max_bitrate = 0;
306 gst_buffer_replace (&qtpad->last_buf, NULL);
308 /* reference owned elsewhere */
312 atom_traf_free (qtpad->traf);
315 atom_array_clear (&qtpad->fragment_buffers);
317 /* reference owned elsewhere */
322 * Takes GstQTMux back to its initial state
325 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
329 qtmux->state = GST_QT_MUX_STATE_NONE;
330 qtmux->header_size = 0;
331 qtmux->mdat_size = 0;
333 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
334 qtmux->video_pads = 0;
335 qtmux->audio_pads = 0;
336 qtmux->fragment_sequence = 0;
339 atom_ftyp_free (qtmux->ftyp);
343 atom_moov_free (qtmux->moov);
347 atom_mfra_free (qtmux->mfra);
350 if (qtmux->fast_start_file) {
351 fclose (qtmux->fast_start_file);
352 g_remove (qtmux->fast_start_file_path);
353 qtmux->fast_start_file = NULL;
355 if (qtmux->moov_recov_file) {
356 fclose (qtmux->moov_recov_file);
357 qtmux->moov_recov_file = NULL;
359 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
360 AtomInfo *ainfo = (AtomInfo *) walk->data;
361 ainfo->free_func (ainfo->atom);
363 g_slist_free (qtmux->extra_atoms);
364 qtmux->extra_atoms = NULL;
366 GST_OBJECT_LOCK (qtmux);
367 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
368 GST_OBJECT_UNLOCK (qtmux);
371 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
372 GstQTPad *qtpad = (GstQTPad *) walk->data;
373 gst_qt_mux_pad_reset (qtpad);
375 /* hm, moov_free above yanked the traks away from us,
376 * so do not free, but do clear */
381 qtmux->moov = atom_moov_new (qtmux->context);
382 /* ensure all is as nice and fresh as request_new_pad would provide it */
383 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
384 GstQTPad *qtpad = (GstQTPad *) walk->data;
386 qtpad->trak = atom_trak_new (qtmux->context);
387 atom_moov_add_trak (qtmux->moov, qtpad->trak);
393 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
395 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
396 GstPadTemplate *templ;
399 templ = gst_element_class_get_pad_template (klass, "src");
400 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
401 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
402 gst_pad_set_caps (qtmux->srcpad, caps);
403 gst_caps_unref (caps);
404 gst_pad_use_fixed_caps (qtmux->srcpad);
405 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
407 qtmux->sinkpads = NULL;
408 qtmux->collect = gst_collect_pads_new ();
409 gst_collect_pads_set_function (qtmux->collect,
410 (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
412 /* properties set to default upon construction */
414 /* always need this */
416 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
418 /* internals to initial state */
419 gst_qt_mux_reset (qtmux, TRUE);
424 gst_qt_mux_finalize (GObject * object)
426 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
428 gst_qt_mux_reset (qtmux, FALSE);
430 g_free (qtmux->fast_start_file_path);
431 g_free (qtmux->moov_recov_file_path);
433 atoms_context_free (qtmux->context);
434 gst_object_unref (qtmux->collect);
436 g_slist_free (qtmux->sinkpads);
438 G_OBJECT_CLASS (parent_class)->finalize (object);
442 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
447 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
452 newbuf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buf) + 8);
453 gst_buffer_copy_metadata (newbuf, buf, GST_BUFFER_COPY_ALL);
455 GST_WRITE_UINT32_BE (GST_BUFFER_DATA (newbuf), GST_BUFFER_SIZE (newbuf));
456 GST_WRITE_UINT32_LE (GST_BUFFER_DATA (newbuf) + 4, FOURCC_jp2c);
458 memcpy (GST_BUFFER_DATA (newbuf) + 8, GST_BUFFER_DATA (buf),
459 GST_BUFFER_SIZE (buf));
460 gst_buffer_unref (buf);
466 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
467 const char *tag, const char *tag2, guint32 fourcc)
469 switch (gst_tag_get_type (tag)) {
475 if (!gst_tag_list_get_string (list, tag, &str) || !str)
477 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
478 GST_FOURCC_ARGS (fourcc), str);
479 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
488 if (!gst_tag_list_get_double (list, tag, &value))
490 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
491 GST_FOURCC_ARGS (fourcc), (gint) value);
492 atom_moov_add_uint_tag (qtmux->moov, fourcc, 21, (gint) value);
499 /* paired unsigned integers */
502 if (!(gst_tag_list_get_uint (list, tag, &value) ||
503 gst_tag_list_get_uint (list, tag2, &count)))
505 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
506 GST_FOURCC_ARGS (fourcc), value, count);
507 atom_moov_add_uint_tag (qtmux->moov, fourcc, 0,
508 value << 16 | (count & 0xFFFF));
510 /* unpaired unsigned integers */
511 if (!gst_tag_list_get_uint (list, tag, &value))
513 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
514 GST_FOURCC_ARGS (fourcc), value);
515 atom_moov_add_uint_tag (qtmux->moov, fourcc, 1, value);
520 g_assert_not_reached ();
526 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
527 const char *tag, const char *tag2, guint32 fourcc)
535 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_DATE);
537 if (!gst_tag_list_get_date (list, tag, &date) || !date)
540 year = g_date_get_year (date);
541 month = g_date_get_month (date);
542 day = g_date_get_day (date);
544 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
545 day == G_DATE_BAD_DAY) {
546 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
550 str = g_strdup_printf ("%u-%u-%u", year, month, day);
551 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
552 GST_FOURCC_ARGS (fourcc), str);
553 atom_moov_add_str_tag (qtmux->moov, fourcc, str);
558 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
559 const char *tag, const char *tag2, guint32 fourcc)
561 GValue value = { 0, };
564 GstStructure *structure;
567 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_BUFFER);
569 if (!gst_tag_list_copy_value (&value, list, tag))
572 buf = gst_value_get_buffer (&value);
576 caps = gst_buffer_get_caps (buf);
578 GST_WARNING_OBJECT (qtmux, "preview image without caps");
582 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
584 structure = gst_caps_get_structure (caps, 0);
585 if (gst_structure_has_name (structure, "image/jpeg"))
587 else if (gst_structure_has_name (structure, "image/png"))
589 gst_caps_unref (caps);
592 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
596 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
597 " -> image size %d", GST_FOURCC_ARGS (fourcc), GST_BUFFER_SIZE (buf));
598 atom_moov_add_tag (qtmux->moov, fourcc, flags, GST_BUFFER_DATA (buf),
599 GST_BUFFER_SIZE (buf));
601 g_value_unset (&value);
605 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
606 const char *tag, const char *tag2, guint32 fourcc)
611 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
612 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
614 if (!gst_tag_list_get_string (list, tag, &str) || !str)
618 if (!gst_tag_list_get_uint (list, tag2, &number))
622 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
623 GST_FOURCC_ARGS (fourcc), str);
624 atom_moov_add_3gp_str_tag (qtmux->moov, fourcc, str);
626 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
627 GST_FOURCC_ARGS (fourcc), str, number);
628 atom_moov_add_3gp_str_int_tag (qtmux->moov, fourcc, str, number);
635 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
636 const char *tag, const char *tag2, guint32 fourcc)
641 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_DATE);
643 if (!gst_tag_list_get_date (list, tag, &date) || !date)
646 year = g_date_get_year (date);
648 if (year == G_DATE_BAD_YEAR) {
649 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
653 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
654 GST_FOURCC_ARGS (fourcc), year);
655 atom_moov_add_3gp_uint_tag (qtmux->moov, fourcc, year);
659 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
660 const char *tag, const char *tag2, guint32 fourcc)
662 gdouble latitude = -360, longitude = -360, altitude = 0;
663 gchar *location = NULL;
664 guint8 *data, *ddata;
665 gint size = 0, len = 0;
666 gboolean ret = FALSE;
668 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
670 ret = gst_tag_list_get_string (list, tag, &location);
671 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
673 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
675 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
682 len = strlen (location);
685 /* role + (long, lat, alt) + body + notes */
686 size += 1 + 3 * 4 + 1 + 1;
688 data = ddata = g_malloc (size);
691 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
694 memcpy (data + 2, location, len);
695 GST_WRITE_UINT8 (data + 2 + len, 0);
698 GST_WRITE_UINT8 (data, 0);
700 GST_WRITE_UINT32_BE (data + 1, (guint32) (longitude * 65536.0));
701 GST_WRITE_UINT32_BE (data + 5, (guint32) (latitude * 65536.0));
702 GST_WRITE_UINT32_BE (data + 9, (guint32) (altitude * 65536.0));
703 /* neither astronomical body nor notes */
704 GST_WRITE_UINT16_BE (data + 13, 0);
706 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
707 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
712 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
713 const char *tag, const char *tag2, guint32 fourcc)
715 gchar *keywords = NULL;
716 guint8 *data, *ddata;
720 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
722 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
725 kwds = g_strsplit (keywords, ",", 0);
729 for (i = 0; kwds[i]; i++) {
730 /* size byte + null-terminator */
731 size += strlen (kwds[i]) + 1 + 1;
734 /* language tag + count + keywords */
737 data = ddata = g_malloc (size);
740 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
742 GST_WRITE_UINT8 (data + 2, i);
745 for (i = 0; kwds[i]; ++i) {
746 gint len = strlen (kwds[i]);
748 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
749 GST_FOURCC_ARGS (fourcc), kwds[i]);
751 GST_WRITE_UINT8 (data, len + 1);
752 memcpy (data + 1, kwds[i], len + 1);
758 atom_moov_add_3gp_tag (qtmux->moov, fourcc, ddata, size);
763 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
764 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
772 size = strlen (input);
774 if (size < 4 + 3 + 1 + 1 + 1) {
775 /* at least the minimum xxxx://y/z */
776 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
781 /* read the fourcc */
782 memcpy (&fourcc, data, 4);
786 if (strncmp (data, "://", 3) != 0) {
792 /* read the table number */
793 if (sscanf (data, "%d", &table) != 1) {
797 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
798 ", table numbers should be positive, ignoring tag", table);
802 /* find the next / */
803 while (size > 0 && data[0] != '/') {
810 g_assert (data[0] == '/');
819 /* read up the rest of the string */
820 *p_content = g_strdup (data);
821 *p_table = (guint16) table;
827 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
828 "input (%s) didn't match the expected entitycode://table/content",
835 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
836 const char *tag, const char *tag2, guint32 fourcc)
838 gchar *clsf_data = NULL;
842 gchar *content = NULL;
845 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
847 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
850 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
851 GST_FOURCC_ARGS (fourcc), clsf_data);
853 /* parse the string, format is:
854 * entityfourcc://table/content
856 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
860 size = strlen (content) + 1;
862 /* now we have everything, build the atom
863 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
864 data = g_malloc (4 + 2 + 2 + size);
865 GST_WRITE_UINT32_LE (data, entity);
866 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
867 GST_WRITE_UINT16_BE (data + 6, 0);
868 memcpy (data + 8, content, size);
871 atom_moov_add_3gp_tag (qtmux->moov, fourcc, data, 4 + 2 + 2 + size);
875 typedef void (*GstQTMuxAddTagFunc) (GstQTMux * mux, const GstTagList * list,
876 const char *tag, const char *tag2, guint32 fourcc);
879 * Struct to record mappings from gstreamer tags to fourcc codes
881 typedef struct _GstTagToFourcc
885 const gchar *gsttag2;
886 const GstQTMuxAddTagFunc func;
889 /* tag list tags to fourcc matching */
890 static const GstTagToFourcc tag_matches_mp4[] = {
891 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
892 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
893 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
894 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
895 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
896 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
897 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
898 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
899 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
900 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
901 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
902 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
903 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
904 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
905 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
906 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
907 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
908 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
909 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
910 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
911 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
912 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
913 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
914 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
915 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
916 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
917 gst_qt_mux_add_mp4_tag},
918 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
919 gst_qt_mux_add_mp4_tag},
920 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
924 static const GstTagToFourcc tag_matches_3gp[] = {
925 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
926 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
927 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
928 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
929 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
930 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
931 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
932 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
933 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
934 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
935 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
936 gst_qt_mux_add_3gp_classification},
940 /* qtdemux produces these for atoms it cannot parse */
941 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
944 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
946 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
948 /* adobe specs only have 'quicktime' and 'mp4',
949 * but I guess we can extrapolate to gpp.
950 * Keep mj2 out for now as we don't add any tags for it yet.
951 * If you have further info about xmp on these formats, please share */
952 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
955 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
957 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
958 atom_moov_add_xmp_tags (qtmux->moov, list);
960 /* for isom/mp4, it is a top level uuid atom */
961 AtomInfo *ainfo = build_uuid_xmp_atom (list);
963 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
969 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list)
971 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
974 const gchar *tag, *tag2;
975 const GstTagToFourcc *tag_matches;
977 switch (qtmux_klass->format) {
978 case GST_QT_MUX_FORMAT_3GP:
979 tag_matches = tag_matches_3gp;
981 case GST_QT_MUX_FORMAT_MJ2:
985 /* sort of iTunes style for mp4 and QT (?) */
986 tag_matches = tag_matches_mp4;
993 for (i = 0; tag_matches[i].fourcc; i++) {
994 fourcc = tag_matches[i].fourcc;
995 tag = tag_matches[i].gsttag;
996 tag2 = tag_matches[i].gsttag2;
998 g_assert (tag_matches[i].func);
999 tag_matches[i].func (qtmux, list, tag, tag2, fourcc);
1002 /* add unparsed blobs if present */
1003 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1006 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1007 for (i = 0; i < num_tags; ++i) {
1010 GstCaps *caps = NULL;
1012 val = gst_tag_list_get_value_index (list, GST_QT_DEMUX_PRIVATE_TAG, i);
1013 buf = (GstBuffer *) gst_value_get_mini_object (val);
1015 if (buf && (caps = gst_buffer_get_caps (buf))) {
1017 const gchar *style = NULL;
1019 GST_DEBUG_OBJECT (qtmux, "Found private tag %d/%d; size %d, caps %"
1020 GST_PTR_FORMAT, i, num_tags, GST_BUFFER_SIZE (buf), caps);
1021 s = gst_caps_get_structure (caps, 0);
1022 if (s && (style = gst_structure_get_string (s, "style"))) {
1023 /* try to prevent some style tag ending up into another variant
1024 * (todo: make into a list if more cases) */
1025 if ((strcmp (style, "itunes") == 0 &&
1026 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1027 (strcmp (style, "iso") == 0 &&
1028 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1029 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1030 atom_moov_add_blob_tag (qtmux->moov, GST_BUFFER_DATA (buf),
1031 GST_BUFFER_SIZE (buf));
1034 gst_caps_unref (caps);
1043 * Gets the tagsetter iface taglist and puts the known tags
1044 * into the output stream
1047 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1049 const GstTagList *tags;
1051 GST_OBJECT_LOCK (qtmux);
1052 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1053 GST_OBJECT_UNLOCK (qtmux);
1055 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1057 if (tags && !gst_tag_list_is_empty (tags)) {
1058 GstTagList *copy = gst_tag_list_copy (tags);
1060 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1061 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1062 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1063 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1065 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1066 gst_qt_mux_add_metadata_tags (qtmux, copy);
1067 gst_qt_mux_add_xmp_tags (qtmux, copy);
1068 gst_tag_list_free (copy);
1070 GST_DEBUG_OBJECT (qtmux, "No tags received");
1074 static inline GstBuffer *
1075 _gst_buffer_new_take_data (guint8 * data, guint size)
1079 buf = gst_buffer_new ();
1080 GST_BUFFER_DATA (buf) = GST_BUFFER_MALLOCDATA (buf) = data;
1081 GST_BUFFER_SIZE (buf) = size;
1086 static GstFlowReturn
1087 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1094 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1096 data = GST_BUFFER_DATA (buf);
1097 size = GST_BUFFER_SIZE (buf);
1099 GST_LOG_OBJECT (qtmux, "sending buffer size %d", size);
1101 if (mind_fast && qtmux->fast_start_file) {
1104 GST_LOG_OBJECT (qtmux, "to temporary file");
1105 ret = fwrite (data, sizeof (guint8), size, qtmux->fast_start_file);
1106 gst_buffer_unref (buf);
1112 GST_LOG_OBJECT (qtmux, "downstream");
1114 buf = gst_buffer_make_metadata_writable (buf);
1115 gst_buffer_set_caps (buf, GST_PAD_CAPS (qtmux->srcpad));
1116 res = gst_pad_push (qtmux->srcpad, buf);
1119 if (G_LIKELY (offset))
1127 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1128 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1129 return GST_FLOW_ERROR;
1134 gst_qt_mux_seek_to_beginning (FILE * f)
1137 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1139 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1140 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1143 if (fseek (f, (long) 0, SEEK_SET) != 0)
1149 static GstFlowReturn
1150 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1152 GstFlowReturn ret = GST_FLOW_OK;
1153 GstBuffer *buf = NULL;
1155 if (fflush (qtmux->fast_start_file))
1158 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1161 /* hm, this could all take a really really long time,
1162 * but there may not be another way to get moov atom first
1163 * (somehow optimize copy?) */
1164 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1165 while (ret == GST_FLOW_OK) {
1167 const int bufsize = 4096;
1169 buf = gst_buffer_new_and_alloc (bufsize);
1170 r = fread (GST_BUFFER_DATA (buf), sizeof (guint8), bufsize,
1171 qtmux->fast_start_file);
1174 GST_BUFFER_SIZE (buf) = r;
1175 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", r);
1176 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1180 gst_buffer_unref (buf);
1182 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1184 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1192 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1193 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1194 ret = GST_FLOW_ERROR;
1199 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1200 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1201 ret = GST_FLOW_ERROR;
1206 /* clear descriptor so we don't remove temp file later on,
1207 * might be possible to recover */
1208 fclose (qtmux->fast_start_file);
1209 qtmux->fast_start_file = NULL;
1215 * Sends the initial mdat atom fields (size fields and fourcc type),
1216 * the subsequent buffers are considered part of it's data.
1217 * As we can't predict the amount of data that we are going to place in mdat
1218 * we need to record the position of the size field in the stream so we can
1219 * seek back to it later and update when the streams have finished.
1221 static GstFlowReturn
1222 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1227 guint8 *data = NULL;
1230 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1231 "size %" G_GUINT64_FORMAT, size);
1233 node_header = g_malloc0 (sizeof (Atom));
1234 node_header->type = FOURCC_mdat;
1236 /* use extended size */
1237 node_header->size = 1;
1238 node_header->extended_size = 0;
1240 node_header->extended_size = size + 16;
1242 node_header->size = size + 8;
1246 if (atom_copy_data (node_header, &data, &size, &offset) == 0)
1247 goto serialize_error;
1249 buf = _gst_buffer_new_take_data (data, offset);
1250 g_free (node_header);
1252 GST_LOG_OBJECT (qtmux, "Pushing mdat start");
1253 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1258 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1259 ("Failed to serialize mdat"));
1260 return GST_FLOW_ERROR;
1265 * We get the position of the mdat size field, seek back to it
1266 * and overwrite with the real value
1268 static GstFlowReturn
1269 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1270 guint64 mdat_size, guint64 * offset)
1274 gboolean large_file;
1276 large_file = (mdat_size > MDAT_LARGE_FILE_LIMIT);
1281 /* seek and rewrite the header */
1282 event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1283 mdat_pos, GST_CLOCK_TIME_NONE, 0);
1284 gst_pad_push_event (qtmux->srcpad, event);
1287 buf = gst_buffer_new_and_alloc (sizeof (guint64));
1288 GST_WRITE_UINT64_BE (GST_BUFFER_DATA (buf), mdat_size + 16);
1292 buf = gst_buffer_new_and_alloc (16);
1293 data = GST_BUFFER_DATA (buf);
1294 GST_WRITE_UINT32_BE (data, 8);
1295 GST_WRITE_UINT32_LE (data + 4, FOURCC_free);
1296 GST_WRITE_UINT32_BE (data + 8, mdat_size + 8);
1297 GST_WRITE_UINT32_LE (data + 12, FOURCC_mdat);
1300 return gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1303 static GstFlowReturn
1304 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1307 guint64 size = 0, offset = 0;
1308 guint8 *data = NULL;
1310 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1312 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1313 goto serialize_error;
1315 buf = _gst_buffer_new_take_data (data, offset);
1317 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1318 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1323 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1324 ("Failed to serialize ftyp"));
1325 return GST_FLOW_ERROR;
1330 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1331 GstBuffer ** p_prefix)
1333 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1334 guint32 major, version;
1336 GstBuffer *prefix = NULL;
1337 AtomFTYP *ftyp = NULL;
1339 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1341 /* init and send context and ftyp based on current property state */
1342 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1343 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1344 qtmux->fast_start_file != NULL);
1345 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1352 gst_buffer_unref (prefix);
1357 static GstFlowReturn
1358 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1360 GstFlowReturn ret = GST_FLOW_OK;
1361 GstBuffer *prefix = NULL;
1363 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1365 /* init and send context and ftyp based on current property state */
1367 atom_ftyp_free (qtmux->ftyp);
1370 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1372 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1373 if (ret != GST_FLOW_OK)
1376 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1380 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1382 GstStructure *structure;
1383 GValue array = { 0 };
1384 GValue value = { 0 };
1385 GstCaps *caps = GST_PAD_CAPS (mux->srcpad);
1387 caps = gst_caps_copy (GST_PAD_CAPS (mux->srcpad));
1388 structure = gst_caps_get_structure (caps, 0);
1390 g_value_init (&array, GST_TYPE_ARRAY);
1392 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
1393 g_value_init (&value, GST_TYPE_BUFFER);
1394 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1395 gst_value_array_append_value (&array, &value);
1396 g_value_unset (&value);
1398 gst_structure_set_value (structure, "streamheader", &array);
1399 g_value_unset (&array);
1400 gst_pad_set_caps (mux->srcpad, caps);
1401 gst_caps_unref (caps);
1405 gst_qt_mux_configure_moov (GstQTMux * qtmux, guint32 * _timescale)
1407 gboolean large_file, fragmented;
1410 GST_OBJECT_LOCK (qtmux);
1411 timescale = qtmux->timescale;
1412 large_file = qtmux->large_file;
1413 fragmented = qtmux->fragment_sequence > 0;
1414 GST_OBJECT_UNLOCK (qtmux);
1416 /* inform lower layers of our property wishes, and determine duration.
1417 * Let moov take care of this using its list of traks;
1418 * so that released pads are also included */
1419 GST_DEBUG_OBJECT (qtmux, "Large file support: %d", large_file);
1420 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1422 atom_moov_update_timescale (qtmux->moov, timescale);
1423 atom_moov_set_64bits (qtmux->moov, large_file);
1424 atom_moov_set_fragmented (qtmux->moov, fragmented);
1426 atom_moov_update_duration (qtmux->moov);
1429 *_timescale = timescale;
1432 static GstFlowReturn
1433 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset, gboolean mind_fast)
1435 guint64 offset = 0, size = 0;
1438 GstFlowReturn ret = GST_FLOW_OK;
1440 /* serialize moov */
1443 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1444 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1445 goto serialize_error;
1447 buf = _gst_buffer_new_take_data (data, offset);
1448 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1449 gst_qt_mux_set_header_on_caps (qtmux, buf);
1450 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1457 return GST_FLOW_ERROR;
1461 /* either calculates size of extra atoms or pushes them */
1462 static GstFlowReturn
1463 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1467 guint64 loffset = 0, size = 0;
1469 GstFlowReturn ret = GST_FLOW_OK;
1471 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1472 AtomInfo *ainfo = (AtomInfo *) walk->data;
1476 if (!ainfo->copy_data_func (ainfo->atom,
1477 send ? &data : NULL, &size, &loffset))
1478 goto serialize_error;
1483 GST_DEBUG_OBJECT (qtmux,
1484 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1485 GST_FOURCC_ARGS (ainfo->atom->type));
1486 buf = _gst_buffer_new_take_data (data, loffset);
1487 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1488 if (ret != GST_FLOW_OK)
1501 return GST_FLOW_ERROR;
1505 static GstFlowReturn
1506 gst_qt_mux_start_file (GstQTMux * qtmux)
1508 GstFlowReturn ret = GST_FLOW_OK;
1510 GST_DEBUG_OBJECT (qtmux, "starting file");
1512 /* let downstream know we think in BYTES and expect to do seeking later on */
1513 gst_pad_push_event (qtmux->srcpad,
1514 gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES, 0, -1, 0));
1516 /* initialize our moov recovery file */
1517 GST_OBJECT_LOCK (qtmux);
1518 if (qtmux->moov_recov_file_path) {
1519 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
1520 qtmux->moov_recov_file_path);
1521 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
1522 if (qtmux->moov_recov_file == NULL) {
1523 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
1524 qtmux->moov_recov_file_path);
1527 gboolean fail = FALSE;
1528 AtomFTYP *ftyp = NULL;
1529 GstBuffer *prefix = NULL;
1531 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
1533 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
1534 qtmux->moov, qtmux->timescale,
1535 g_slist_length (qtmux->sinkpads))) {
1536 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file "
1541 atom_ftyp_free (ftyp);
1543 gst_buffer_unref (prefix);
1545 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
1546 GstCollectData *cdata = (GstCollectData *) walk->data;
1547 GstQTPad *qpad = (GstQTPad *) cdata;
1548 /* write info for each stream */
1549 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
1551 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
1557 fclose (qtmux->moov_recov_file);
1558 qtmux->moov_recov_file = NULL;
1559 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
1560 "recover file, moov recovery won't work");
1564 GST_OBJECT_UNLOCK (qtmux);
1567 * send mdat header if already needed, and mark position for later update.
1568 * We don't send ftyp now if we are on fast start mode, because we can
1569 * better fine tune using the information we gather to create the whole moov
1572 if (qtmux->fast_start) {
1573 GST_OBJECT_LOCK (qtmux);
1574 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
1575 if (!qtmux->fast_start_file)
1577 GST_OBJECT_UNLOCK (qtmux);
1579 /* send a dummy buffer for preroll */
1580 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
1581 if (ret != GST_FLOW_OK)
1585 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1586 if (ret != GST_FLOW_OK) {
1590 /* well, it's moov pos if fragmented ... */
1591 qtmux->mdat_pos = qtmux->header_size;
1593 if (qtmux->fragment_duration) {
1594 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
1595 qtmux->fragment_duration);
1596 /* also used as snapshot marker to indicate fragmented file */
1597 qtmux->fragment_sequence = 1;
1598 /* prepare moov and/or tags */
1599 gst_qt_mux_configure_moov (qtmux, NULL);
1600 gst_qt_mux_setup_metadata (qtmux);
1601 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, FALSE);
1602 if (ret != GST_FLOW_OK)
1606 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
1607 if (ret != GST_FLOW_OK)
1610 if (!qtmux->streamable)
1611 qtmux->mfra = atom_mfra_new (qtmux->context);
1613 /* extended to ensure some spare space */
1614 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE);
1624 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
1625 (("Could not open temporary file \"%s\""), qtmux->fast_start_file_path),
1627 GST_OBJECT_UNLOCK (qtmux);
1628 return GST_FLOW_ERROR;
1632 static GstFlowReturn
1633 gst_qt_mux_stop_file (GstQTMux * qtmux)
1635 gboolean ret = GST_FLOW_OK;
1636 guint64 offset = 0, size = 0;
1638 gboolean large_file;
1640 GstClockTime first_ts = GST_CLOCK_TIME_NONE;
1642 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
1644 /* pushing last buffers for each pad */
1645 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1646 GstCollectData *cdata = (GstCollectData *) walk->data;
1647 GstQTPad *qtpad = (GstQTPad *) cdata;
1649 if (!qtpad->last_buf) {
1650 GST_DEBUG_OBJECT (qtmux, "Pad %s has no buffers",
1651 GST_PAD_NAME (qtpad->collect.pad));
1654 /* send last buffer */
1655 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
1656 GST_PAD_NAME (qtpad->collect.pad));
1657 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
1658 if (ret != GST_FLOW_OK)
1659 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
1660 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
1661 gst_flow_get_name (ret));
1662 /* determine max stream duration */
1663 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1664 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1665 qtpad->last_dts > first_ts)) {
1666 first_ts = qtpad->last_dts;
1670 if (qtmux->fragment_sequence) {
1674 guint8 *data = NULL;
1678 GST_DEBUG_OBJECT (qtmux, "adding mfra");
1679 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
1680 goto serialize_error;
1681 buf = _gst_buffer_new_take_data (data, offset);
1682 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
1683 if (ret != GST_FLOW_OK)
1686 /* must have been streamable; no need to write duration */
1687 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
1692 timescale = qtmux->timescale;
1693 /* only mvex duration is updated,
1694 * mvhd should be consistent with empty moov
1695 * (but TODO maybe some clients do not handle that well ?) */
1696 qtmux->moov->mvex.mehd.fragment_duration =
1697 gst_util_uint64_scale (first_ts, timescale, GST_SECOND);
1698 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
1699 GST_TIME_FORMAT, GST_TIME_ARGS (first_ts));
1700 /* seek and rewrite the header */
1701 event = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1702 qtmux->mdat_pos, GST_CLOCK_TIME_NONE, 0);
1703 gst_pad_push_event (qtmux->srcpad, event);
1704 /* no need to seek back */
1705 return gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1708 gst_qt_mux_configure_moov (qtmux, ×cale);
1710 /* check for late streams */
1711 first_ts = GST_CLOCK_TIME_NONE;
1712 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1713 GstCollectData *cdata = (GstCollectData *) walk->data;
1714 GstQTPad *qtpad = (GstQTPad *) cdata;
1716 if (!GST_CLOCK_TIME_IS_VALID (first_ts) ||
1717 (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1718 qtpad->first_ts < first_ts)) {
1719 first_ts = qtpad->first_ts;
1722 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
1723 GST_TIME_ARGS (first_ts));
1724 /* add EDTSs for late streams */
1725 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1726 GstCollectData *cdata = (GstCollectData *) walk->data;
1727 GstQTPad *qtpad = (GstQTPad *) cdata;
1731 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts) &&
1732 qtpad->first_ts > first_ts + MAX_TOLERATED_LATENESS) {
1733 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
1734 GST_PAD_NAME (qtpad->collect.pad),
1735 GST_TIME_ARGS (qtpad->first_ts - first_ts));
1736 lateness = gst_util_uint64_scale_round (qtpad->first_ts - first_ts,
1737 timescale, GST_SECOND);
1738 duration = qtpad->trak->tkhd.duration;
1739 atom_trak_add_elst_entry (qtpad->trak, lateness, (guint32) - 1,
1740 (guint32) (1 * 65536.0));
1741 atom_trak_add_elst_entry (qtpad->trak, duration, 0,
1742 (guint32) (1 * 65536.0));
1744 /* need to add the empty time to the trak duration */
1745 qtpad->trak->tkhd.duration += lateness;
1749 /* tags into file metadata */
1750 gst_qt_mux_setup_metadata (qtmux);
1752 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
1753 /* if faststart, update the offset of the atoms in the movie with the offset
1754 * that the movie headers before mdat will cause.
1755 * Also, send the ftyp */
1756 if (qtmux->fast_start_file) {
1757 GstFlowReturn flow_ret;
1760 flow_ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
1761 if (flow_ret != GST_FLOW_OK) {
1764 /* copy into NULL to obtain size */
1765 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
1766 goto serialize_error;
1767 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
1769 offset += qtmux->header_size + (large_file ? 16 : 8);
1771 /* sum up with the extra atoms size */
1772 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
1773 if (ret != GST_FLOW_OK)
1776 offset = qtmux->header_size;
1778 atom_moov_chunks_add_offset (qtmux->moov, offset);
1781 /* note: as of this point, we no longer care about tracking written data size,
1782 * since there is no more use for it anyway */
1783 ret = gst_qt_mux_send_moov (qtmux, NULL, FALSE);
1784 if (ret != GST_FLOW_OK)
1788 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
1789 if (ret != GST_FLOW_OK)
1792 /* if needed, send mdat atom and move buffered data into it */
1793 if (qtmux->fast_start_file) {
1794 /* mdat_size = accumulated (buffered data) */
1795 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
1797 if (ret != GST_FLOW_OK)
1799 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
1800 if (ret != GST_FLOW_OK)
1803 /* mdat needs update iff not using faststart */
1804 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
1805 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
1806 qtmux->mdat_size, NULL);
1807 /* note; no seeking back to the end of file is done,
1808 * since we no longer write anything anyway */
1816 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1817 ("Failed to serialize moov"));
1818 return GST_FLOW_ERROR;
1822 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
1823 return GST_FLOW_ERROR;
1827 static GstFlowReturn
1828 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
1829 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
1830 guint32 delta, guint32 size, gboolean sync, gboolean do_pts,
1833 GstFlowReturn ret = GST_FLOW_OK;
1835 /* setup if needed */
1836 if (G_UNLIKELY (!pad->traf || force))
1840 /* flush pad fragment if threshold reached,
1841 * or at new keyframe if we should be minding those in the first place */
1842 if (G_UNLIKELY (force || (sync && pad->sync) ||
1843 pad->fragment_duration < (gint64) delta)) {
1845 guint64 size = 0, offset = 0;
1846 guint8 *data = NULL;
1848 guint i, total_size;
1850 /* now we know where moof ends up, update offset in tfra */
1852 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
1854 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
1855 /* takes ownership */
1856 atom_moof_add_traf (moof, pad->traf);
1858 atom_moof_copy_data (moof, &data, &size, &offset);
1859 buffer = _gst_buffer_new_take_data (data, offset);
1860 GST_LOG_OBJECT (qtmux, "writing moof size %d", GST_BUFFER_SIZE (buffer));
1861 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
1863 /* and actual data */
1865 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
1867 GST_BUFFER_SIZE (atom_array_index (&pad->fragment_buffers, i));
1870 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
1871 atom_array_get_len (&pad->fragment_buffers), total_size);
1872 if (ret == GST_FLOW_OK)
1873 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
1875 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
1876 if (G_LIKELY (ret == GST_FLOW_OK))
1877 ret = gst_qt_mux_send_buffer (qtmux,
1878 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
1881 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
1884 atom_array_clear (&pad->fragment_buffers);
1885 atom_moof_free (moof);
1886 qtmux->fragment_sequence++;
1891 if (G_UNLIKELY (!pad->traf)) {
1892 GST_LOG_OBJECT (qtmux, "setting up new fragment");
1893 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
1894 atom_array_init (&pad->fragment_buffers, 512);
1895 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
1896 atom_trak_get_timescale (pad->trak), 1000);
1898 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
1899 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
1900 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
1904 /* add buffer and metadata */
1905 atom_traf_add_samples (pad->traf, delta, size, sync, do_pts, pts_offset,
1907 atom_array_append (&pad->fragment_buffers, buf, 256);
1908 pad->fragment_duration -= delta;
1911 guint32 sn = atom_traf_get_sample_num (pad->traf);
1913 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
1914 atom_tfra_add_entry (pad->tfra, dts, sn);
1917 if (G_UNLIKELY (force))
1923 /* check whether @a differs from @b by order of @magn */
1924 static gboolean inline
1925 gst_qtmux_check_difference (GstQTMux * qtmux, GstClockTime a,
1926 GstClockTime b, GstClockTime magn)
1928 return ((a >= b) ? (a - b >= (magn >> 1)) : (b - a >= (magn >> 1)));
1932 * Here we push the buffer and update the tables in the track atoms
1934 static GstFlowReturn
1935 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
1937 GstBuffer *last_buf = NULL;
1938 GstClockTime duration;
1939 guint nsamples, sample_size;
1940 guint64 scaled_duration, chunk_offset;
1942 gint64 pts_offset = 0;
1943 gboolean sync = FALSE, do_pts = FALSE;
1946 goto not_negotiated;
1948 /* if this pad has a prepare function, call it */
1949 if (pad->prepare_buf_func != NULL) {
1950 buf = pad->prepare_buf_func (pad, buf, qtmux);
1953 last_buf = pad->last_buf;
1954 if (last_buf == NULL) {
1955 #ifndef GST_DISABLE_GST_DEBUG
1957 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
1958 "received NULL buffer, doing nothing",
1959 GST_PAD_NAME (pad->collect.pad));
1961 GST_LOG_OBJECT (qtmux,
1962 "Pad %s has no previous buffer stored, storing now",
1963 GST_PAD_NAME (pad->collect.pad));
1966 pad->last_buf = buf;
1969 gst_buffer_ref (last_buf);
1971 /* nasty heuristic mess to guestimate dealing with DTS/PTS,
1972 * while also trying to stay close to input ts to preserve sync, so:
1973 * - prefer using input ts where possible
1974 * - if those detected out-of-order (*), and input duration available,
1975 * mark as out-of-order and fallback to duration
1976 * - if in out-of-order, need to preserve sync between streams, and adding
1977 * durations might drift, so try to resync when we expect
1978 * input ts == (sum of durations), which is at some keyframe input frame.
1980 * (*) if input ts out-of-order, or if ts differs from (sum of durations)
1981 * by an (approx) order-of-duration magnitude
1983 if (G_LIKELY (buf) && !pad->is_out_of_order) {
1984 if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (last_buf) &&
1985 GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
1986 if ((GST_BUFFER_TIMESTAMP (buf) < GST_BUFFER_TIMESTAMP (last_buf)) ||
1987 (!GST_CLOCK_TIME_IS_VALID (pad->first_ts) &&
1988 GST_BUFFER_DURATION_IS_VALID (last_buf) &&
1989 gst_qtmux_check_difference (qtmux,
1990 GST_BUFFER_TIMESTAMP (last_buf) +
1991 GST_BUFFER_DURATION (last_buf), GST_BUFFER_TIMESTAMP (buf),
1992 GST_BUFFER_DURATION (last_buf)))) {
1993 GST_DEBUG_OBJECT (qtmux, "detected out-of-order input");
1994 pad->is_out_of_order = TRUE;
1997 /* this is pretty bad */
1998 GST_WARNING_OBJECT (qtmux, "missing input timestamp");
1999 /* fall back to durations */
2000 pad->is_out_of_order = TRUE;
2004 /* fall back to duration if last buffer or
2005 * out-of-order (determined previously), otherwise use input ts */
2006 if (buf == NULL || pad->is_out_of_order) {
2007 if (!GST_BUFFER_DURATION_IS_VALID (last_buf)) {
2008 /* be forgiving for some possibly last upstream flushed buffer */
2011 GST_WARNING_OBJECT (qtmux, "no duration for last buffer");
2012 /* iso spec recommends some small value, try 0 */
2015 duration = GST_BUFFER_DURATION (last_buf);
2016 /* avoid drift in sum timestamps,
2017 * so use input timestamp for suitable keyframe */
2018 if (buf && !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT) &&
2019 GST_BUFFER_TIMESTAMP (buf) >= pad->last_dts &&
2020 !gst_qtmux_check_difference (qtmux, pad->last_dts + duration,
2021 GST_BUFFER_TIMESTAMP (buf), duration)) {
2022 GST_DEBUG_OBJECT (qtmux, "resyncing out-of-order input to ts; "
2023 "replacing %" GST_TIME_FORMAT " by %" GST_TIME_FORMAT,
2024 GST_TIME_ARGS (pad->last_dts + duration),
2025 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2026 duration = GST_BUFFER_TIMESTAMP (buf) - pad->last_dts;
2030 duration = GST_BUFFER_TIMESTAMP (buf) - GST_BUFFER_TIMESTAMP (last_buf);
2033 gst_buffer_replace (&pad->last_buf, buf);
2035 last_dts = gst_util_uint64_scale_round (pad->last_dts,
2036 atom_trak_get_timescale (pad->trak), GST_SECOND);
2038 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
2039 if (pad->sample_size && !qtmux->fragment_sequence) {
2040 /* Constant size packets: usually raw audio (with many samples per
2041 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
2043 sample_size = pad->sample_size;
2044 if (GST_BUFFER_SIZE (last_buf) % sample_size != 0)
2045 goto fragmented_sample;
2046 /* note: qt raw audio storage warps it implicitly into a timewise
2047 * perfect stream, discarding buffer times */
2048 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
2049 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
2050 atom_trak_get_timescale (pad->trak), GST_SECOND);
2052 nsamples = GST_BUFFER_SIZE (last_buf) / sample_size;
2054 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
2056 /* timescale = samplerate */
2057 scaled_duration = 1;
2058 pad->last_dts += duration * nsamples;
2061 sample_size = GST_BUFFER_SIZE (last_buf);
2062 if (pad->have_dts) {
2064 pad->last_dts = GST_BUFFER_OFFSET_END (last_buf);
2065 if ((gint64) (pad->last_dts) < 0) {
2066 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
2067 atom_trak_get_timescale (pad->trak), GST_SECOND);
2069 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
2070 atom_trak_get_timescale (pad->trak), GST_SECOND);
2072 scaled_duration = scaled_dts - last_dts;
2073 last_dts = scaled_dts;
2075 /* first convert intended timestamp (in GstClockTime resolution) to
2076 * trak timescale, then derive delta;
2077 * this ensures sums of (scale)delta add up to converted timestamp,
2078 * which only deviates at most 1/scale from timestamp itself */
2079 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
2080 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
2081 pad->last_dts += duration;
2084 chunk_offset = qtmux->mdat_size;
2086 GST_LOG_OBJECT (qtmux,
2087 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
2088 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
2089 GST_LOG_OBJECT (qtmux,
2090 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
2091 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
2092 nsamples, scaled_duration, sample_size, chunk_offset);
2094 /* might be a sync sample */
2096 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2097 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
2098 GST_PAD_NAME (pad->collect.pad));
2102 /* optionally calculate ctts entry values
2103 * (if composition-time expected different from decoding-time) */
2104 /* really not recommended:
2105 * - decoder typically takes care of dts/pts issues
2106 * - in case of out-of-order, dts may only be determined as above
2107 * (e.g. sum of duration), which may be totally different from
2108 * buffer timestamps in case of multiple segment, non-perfect streams
2109 * (and just perhaps maybe with some luck segment_to_running_time
2110 * or segment_to_media_time might get near to it) */
2111 if ((pad->have_dts || qtmux->guess_pts) && pad->is_out_of_order) {
2114 pts = gst_util_uint64_scale_round (GST_BUFFER_TIMESTAMP (last_buf),
2115 atom_trak_get_timescale (pad->trak), GST_SECOND);
2116 pts_offset = (gint64) (pts - last_dts);
2118 GST_LOG_OBJECT (qtmux, "Adding ctts entry for pad %s: %" G_GINT64_FORMAT,
2119 GST_PAD_NAME (pad->collect.pad), pts_offset);
2123 * Each buffer starts a new chunk, so we can assume the buffer
2124 * duration is the chunk duration
2126 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
2127 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
2128 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
2129 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
2130 qtmux->longest_chunk = duration;
2133 /* if this is the first buffer, store the timestamp */
2134 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
2135 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (last_buf))) {
2136 pad->first_ts = GST_BUFFER_TIMESTAMP (last_buf);
2138 GST_DEBUG_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
2139 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
2142 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
2143 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
2144 GST_TIME_ARGS (pad->first_ts));
2147 /* now we go and register this buffer/sample all over */
2148 /* note that a new chunk is started each time (not fancy but works) */
2149 if (qtmux->moov_recov_file) {
2150 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2151 nsamples, scaled_duration, sample_size, chunk_offset, sync, do_pts,
2153 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2154 "recovery file, disabling recovery");
2155 fclose (qtmux->moov_recov_file);
2156 qtmux->moov_recov_file = NULL;
2161 gst_buffer_unref (buf);
2163 if (qtmux->fragment_sequence) {
2164 /* ensure that always sync samples are marked as such */
2165 return gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, last_buf,
2166 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
2167 !pad->sync || sync, do_pts, pts_offset);
2169 atom_trak_add_samples (pad->trak, nsamples, scaled_duration, sample_size,
2170 chunk_offset, sync, do_pts, pts_offset);
2171 return gst_qt_mux_send_buffer (qtmux, last_buf, &qtmux->mdat_size, TRUE);
2178 gst_buffer_unref (buf);
2179 gst_buffer_unref (last_buf);
2180 return GST_FLOW_ERROR;
2184 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2185 ("Received buffer without timestamp/duration."));
2190 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2191 ("Audio buffer contains fragmented sample."));
2196 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
2197 ("format wasn't negotiated before buffer flow on pad %s",
2198 GST_PAD_NAME (pad->collect.pad)));
2200 gst_buffer_unref (buf);
2201 return GST_FLOW_NOT_NEGOTIATED;
2205 static GstFlowReturn
2206 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
2208 GstFlowReturn ret = GST_FLOW_OK;
2209 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
2211 GstQTPad *best_pad = NULL;
2212 GstClockTime time, best_time = GST_CLOCK_TIME_NONE;
2215 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
2216 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
2219 qtmux->state = GST_QT_MUX_STATE_DATA;
2222 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
2223 return GST_FLOW_UNEXPECTED;
2225 /* select the best buffer */
2226 walk = qtmux->collect->data;
2229 GstCollectData *data;
2231 data = (GstCollectData *) walk->data;
2232 pad = (GstQTPad *) data;
2234 walk = g_slist_next (walk);
2236 buf = gst_collect_pads_peek (pads, data);
2238 GST_LOG_OBJECT (qtmux, "Pad %s has no buffers",
2239 GST_PAD_NAME (pad->collect.pad));
2242 time = GST_BUFFER_TIMESTAMP (buf);
2243 gst_buffer_unref (buf);
2245 if (best_pad == NULL || !GST_CLOCK_TIME_IS_VALID (time) ||
2246 (GST_CLOCK_TIME_IS_VALID (best_time) && time < best_time)) {
2252 if (best_pad != NULL) {
2253 GST_LOG_OBJECT (qtmux, "selected pad %s with time %" GST_TIME_FORMAT,
2254 GST_PAD_NAME (best_pad->collect.pad), GST_TIME_ARGS (best_time));
2255 buf = gst_collect_pads_pop (pads, &best_pad->collect);
2256 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
2258 ret = gst_qt_mux_stop_file (qtmux);
2259 if (ret == GST_FLOW_OK) {
2260 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
2261 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
2262 ret = GST_FLOW_UNEXPECTED;
2264 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
2265 gst_flow_get_name (ret));
2267 qtmux->state = GST_QT_MUX_STATE_EOS;
2274 check_field (GQuark field_id, const GValue * value, gpointer user_data)
2276 GstStructure *structure = (GstStructure *) user_data;
2277 const GValue *other = gst_structure_id_get_value (structure, field_id);
2280 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
2284 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
2287 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
2288 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
2290 return gst_structure_foreach (sub_s, check_field, sup_s);
2294 gst_qt_mux_audio_sink_set_caps (GstPad * pad, GstCaps * caps)
2296 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2297 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2298 GstQTPad *qtpad = NULL;
2299 GstStructure *structure;
2300 const gchar *mimetype;
2301 gint rate, channels;
2302 const GValue *value = NULL;
2303 const GstBuffer *codec_data = NULL;
2304 GstQTMuxFormat format;
2305 AudioSampleEntry entry = { 0, };
2306 AtomInfo *ext_atom = NULL;
2307 gint constant_size = 0;
2308 const gchar *stream_format;
2309 GstCaps *current_caps = NULL;
2311 /* find stream data */
2312 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2315 qtpad->prepare_buf_func = NULL;
2317 /* does not go well to renegotiate stream mid-way, unless
2318 * the old caps are a subset of the new one (this means upstream
2319 * added more info to the caps, as both should be 'fixed' caps) */
2320 if (qtpad->fourcc) {
2321 g_object_get (pad, "caps", ¤t_caps, NULL);
2322 g_assert (caps != NULL);
2324 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2325 goto refuse_renegotiation;
2327 GST_DEBUG_OBJECT (qtmux,
2328 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2329 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
2332 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2333 GST_DEBUG_PAD_NAME (pad), caps);
2335 format = qtmux_klass->format;
2336 structure = gst_caps_get_structure (caps, 0);
2337 mimetype = gst_structure_get_name (structure);
2340 if (!gst_structure_get_int (structure, "channels", &channels) ||
2341 !gst_structure_get_int (structure, "rate", &rate)) {
2346 value = gst_structure_get_value (structure, "codec_data");
2348 codec_data = gst_value_get_buffer (value);
2350 qtpad->is_out_of_order = FALSE;
2351 qtpad->have_dts = FALSE;
2353 /* set common properties */
2354 entry.sample_rate = rate;
2355 entry.channels = channels;
2357 entry.sample_size = 16;
2358 /* this is the typical compressed case */
2359 if (format == GST_QT_MUX_FORMAT_QT) {
2361 entry.compression_id = -2;
2364 /* now map onto a fourcc, and some extra properties */
2365 if (strcmp (mimetype, "audio/mpeg") == 0) {
2366 gint mpegversion = 0;
2369 gst_structure_get_int (structure, "mpegversion", &mpegversion);
2370 switch (mpegversion) {
2372 gst_structure_get_int (structure, "layer", &layer);
2376 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
2377 if (format == GST_QT_MUX_FORMAT_QT)
2378 entry.fourcc = FOURCC__mp3;
2380 entry.fourcc = FOURCC_mp4a;
2382 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
2383 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2384 qtpad->max_bitrate);
2386 entry.samples_per_packet = 1152;
2387 entry.bytes_per_sample = 2;
2393 /* check stream-format */
2394 stream_format = gst_structure_get_string (structure, "stream-format");
2395 if (stream_format) {
2396 if (strcmp (stream_format, "raw") != 0) {
2397 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
2398 "please use 'raw'", stream_format);
2402 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
2406 if (!codec_data || GST_BUFFER_SIZE (codec_data) < 2)
2407 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
2409 guint8 profile = GST_READ_UINT8 (GST_BUFFER_DATA (codec_data));
2411 /* warn if not Low Complexity profile */
2414 GST_WARNING_OBJECT (qtmux,
2415 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
2419 entry.fourcc = FOURCC_mp4a;
2421 if (format == GST_QT_MUX_FORMAT_QT)
2422 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
2423 qtpad->avg_bitrate, qtpad->max_bitrate);
2426 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
2427 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
2428 qtpad->max_bitrate);
2433 } else if (strcmp (mimetype, "audio/AMR") == 0) {
2434 entry.fourcc = FOURCC_samr;
2435 entry.sample_size = 16;
2436 entry.samples_per_packet = 160;
2437 entry.bytes_per_sample = 2;
2438 ext_atom = build_amr_extension ();
2439 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
2440 entry.fourcc = FOURCC_sawb;
2441 entry.sample_size = 16;
2442 entry.samples_per_packet = 320;
2443 entry.bytes_per_sample = 2;
2444 ext_atom = build_amr_extension ();
2445 } else if (strcmp (mimetype, "audio/x-raw-int") == 0) {
2451 if (!gst_structure_get_int (structure, "width", &width) ||
2452 !gst_structure_get_int (structure, "depth", &depth) ||
2453 !gst_structure_get_boolean (structure, "signed", &sign)) {
2454 GST_DEBUG_OBJECT (qtmux, "broken caps, width/depth/signed field missing");
2459 endianness = G_BYTE_ORDER;
2460 } else if (!gst_structure_get_int (structure, "endianness", &endianness)) {
2461 GST_DEBUG_OBJECT (qtmux, "broken caps, endianness field missing");
2465 /* spec has no place for a distinction in these */
2466 if (width != depth) {
2467 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
2472 if (endianness == G_LITTLE_ENDIAN)
2473 entry.fourcc = FOURCC_sowt;
2474 else if (endianness == G_BIG_ENDIAN)
2475 entry.fourcc = FOURCC_twos;
2476 /* maximum backward compatibility; only new version for > 16 bit */
2479 /* not compressed in any case */
2480 entry.compression_id = 0;
2481 /* QT spec says: max at 16 bit even if sample size were actually larger,
2482 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
2483 entry.sample_size = depth;
2484 entry.bytes_per_sample = depth / 8;
2485 entry.samples_per_packet = 1;
2486 entry.bytes_per_packet = depth / 8;
2487 entry.bytes_per_frame = entry.bytes_per_packet * channels;
2489 if (width == 8 && depth == 8) {
2490 /* fall back to old 8-bit version */
2491 entry.fourcc = FOURCC_raw_;
2493 entry.compression_id = 0;
2494 entry.sample_size = 8;
2496 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
2500 constant_size = (depth / 8) * channels;
2501 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
2502 entry.fourcc = FOURCC_alaw;
2503 entry.samples_per_packet = 1023;
2504 entry.bytes_per_sample = 2;
2505 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
2506 entry.fourcc = FOURCC_ulaw;
2507 entry.samples_per_packet = 1023;
2508 entry.bytes_per_sample = 2;
2509 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
2511 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
2512 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
2515 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
2517 entry.fourcc = MS_WAVE_FOURCC (0x11);
2518 /* 4 byte header per channel (including one sample). 2 samples per byte
2519 remaining. Simplifying gives the following (samples per block per
2521 entry.samples_per_packet = 2 * blocksize / channels - 7;
2522 entry.bytes_per_sample = 2;
2524 entry.bytes_per_frame = blocksize;
2525 entry.bytes_per_packet = blocksize / channels;
2526 /* ADPCM has constant size packets */
2528 /* TODO: I don't really understand why this helps, but it does! Constant
2529 * size and compression_id of -2 seem to be incompatible, and other files
2530 * in the wild use this too. */
2531 entry.compression_id = -1;
2533 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
2534 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
2535 GstBuffer *codec_config;
2538 entry.fourcc = FOURCC_alac;
2539 /* let's check if codec data already comes with 'alac' atom prefix */
2540 if (!codec_data || (len = GST_BUFFER_SIZE (codec_data)) < 28) {
2541 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
2544 if (GST_READ_UINT32_LE (GST_BUFFER_DATA (codec_data) + 4) == FOURCC_alac) {
2546 codec_config = gst_buffer_create_sub ((GstBuffer *) codec_data, 8, len);
2548 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
2551 /* does not look good, but perhaps some trailing unneeded stuff */
2552 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
2554 if (format == GST_QT_MUX_FORMAT_QT)
2555 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
2557 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
2558 /* set some more info */
2559 entry.bytes_per_sample = 2;
2560 entry.samples_per_packet =
2561 GST_READ_UINT32_BE (GST_BUFFER_DATA (codec_config) + 4);
2562 gst_buffer_unref (codec_config);
2568 /* ok, set the pad info accordingly */
2569 qtpad->fourcc = entry.fourcc;
2570 qtpad->sample_size = constant_size;
2571 atom_trak_set_audio_type (qtpad->trak, qtmux->context, &entry,
2572 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
2573 ext_atom, constant_size);
2575 gst_object_unref (qtmux);
2581 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2582 GST_PAD_NAME (pad), caps);
2583 gst_object_unref (qtmux);
2586 refuse_renegotiation:
2588 GST_WARNING_OBJECT (qtmux,
2589 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
2590 GST_PAD_NAME (pad), caps);
2591 gst_object_unref (qtmux);
2596 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
2598 adjust_rate (guint64 rate)
2603 while (rate >= 10000)
2609 return (guint32) rate;
2613 gst_qt_mux_video_sink_set_caps (GstPad * pad, GstCaps * caps)
2615 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2616 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2617 GstQTPad *qtpad = NULL;
2618 GstStructure *structure;
2619 const gchar *mimetype;
2620 gint width, height, depth = -1;
2621 gint framerate_num, framerate_den;
2623 const GValue *value = NULL;
2624 const GstBuffer *codec_data = NULL;
2625 VisualSampleEntry entry = { 0, };
2626 GstQTMuxFormat format;
2627 AtomInfo *ext_atom = NULL;
2628 GList *ext_atom_list = NULL;
2629 gboolean sync = FALSE;
2630 int par_num, par_den;
2631 GstCaps *current_caps = NULL;
2633 /* find stream data */
2634 qtpad = (GstQTPad *) gst_pad_get_element_private (pad);
2637 qtpad->prepare_buf_func = NULL;
2639 /* does not go well to renegotiate stream mid-way, unless
2640 * the old caps are a subset of the new one (this means upstream
2641 * added more info to the caps, as both should be 'fixed' caps) */
2642 if (qtpad->fourcc) {
2643 g_object_get (pad, "caps", ¤t_caps, NULL);
2644 g_assert (caps != NULL);
2646 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
2647 goto refuse_renegotiation;
2649 GST_DEBUG_OBJECT (qtmux,
2650 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
2651 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
2654 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
2655 GST_DEBUG_PAD_NAME (pad), caps);
2657 format = qtmux_klass->format;
2658 structure = gst_caps_get_structure (caps, 0);
2659 mimetype = gst_structure_get_name (structure);
2661 /* required parts */
2662 if (!gst_structure_get_int (structure, "width", &width) ||
2663 !gst_structure_get_int (structure, "height", &height))
2668 /* works as a default timebase */
2669 framerate_num = 10000;
2671 gst_structure_get_fraction (structure, "framerate", &framerate_num,
2673 gst_structure_get_int (structure, "depth", &depth);
2674 value = gst_structure_get_value (structure, "codec_data");
2676 codec_data = gst_value_get_buffer (value);
2680 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
2683 qtpad->is_out_of_order = FALSE;
2685 /* bring frame numerator into a range that ensures both reasonable resolution
2686 * as well as a fair duration */
2687 rate = qtmux->trak_timescale ?
2688 qtmux->trak_timescale : adjust_rate (framerate_num);
2689 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
2692 /* set common properties */
2693 entry.width = width;
2694 entry.height = height;
2695 entry.par_n = par_num;
2696 entry.par_d = par_den;
2697 /* should be OK according to qt and iso spec, override if really needed */
2698 entry.color_table_id = -1;
2699 entry.frame_count = 1;
2702 /* sync entries by default */
2705 /* now map onto a fourcc, and some extra properties */
2706 if (strcmp (mimetype, "video/x-raw-rgb") == 0) {
2709 entry.fourcc = FOURCC_raw_;
2710 gst_structure_get_int (structure, "bpp", &bpp);
2713 } else if (strcmp (mimetype, "video/x-raw-yuv") == 0) {
2717 gst_structure_get_fourcc (structure, "format", &format);
2719 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
2722 entry.fourcc = FOURCC_2vuy;
2723 entry.depth = depth;
2726 } else if (strcmp (mimetype, "video/x-h263") == 0) {
2728 if (format == GST_QT_MUX_FORMAT_QT)
2729 entry.fourcc = FOURCC_h263;
2731 entry.fourcc = FOURCC_s263;
2732 ext_atom = build_h263_extension ();
2733 if (ext_atom != NULL)
2734 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2735 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
2736 strcmp (mimetype, "video/mpeg") == 0) {
2739 if (strcmp (mimetype, "video/x-divx") == 0) {
2740 gst_structure_get_int (structure, "divxversion", &version);
2741 version = version == 5 ? 1 : 0;
2743 gst_structure_get_int (structure, "mpegversion", &version);
2744 version = version == 4 ? 1 : 0;
2747 entry.fourcc = FOURCC_mp4v;
2749 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
2750 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
2751 qtpad->max_bitrate);
2752 if (ext_atom != NULL)
2753 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2755 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
2756 "output might not play in Apple QuickTime (try global-headers?)");
2758 } else if (strcmp (mimetype, "video/x-h264") == 0) {
2759 entry.fourcc = FOURCC_avc1;
2760 if (qtpad->avg_bitrate == 0) {
2761 gint avg_bitrate = 0;
2762 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
2763 qtpad->avg_bitrate = avg_bitrate;
2765 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
2766 if (ext_atom != NULL)
2767 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2769 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
2770 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
2771 if (ext_atom != NULL)
2772 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2773 } else if (strcmp (mimetype, "video/x-svq") == 0) {
2775 const GstBuffer *seqh = NULL;
2776 const GValue *seqh_value;
2779 gst_structure_get_int (structure, "svqversion", &version);
2781 entry.fourcc = FOURCC_SVQ3;
2785 seqh_value = gst_structure_get_value (structure, "seqh");
2787 seqh = gst_value_get_buffer (seqh_value);
2788 ext_atom = build_SMI_atom (seqh);
2790 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2793 /* we need to add the gamma anyway because quicktime might crash
2794 * when it doesn't find it */
2795 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
2796 /* it seems that using 0 here makes it ignored */
2799 ext_atom = build_gama_atom (gamma);
2801 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
2803 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
2804 "a bug at http://bugzilla.gnome.org", version);
2806 } else if (strcmp (mimetype, "video/x-dv") == 0) {
2808 gboolean pal = TRUE;
2811 if (framerate_num != 25 || framerate_den != 1)
2813 gst_structure_get_int (structure, "dvversion", &version);
2814 /* fall back to typical one */
2820 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
2822 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
2826 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
2828 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
2831 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
2834 } else if (strcmp (mimetype, "image/jpeg") == 0) {
2835 entry.fourcc = FOURCC_jpeg;
2837 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
2838 strcmp (mimetype, "image/x-jpc") == 0) {
2840 const GValue *cmap_array;
2841 const GValue *cdef_array;
2845 if (strcmp (mimetype, "image/x-jpc") == 0) {
2846 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
2849 gst_structure_get_int (structure, "num-components", &ncomp);
2850 gst_structure_get_int (structure, "fields", &fields);
2851 cmap_array = gst_structure_get_value (structure, "component-map");
2852 cdef_array = gst_structure_get_value (structure, "channel-definitions");
2855 entry.fourcc = FOURCC_mjp2;
2857 if (gst_structure_get_fourcc (structure, "fourcc", &fourcc) &&
2859 build_jp2h_extension (qtpad->trak, width, height, fourcc, ncomp,
2860 cmap_array, cdef_array)) != NULL) {
2861 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
2863 ext_atom = build_fiel_extension (fields);
2865 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
2867 ext_atom = build_jp2x_extension (codec_data);
2869 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
2871 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
2874 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
2875 entry.fourcc = FOURCC_VP80;
2877 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
2880 gst_structure_get_fourcc (structure, "format", &fourcc);
2881 entry.fourcc = fourcc;
2882 qtpad->have_dts = TRUE;
2883 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
2886 gst_structure_get_fourcc (structure, "format", &fourcc);
2887 entry.fourcc = fourcc;
2888 qtpad->have_dts = TRUE;
2894 /* ok, set the pad info accordingly */
2895 qtpad->fourcc = entry.fourcc;
2897 atom_trak_set_video_type (qtpad->trak, qtmux->context, &entry, rate,
2900 gst_object_unref (qtmux);
2906 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
2907 GST_PAD_NAME (pad), caps);
2908 gst_object_unref (qtmux);
2911 refuse_renegotiation:
2913 GST_WARNING_OBJECT (qtmux,
2914 "pad %s refused renegotiation to %" GST_PTR_FORMAT " from %"
2915 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, GST_PAD_CAPS (pad));
2916 gst_object_unref (qtmux);
2922 gst_qt_mux_sink_event (GstPad * pad, GstEvent * event)
2926 guint32 avg_bitrate = 0, max_bitrate = 0;
2928 qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
2929 switch (GST_EVENT_TYPE (event)) {
2930 case GST_EVENT_TAG:{
2932 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
2933 GstTagMergeMode mode;
2935 GST_OBJECT_LOCK (qtmux);
2936 mode = gst_tag_setter_get_tag_merge_mode (setter);
2938 GST_DEBUG_OBJECT (qtmux, "received tag event");
2939 gst_event_parse_tag (event, &list);
2941 gst_tag_setter_merge_tags (setter, list, mode);
2942 GST_OBJECT_UNLOCK (qtmux);
2944 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
2945 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
2946 GstQTPad *qtpad = gst_pad_get_element_private (pad);
2949 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
2950 qtpad->avg_bitrate = avg_bitrate;
2951 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
2952 qtpad->max_bitrate = max_bitrate;
2961 ret = qtmux->collect_event (pad, event);
2962 gst_object_unref (qtmux);
2968 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
2970 GstQTMux *mux = GST_QT_MUX_CAST (element);
2973 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
2975 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
2976 GstQTPad *qtpad = (GstQTPad *) walk->data;
2977 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
2978 if (qtpad->collect.pad == pad) {
2979 /* this is it, remove */
2980 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
2981 gst_element_remove_pad (element, pad);
2986 gst_collect_pads_remove_pad (mux->collect, pad);
2990 gst_qt_mux_request_new_pad (GstElement * element,
2991 GstPadTemplate * templ, const gchar * req_name)
2993 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
2994 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
2995 GstQTPad *collect_pad;
3000 if (templ->direction != GST_PAD_SINK)
3001 goto wrong_direction;
3003 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
3006 if (templ == gst_element_class_get_pad_template (klass, "audio_%d")) {
3008 name = g_strdup_printf ("audio_%02d", qtmux->audio_pads++);
3009 } else if (templ == gst_element_class_get_pad_template (klass, "video_%d")) {
3011 name = g_strdup_printf ("video_%02d", qtmux->video_pads++);
3013 goto wrong_template;
3015 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
3017 /* create pad and add to collections */
3018 newpad = gst_pad_new_from_template (templ, name);
3020 collect_pad = (GstQTPad *)
3021 gst_collect_pads_add_pad_full (qtmux->collect, newpad, sizeof (GstQTPad),
3022 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset));
3024 gst_qt_mux_pad_reset (collect_pad);
3025 collect_pad->trak = atom_trak_new (qtmux->context);
3026 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
3028 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
3030 /* set up pad functions */
3032 gst_pad_set_setcaps_function (newpad,
3033 GST_DEBUG_FUNCPTR (gst_qt_mux_audio_sink_set_caps));
3035 gst_pad_set_setcaps_function (newpad,
3036 GST_DEBUG_FUNCPTR (gst_qt_mux_video_sink_set_caps));
3038 /* FIXME: hacked way to override/extend the event function of
3039 * GstCollectPads; because it sets its own event function giving the
3040 * element no access to events.
3042 qtmux->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
3043 gst_pad_set_event_function (newpad,
3044 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event));
3046 gst_pad_set_active (newpad, TRUE);
3047 gst_element_add_pad (element, newpad);
3054 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
3059 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
3064 GST_WARNING_OBJECT (qtmux, "This is not our template!");
3070 gst_qt_mux_get_property (GObject * object,
3071 guint prop_id, GValue * value, GParamSpec * pspec)
3073 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3075 GST_OBJECT_LOCK (qtmux);
3077 case PROP_LARGE_FILE:
3078 g_value_set_boolean (value, qtmux->large_file);
3080 case PROP_MOVIE_TIMESCALE:
3081 g_value_set_uint (value, qtmux->timescale);
3083 case PROP_TRAK_TIMESCALE:
3084 g_value_set_uint (value, qtmux->trak_timescale);
3087 g_value_set_boolean (value, qtmux->guess_pts);
3089 case PROP_FAST_START:
3090 g_value_set_boolean (value, qtmux->fast_start);
3092 case PROP_FAST_START_TEMP_FILE:
3093 g_value_set_string (value, qtmux->fast_start_file_path);
3095 case PROP_MOOV_RECOV_FILE:
3096 g_value_set_string (value, qtmux->moov_recov_file_path);
3098 case PROP_FRAGMENT_DURATION:
3099 g_value_set_uint (value, qtmux->fragment_duration);
3101 case PROP_STREAMABLE:
3102 g_value_set_boolean (value, qtmux->streamable);
3105 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3108 GST_OBJECT_UNLOCK (qtmux);
3112 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
3116 g_free (qtmux->fast_start_file_path);
3117 qtmux->fast_start_file_path = NULL;
3119 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
3120 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
3125 gst_qt_mux_set_property (GObject * object,
3126 guint prop_id, const GValue * value, GParamSpec * pspec)
3128 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
3130 GST_OBJECT_LOCK (qtmux);
3132 case PROP_LARGE_FILE:
3133 qtmux->large_file = g_value_get_boolean (value);
3135 case PROP_MOVIE_TIMESCALE:
3136 qtmux->timescale = g_value_get_uint (value);
3138 case PROP_TRAK_TIMESCALE:
3139 qtmux->trak_timescale = g_value_get_uint (value);
3142 qtmux->guess_pts = g_value_get_boolean (value);
3144 case PROP_FAST_START:
3145 qtmux->fast_start = g_value_get_boolean (value);
3147 case PROP_FAST_START_TEMP_FILE:
3148 g_free (qtmux->fast_start_file_path);
3149 qtmux->fast_start_file_path = g_value_dup_string (value);
3150 /* NULL means to generate a random one */
3151 if (!qtmux->fast_start_file_path) {
3152 gst_qt_mux_generate_fast_start_file_path (qtmux);
3155 case PROP_MOOV_RECOV_FILE:
3156 g_free (qtmux->moov_recov_file_path);
3157 qtmux->moov_recov_file_path = g_value_dup_string (value);
3159 case PROP_FRAGMENT_DURATION:
3160 qtmux->fragment_duration = g_value_get_uint (value);
3162 case PROP_STREAMABLE:
3163 qtmux->streamable = g_value_get_boolean (value);
3166 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3169 GST_OBJECT_UNLOCK (qtmux);
3172 static GstStateChangeReturn
3173 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
3175 GstStateChangeReturn ret;
3176 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
3178 switch (transition) {
3179 case GST_STATE_CHANGE_NULL_TO_READY:
3181 case GST_STATE_CHANGE_READY_TO_PAUSED:
3182 gst_collect_pads_start (qtmux->collect);
3183 qtmux->state = GST_QT_MUX_STATE_STARTED;
3185 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3187 case GST_STATE_CHANGE_PAUSED_TO_READY:
3188 gst_collect_pads_stop (qtmux->collect);
3194 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3196 switch (transition) {
3197 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3199 case GST_STATE_CHANGE_PAUSED_TO_READY:
3200 gst_qt_mux_reset (qtmux, TRUE);
3202 case GST_STATE_CHANGE_READY_TO_NULL:
3212 gst_qt_mux_register (GstPlugin * plugin)
3214 GTypeInfo typeinfo = {
3215 sizeof (GstQTMuxClass),
3216 (GBaseInitFunc) gst_qt_mux_base_init,
3218 (GClassInitFunc) gst_qt_mux_class_init,
3223 (GInstanceInitFunc) gst_qt_mux_init,
3225 static const GInterfaceInfo tag_setter_info = {
3229 GstQTMuxFormat format;
3230 GstQTMuxClassParams *params;
3233 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
3235 GST_LOG ("Registering muxers");
3238 GstQTMuxFormatProp *prop;
3240 prop = &gst_qt_mux_format_list[i];
3241 format = prop->format;
3242 if (format == GST_QT_MUX_FORMAT_NONE)
3245 /* create a cache for these properties */
3246 params = g_new0 (GstQTMuxClassParams, 1);
3247 params->prop = prop;
3248 params->src_caps = gst_static_caps_get (&prop->src_caps);
3249 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
3250 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
3252 /* create the type now */
3253 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
3255 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
3256 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
3258 if (!gst_element_register (plugin, prop->name, GST_RANK_PRIMARY, type))
3264 GST_LOG ("Finished registering muxers");
3266 /* FIXME: ideally classification tag should be added and
3267 registered in gstreamer core gsttaglist
3270 GST_LOG ("Registering tags");
3272 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
3273 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
3274 gst_tag_merge_use_first);
3276 GST_LOG ("Finished registering tags");