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 * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6 * Contact: Stefan Kost <stefan.kost@nokia.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
24 * Unless otherwise indicated, Source Code is licensed under MIT license.
25 * See further explanation attached in License Statement (distributed in the file
28 * Permission is hereby granted, free of charge, to any person obtaining a copy of
29 * this software and associated documentation files (the "Software"), to deal in
30 * the Software without restriction, including without limitation the rights to
31 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32 * of the Software, and to permit persons to whom the Software is furnished to do
33 * so, subject to the following conditions:
35 * The above copyright notice and this permission notice shall be included in all
36 * copies or substantial portions of the Software.
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49 * SECTION:element-qtmux
50 * @short_description: Muxer for quicktime(.mov) files
52 * This element merges streams (audio and video) into QuickTime(.mov) files.
54 * The following background intends to explain why various similar muxers
55 * are present in this plugin.
57 * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58 * QuickTime file format specification</ulink> served as basis for the MP4 file
59 * format specification (mp4mux), and as such the QuickTime file structure is
60 * nearly identical to the so-called ISO Base Media file format defined in
61 * ISO 14496-12 (except for some media specific parts).
62 * In turn, the latter ISO Base Media format was further specialized as a
63 * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64 * and in various 3GPP(2) specs (gppmux).
65 * The fragmented file features defined (only) in ISO Base Media are used by
66 * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
68 * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale,
69 * #GstQTMuxPad:trak-timescale) allow adjusting some technical parameters,
70 * which might be useful in (rare) cases to resolve compatibility issues in
73 * Some other properties influence the result more fundamentally.
74 * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
75 * file, somewhat contrary to this usually being called "the header".
76 * However, a #GstQTMux:faststart file will (with some effort) arrange this to
77 * be located near start of the file, which then allows it e.g. to be played
78 * while downloading. Alternatively, rather than having one chunk of metadata at
79 * start (or end), there can be some metadata at start and most of the other
80 * data can be spread out into fragments of #GstQTMux:fragment-duration.
81 * If such fragmented layout is intended for streaming purposes, then
82 * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
85 * When the maximum duration to be recorded can be known in advance, #GstQTMux
86 * also supports a 'Robust Muxing' mode. In robust muxing mode, space for the
87 * headers are reserved at the start of muxing, and rewritten at a configurable
88 * interval, so that the output file is always playable, even if the recording
89 * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
90 * output, such as filesink, because it needs to rewrite the start of the file.
92 * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
93 * and #GstQTMux::reserved-max-duration property. Also present is the
94 * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
95 * for some reason the default is not large enough and the initial reserved
96 * space for headers is too small. Applications can monitor the
97 * #GstQTMux::reserved-duration-remaining property to see how close to full
98 * the reserved space is becoming.
100 * Applications that wish to be able to use/edit a file while it is being
101 * written to by live content, can use the "Robust Prefill Muxing" mode. That
102 * mode is a variant of the "Robust Muxing" mode in that it will pre-allocate a
103 * completely valid header from the start for all tracks (i.e. it appears as
104 * though the file is "reserved-max-duration" long with all samples
105 * present). This mode can be enabled by setting the
106 * #GstQTMux::reserved-moov-update-period and #GstQTMux::reserved-prefill
107 * properties. Note that this mode is only possible with input streams that have
108 * a fixed sample size (such as raw audio and Prores Video) and that don't
109 * have reordered samples.
112 * <title>Example pipelines</title>
114 * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
116 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
128 #include <glib/gstdio.h>
131 #include <gst/base/gstcollectpads.h>
132 #include <gst/base/gstbytereader.h>
133 #include <gst/base/gstbitreader.h>
134 #include <gst/audio/audio.h>
135 #include <gst/video/video.h>
136 #include <gst/tag/tag.h>
137 #include <gst/pbutils/pbutils.h>
139 #include <sys/types.h>
141 #include <io.h> /* lseek, open, close, read */
143 #define lseek _lseeki64
145 #define off_t guint64
149 #define ftruncate g_win32_ftruncate
156 #include "gstqtmux.h"
158 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
159 #define GST_CAT_DEFAULT gst_qt_mux_debug
162 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
167 * The basic building blocks of MP4 files are:
168 * - an 'ftyp' box at the very start
169 * - an 'mdat' box which contains the raw audio/video/subtitle data;
170 * this is just a bunch of bytes, completely unframed and possibly
171 * unordered with no additional meta-information
172 * - a 'moov' box that contains information about the different streams
173 * and what they contain, as well as sample tables for each stream
174 * that tell the demuxer where in the mdat box each buffer/sample is
175 * and what its duration/timestamp etc. is, and whether it's a
177 * Additionally, fragmented MP4 works by writing chunks of data in
178 * pairs of 'moof' and 'mdat' boxes:
179 * - 'moof' boxes, header preceding each mdat fragment describing the
180 * contents, like a moov but only for that fragment.
181 * - a 'mfra' box for Fragmented MP4, which is written at the end and
182 * contains a summary of all fragments and seek tables.
184 * Currently mp4mux can work in 4 different modes / generate 4 types
185 * of output files/streams:
187 * - Normal mp4: mp4mux will write a little ftyp identifier at the
188 * beginning, then start an mdat box into which it will write all the
189 * sample data. At EOS it will then write the moov header with track
190 * headers and sample tables at the end of the file, and rewrite the
191 * start of the file to fix up the mdat box size at the beginning.
192 * It has to wait for EOS to write the moov (which includes the
193 * sample tables) because it doesn't know how much space those
194 * tables will be. The output downstream must be seekable to rewrite
195 * the mdat box at EOS.
197 * - Fragmented mp4: moov header with track headers at start
198 * but no sample table, followed by N fragments, each containing
199 * track headers with sample tables followed by some data. Downstream
200 * does not need to be seekable if the 'streamable' flag is TRUE,
201 * as the final mfra and total duration will be omitted.
203 * - Fast-start mp4: the goal here is to create a file where the moov
204 * headers are at the beginning; what mp4mux will do is write all
205 * sample data into a temp file and build moov header plus sample
206 * tables in memory and then when EOS comes, it will push out the
207 * moov header plus sample tables at the beginning, followed by the
208 * mdat sample data at the end which is read in from the temp file
209 * Files created in this mode are better for streaming over the
210 * network, since the client doesn't have to seek to the end of the
211 * file to get the headers, but it requires copying all sample data
212 * out of the temp file at EOS, which can be expensive. Downstream does
213 * not need to be seekable, because of the use of the temp file.
215 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
216 * and reserved-moov-update-period properties to reserve free space
217 * at the start of the file and periodically write the MOOV atom out
218 * to it. That means that killing the muxing at any point still
219 * results in a playable file, at the cost of wasting some amount of
220 * free space at the start of file. The approximate recording duration
221 * has to be known in advance to estimate how much free space to reserve
222 * for the moov, and the downstream must be seekable.
223 * If the moov header grows larger than the reserved space, an error
224 * is generated - so it's better to over-estimate the amount of space
225 * to reserve. To ensure the file is playable at any point, the moov
226 * is updated using a 'ping-pong' strategy, so the output is never in
230 #ifndef GST_REMOVE_DEPRECATED
239 gst_qt_mux_dts_method_get_type (void)
241 static GType gst_qt_mux_dts_method = 0;
243 if (!gst_qt_mux_dts_method) {
244 static const GEnumValue dts_methods[] = {
245 {DTS_METHOD_DD, "delta/duration", "dd"},
246 {DTS_METHOD_REORDER, "reorder", "reorder"},
247 {DTS_METHOD_ASC, "ascending", "asc"},
251 gst_qt_mux_dts_method =
252 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
255 return gst_qt_mux_dts_method;
258 #define GST_TYPE_QT_MUX_DTS_METHOD \
259 (gst_qt_mux_dts_method_get_type ())
265 PROP_PAD_TRAK_TIMESCALE,
268 #define DEFAULT_PAD_TRAK_TIMESCALE 0
270 GType gst_qt_mux_pad_get_type (void);
272 #define GST_TYPE_QT_MUX_PAD \
273 (gst_qt_mux_pad_get_type())
274 #define GST_QT_MUX_PAD(obj) \
275 (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_QT_MUX_PAD, GstQTMuxPad))
276 #define GST_QT_MUX_PAD_CLASS(klass) \
277 (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_QT_MUX_PAD, GstQTMuxPadClass))
278 #define GST_IS_QT_MUX_PAD(obj) \
279 (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_QT_MUX_PAD))
280 #define GST_IS_QT_MUX_PAD_CLASS(klass) \
281 (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_QT_MUX_PAD))
282 #define GST_QT_MUX_PAD_CAST(obj) \
283 ((GstQTMuxPad *)(obj))
285 typedef struct _GstQTMuxPad GstQTMuxPad;
286 typedef struct _GstQTMuxPadClass GstQTMuxPadClass;
292 guint32 trak_timescale;
295 struct _GstQTMuxPadClass
300 G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_PAD);
303 gst_qt_mux_pad_set_property (GObject * object,
304 guint prop_id, const GValue * value, GParamSpec * pspec)
306 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
308 GST_OBJECT_LOCK (pad);
310 case PROP_PAD_TRAK_TIMESCALE:
311 pad->trak_timescale = g_value_get_uint (value);
314 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
317 GST_OBJECT_UNLOCK (pad);
321 gst_qt_mux_pad_get_property (GObject * object,
322 guint prop_id, GValue * value, GParamSpec * pspec)
324 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
326 GST_OBJECT_LOCK (pad);
328 case PROP_PAD_TRAK_TIMESCALE:
329 g_value_set_uint (value, pad->trak_timescale);
332 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
335 GST_OBJECT_UNLOCK (pad);
339 gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
341 GObjectClass *gobject_class = (GObjectClass *) klass;
343 gobject_class->get_property = gst_qt_mux_pad_get_property;
344 gobject_class->set_property = gst_qt_mux_pad_set_property;
346 g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
347 g_param_spec_uint ("trak-timescale", "Track timescale",
348 "Timescale to use for this pad's trak (units per second, 0 is automatic)",
349 0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
350 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
354 gst_qt_mux_pad_init (GstQTMuxPad * pad)
356 pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
360 gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
364 GST_OBJECT_LOCK (pad);
365 timescale = pad->trak_timescale;
366 GST_OBJECT_UNLOCK (pad);
371 /* QTMux signals and args */
381 PROP_MOVIE_TIMESCALE,
384 PROP_FAST_START_TEMP_FILE,
385 PROP_MOOV_RECOV_FILE,
386 PROP_FRAGMENT_DURATION,
388 PROP_RESERVED_MAX_DURATION,
389 PROP_RESERVED_DURATION_REMAINING,
390 PROP_RESERVED_MOOV_UPDATE_PERIOD,
391 PROP_RESERVED_BYTES_PER_SEC,
392 PROP_RESERVED_PREFILL,
393 #ifndef GST_REMOVE_DEPRECATED
397 PROP_INTERLEAVE_BYTES,
398 PROP_INTERLEAVE_TIME,
399 PROP_MAX_RAW_AUDIO_DRIFT,
402 /* some spare for header size as well */
403 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
405 #define DEFAULT_MOVIE_TIMESCALE 0
406 #define DEFAULT_TRAK_TIMESCALE 0
407 #define DEFAULT_DO_CTTS TRUE
408 #define DEFAULT_FAST_START FALSE
409 #define DEFAULT_FAST_START_TEMP_FILE NULL
410 #define DEFAULT_MOOV_RECOV_FILE NULL
411 #define DEFAULT_FRAGMENT_DURATION 0
412 #define DEFAULT_STREAMABLE TRUE
413 #ifndef GST_REMOVE_DEPRECATED
414 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
416 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
417 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
418 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
419 #define DEFAULT_RESERVED_PREFILL FALSE
420 #define DEFAULT_INTERLEAVE_BYTES 0
421 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
422 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
424 static void gst_qt_mux_finalize (GObject * object);
426 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
427 GstStateChange transition);
429 /* property functions */
430 static void gst_qt_mux_set_property (GObject * object,
431 guint prop_id, const GValue * value, GParamSpec * pspec);
432 static void gst_qt_mux_get_property (GObject * object,
433 guint prop_id, GValue * value, GParamSpec * pspec);
436 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
437 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
438 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
441 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
442 GstCollectData * data, GstEvent * event, gpointer user_data);
444 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
446 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
450 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
452 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
453 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
455 static GstElementClass *parent_class = NULL;
458 gst_qt_mux_base_init (gpointer g_class)
460 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
461 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
462 GstQTMuxClassParams *params;
463 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
465 GstPadTemplate *srctempl;
466 gchar *longname, *description;
469 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
470 GST_QT_MUX_PARAMS_QDATA);
471 g_assert (params != NULL);
473 /* construct the element details struct */
474 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
475 description = g_strdup_printf ("Multiplex audio and video into a %s file",
476 params->prop->long_name);
477 gst_element_class_set_static_metadata (element_class, longname,
478 "Codec/Muxer", description,
479 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
481 g_free (description);
484 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
485 GST_PAD_ALWAYS, params->src_caps);
486 gst_element_class_add_pad_template (element_class, srctempl);
488 if (params->audio_sink_caps) {
489 audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
490 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
491 GST_TYPE_QT_MUX_PAD);
492 gst_element_class_add_pad_template (element_class, audiosinktempl);
495 if (params->video_sink_caps) {
496 videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
497 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
498 GST_TYPE_QT_MUX_PAD);
499 gst_element_class_add_pad_template (element_class, videosinktempl);
502 if (params->subtitle_sink_caps) {
503 subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
504 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
505 GST_TYPE_QT_MUX_PAD);
506 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
509 if (params->caption_sink_caps) {
510 captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
511 GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
512 GST_TYPE_QT_MUX_PAD);
513 gst_element_class_add_pad_template (element_class, captionsinktempl);
516 klass->format = params->prop->format;
520 gst_qt_mux_class_init (GstQTMuxClass * klass)
522 GObjectClass *gobject_class;
523 GstElementClass *gstelement_class;
524 GParamFlags streamable_flags;
525 const gchar *streamable_desc;
527 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
528 "be streamed and hence no indexes written or duration written."
530 gobject_class = (GObjectClass *) klass;
531 gstelement_class = (GstElementClass *) klass;
533 parent_class = g_type_class_peek_parent (klass);
535 gobject_class->finalize = gst_qt_mux_finalize;
536 gobject_class->get_property = gst_qt_mux_get_property;
537 gobject_class->set_property = gst_qt_mux_set_property;
539 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
540 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
541 streamable_desc = STREAMABLE_DESC;
542 streamable = DEFAULT_STREAMABLE;
545 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
546 streamable_flags |= G_PARAM_DEPRECATED;
550 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
551 g_param_spec_uint ("movie-timescale", "Movie timescale",
552 "Timescale to use in the movie (units per second, 0 == default)",
553 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
554 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
555 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
556 g_param_spec_uint ("trak-timescale", "Track timescale",
557 "Timescale to use for the tracks (units per second, 0 is automatic)",
558 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
559 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
560 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
561 g_param_spec_boolean ("presentation-time",
562 "Include presentation-time info",
563 "Calculate and include presentation/composition time "
564 "(in addition to decoding time)", DEFAULT_DO_CTTS,
565 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
566 #ifndef GST_REMOVE_DEPRECATED
567 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
568 g_param_spec_enum ("dts-method", "dts-method",
569 "Method to determine DTS time (DEPRECATED)",
570 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
571 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
572 G_PARAM_STATIC_STRINGS));
574 g_object_class_install_property (gobject_class, PROP_FAST_START,
575 g_param_spec_boolean ("faststart", "Format file to faststart",
576 "If the file should be formatted for faststart (headers first)",
577 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
578 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
579 g_param_spec_string ("faststart-file", "File to use for storing buffers",
580 "File that will be used temporarily to store data from the stream "
581 "when creating a faststart file. If null a filepath will be "
582 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
583 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
584 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
585 g_param_spec_string ("moov-recovery-file",
586 "File to store data for posterior moov atom recovery",
587 "File to be used to store "
588 "data for moov atom making movie file recovery possible in case "
589 "of a crash during muxing. Null for disabled. (Experimental)",
590 DEFAULT_MOOV_RECOV_FILE,
591 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
592 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
593 g_param_spec_uint ("fragment-duration", "Fragment duration",
594 "Fragment durations in ms (produce a fragmented file if > 0)",
595 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
596 2000 : DEFAULT_FRAGMENT_DURATION,
597 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
598 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
599 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
600 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
601 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
602 g_param_spec_uint64 ("reserved-max-duration",
603 "Reserved maximum file duration (ns)",
604 "When set to a value > 0, reserves space for index tables at the "
605 "beginning of the file.",
606 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
607 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
608 g_object_class_install_property (gobject_class,
609 PROP_RESERVED_DURATION_REMAINING,
610 g_param_spec_uint64 ("reserved-duration-remaining",
611 "Report the approximate amount of remaining recording space (ns)",
612 "Reports the approximate amount of remaining moov header space "
613 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
614 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
615 g_object_class_install_property (gobject_class,
616 PROP_RESERVED_MOOV_UPDATE_PERIOD,
617 g_param_spec_uint64 ("reserved-moov-update-period",
618 "Interval at which to update index tables (ns)",
619 "When used with reserved-max-duration, periodically updates the "
620 "index tables with information muxed so far.", 0, G_MAXUINT64,
621 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
622 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
623 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
624 g_param_spec_uint ("reserved-bytes-per-sec",
625 "Reserved MOOV bytes per second, per track",
626 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
627 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
628 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
629 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
630 g_param_spec_boolean ("reserved-prefill",
631 "Reserved Prefill Samples Table",
632 "Prefill samples table of reserved duration",
633 DEFAULT_RESERVED_PREFILL,
634 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
635 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
636 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
637 "Interleave between streams in bytes",
638 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
639 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
640 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
641 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
642 "Interleave between streams in nanoseconds",
643 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
644 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
645 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
646 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
647 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
648 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
649 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
651 gstelement_class->request_new_pad =
652 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
653 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
654 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
658 gst_qt_mux_pad_reset (GstQTPad * qtpad)
661 qtpad->is_out_of_order = FALSE;
662 qtpad->sample_size = 0;
665 qtpad->sample_offset = 0;
666 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
667 qtpad->first_ts = GST_CLOCK_TIME_NONE;
668 qtpad->first_dts = GST_CLOCK_TIME_NONE;
669 qtpad->prepare_buf_func = NULL;
670 qtpad->create_empty_buffer = NULL;
671 qtpad->avg_bitrate = 0;
672 qtpad->max_bitrate = 0;
673 qtpad->total_duration = 0;
674 qtpad->total_bytes = 0;
675 qtpad->sparse = FALSE;
677 gst_buffer_replace (&qtpad->last_buf, NULL);
680 gst_tag_list_unref (qtpad->tags);
684 /* reference owned elsewhere */
686 qtpad->tc_trak = NULL;
689 atom_traf_free (qtpad->traf);
692 atom_array_clear (&qtpad->fragment_buffers);
694 g_array_unref (qtpad->samples);
695 qtpad->samples = NULL;
697 /* reference owned elsewhere */
700 qtpad->first_pts = GST_CLOCK_TIME_NONE;
703 gst_video_time_code_free (qtpad->first_tc);
704 qtpad->first_tc = NULL;
706 if (qtpad->raw_audio_adapter)
707 gst_object_unref (qtpad->raw_audio_adapter);
708 qtpad->raw_audio_adapter = NULL;
712 * Takes GstQTMux back to its initial state
715 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
719 qtmux->state = GST_QT_MUX_STATE_NONE;
720 qtmux->header_size = 0;
721 qtmux->mdat_size = 0;
724 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
725 qtmux->fragment_sequence = 0;
728 atom_ftyp_free (qtmux->ftyp);
732 atom_moov_free (qtmux->moov);
736 atom_mfra_free (qtmux->mfra);
739 if (qtmux->fast_start_file) {
740 fclose (qtmux->fast_start_file);
741 g_remove (qtmux->fast_start_file_path);
742 qtmux->fast_start_file = NULL;
744 if (qtmux->moov_recov_file) {
745 fclose (qtmux->moov_recov_file);
746 qtmux->moov_recov_file = NULL;
748 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
749 AtomInfo *ainfo = (AtomInfo *) walk->data;
750 ainfo->free_func (ainfo->atom);
753 g_slist_free (qtmux->extra_atoms);
754 qtmux->extra_atoms = NULL;
756 GST_OBJECT_LOCK (qtmux);
757 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
758 GST_OBJECT_UNLOCK (qtmux);
761 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
762 GstQTPad *qtpad = (GstQTPad *) walk->data;
763 gst_qt_mux_pad_reset (qtpad);
765 /* hm, moov_free above yanked the traks away from us,
766 * so do not free, but do clear */
771 qtmux->moov = atom_moov_new (qtmux->context);
772 /* ensure all is as nice and fresh as request_new_pad would provide it */
773 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
774 GstQTPad *qtpad = (GstQTPad *) walk->data;
776 qtpad->trak = atom_trak_new (qtmux->context);
777 atom_moov_add_trak (qtmux->moov, qtpad->trak);
781 qtmux->current_pad = NULL;
782 qtmux->current_chunk_size = 0;
783 qtmux->current_chunk_duration = 0;
784 qtmux->current_chunk_offset = -1;
786 qtmux->reserved_moov_size = 0;
787 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
788 qtmux->muxed_since_last_update = 0;
789 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
793 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
795 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
796 GstPadTemplate *templ;
798 templ = gst_element_class_get_pad_template (klass, "src");
799 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
800 gst_pad_use_fixed_caps (qtmux->srcpad);
801 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
803 qtmux->sinkpads = NULL;
804 qtmux->collect = gst_collect_pads_new ();
805 gst_collect_pads_set_event_function (qtmux->collect,
806 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
807 gst_collect_pads_set_clip_function (qtmux->collect,
808 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
809 gst_collect_pads_set_function (qtmux->collect,
810 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
812 /* properties set to default upon construction */
814 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
815 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
816 qtmux->reserved_bytes_per_sec_per_trak =
817 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
818 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
819 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
820 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
822 /* always need this */
824 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
826 /* internals to initial state */
827 gst_qt_mux_reset (qtmux, TRUE);
832 gst_qt_mux_finalize (GObject * object)
834 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
836 gst_qt_mux_reset (qtmux, FALSE);
838 g_free (qtmux->fast_start_file_path);
839 g_free (qtmux->moov_recov_file_path);
841 atoms_context_free (qtmux->context);
842 gst_object_unref (qtmux->collect);
844 g_slist_free (qtmux->sinkpads);
846 G_OBJECT_CLASS (parent_class)->finalize (object);
850 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
857 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
862 size = gst_buffer_get_size (buf);
863 newbuf = gst_buffer_new_and_alloc (size + 8);
864 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
866 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
867 GST_WRITE_UINT32_BE (map.data, map.size);
868 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
870 gst_buffer_unmap (buf, &map);
871 gst_buffer_unref (buf);
877 extract_608_field_from_cc_data (const guint8 * ccdata, gsize ccdata_size,
878 guint field, guint8 ** res)
881 gsize storage_size = 128;
882 gsize i, res_size = 0;
884 storage = g_malloc0 (storage_size);
886 /* Iterate over the ccdata and put the corresponding tuples for the given field
888 for (i = 0; i < ccdata_size; i += 3) {
889 if ((field == 1 && ccdata[i * 3] == 0xfc) ||
890 (field == 2 && ccdata[i * 3] == 0xfd)) {
891 GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
892 ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
893 if (res_size >= storage_size) {
895 storage = g_realloc (storage, storage_size);
897 storage[res_size] = ccdata[i * 3 + 1];
898 storage[res_size + 1] = ccdata[i * 3 + 2];
915 gst_qt_mux_prepare_caption_buffer (GstQTPad * qtpad, GstBuffer * buf,
918 GstBuffer *newbuf = NULL;
919 GstMapInfo map, inmap;
926 in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
928 size = gst_buffer_get_size (buf);
929 gst_buffer_map (buf, &inmap, GST_MAP_READ);
931 GST_LOG_OBJECT (qtmux,
932 "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
933 GST_FOURCC_ARGS (qtpad->fourcc), size);
935 switch (qtpad->fourcc) {
939 gsize cdat_size, cdt2_size, total_size = 0;
940 gsize write_offs = 0;
942 cdat_size = extract_608_field_from_cc_data (map.data, map.size, 1, &cdat);
943 cdt2_size = extract_608_field_from_cc_data (map.data, map.size, 2, &cdt2);
946 total_size += cdat_size + 8;
948 total_size += cdt2_size + 8;
949 if (total_size == 0) {
950 GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
951 /* FIXME : We might want to *always* store something, even if
952 * it's "empty" CC (i.e. 0x80 0x80) */
956 newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
957 /* Let's copy over all metadata and not the memory */
958 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
960 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
961 if (cdat_size || in_prefill) {
962 GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
963 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
965 memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
967 /* Write 'empty' CC */
971 write_offs = in_prefill ? 10 : cdat_size + 8;
976 if (cdt2_size || in_prefill) {
977 GST_WRITE_UINT32_BE (map.data + write_offs,
978 in_prefill ? 10 : cdt2_size + 8);
979 GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
981 memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
983 /* Write 'empty' CC */
984 map.data[write_offs + 8] = 0x80;
985 map.data[write_offs + 9] = 0x80;
990 gst_buffer_unmap (newbuf, &map);
996 /* Take the whole CDP */
997 if (in_prefill && size > 92) {
998 GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1001 newbuf = gst_buffer_new_and_alloc (in_prefill ? 100 : size + 8);
1003 /* Let's copy over all metadata and not the memory */
1004 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1006 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1008 GST_WRITE_UINT32_BE (map.data, size + 8);
1009 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1010 memcpy (map.data + 8, inmap.data, inmap.size);
1012 gst_buffer_unmap (newbuf, &map);
1016 /* theoretically this should never happen, but let's keep this here in case */
1017 GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1021 gst_buffer_unmap (buf, &inmap);
1022 gst_buffer_unref (buf);
1028 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1035 const guint8 *dataend;
1037 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1042 gst_buffer_map (buf, &frommap, GST_MAP_READ);
1044 dataend = memchr (frommap.data, 0, frommap.size);
1045 size = dataend ? dataend - frommap.data : frommap.size;
1046 newbuf = gst_buffer_new_and_alloc (size + 2);
1048 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1050 GST_WRITE_UINT16_BE (tomap.data, size);
1051 memcpy (tomap.data + 2, frommap.data, size);
1053 gst_buffer_unmap (newbuf, &tomap);
1054 gst_buffer_unmap (buf, &frommap);
1056 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1058 /* gst_buffer_copy_into is trying to be too clever and
1059 * won't copy duration when size is different */
1060 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1062 gst_buffer_unref (buf);
1068 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1069 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1074 g_return_if_fail (qtpad->trak_ste);
1076 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
1078 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1082 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1086 GstByteReader reader;
1089 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1090 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1094 if (G_UNLIKELY (map.size < 8))
1097 gst_byte_reader_init (&reader, map.data, map.size);
1098 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1103 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1105 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1108 gst_bit_reader_init (&bits, map.data, map.size);
1110 /* off + sync + crc */
1111 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1113 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1114 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1115 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1116 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1117 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1119 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1120 gst_bit_reader_skip_unchecked (&bits, 2);
1121 if ((acmod & 0x4)) /* if a surround channel exists */
1122 gst_bit_reader_skip_unchecked (&bits, 2);
1123 if (acmod == 0x2) /* if in 2/0 mode */
1124 gst_bit_reader_skip_unchecked (&bits, 2);
1126 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1128 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1129 bsmod, acmod, lfe_on);
1131 /* AC-3 spec says that those values should be constant for the
1132 * whole stream when muxed in mp4. We trust the input follows it */
1133 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1134 "prepare buffer function");
1135 qtpad->prepare_buf_func = NULL;
1139 gst_buffer_unmap (buf, &map);
1144 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1148 data = g_malloc (2);
1149 GST_WRITE_UINT16_BE (data, 0);
1151 return gst_buffer_new_wrapped (data, 2);
1155 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1156 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1158 switch (gst_tag_get_type (tag)) {
1164 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1166 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1167 GST_FOURCC_ARGS (fourcc), str);
1168 atom_udta_add_str_tag (udta, fourcc, str);
1177 if (!gst_tag_list_get_double (list, tag, &value))
1179 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1180 GST_FOURCC_ARGS (fourcc), (gint) value);
1181 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1188 /* paired unsigned integers */
1192 got_tag = gst_tag_list_get_uint (list, tag, &value);
1193 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1196 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1197 GST_FOURCC_ARGS (fourcc), value, count);
1198 atom_udta_add_uint_tag (udta, fourcc, 0,
1199 value << 16 | (count & 0xFFFF));
1201 /* unpaired unsigned integers */
1202 if (!gst_tag_list_get_uint (list, tag, &value))
1204 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1205 GST_FOURCC_ARGS (fourcc), value);
1206 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1211 g_assert_not_reached ();
1217 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1218 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1226 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1228 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1231 year = g_date_get_year (date);
1232 month = g_date_get_month (date);
1233 day = g_date_get_day (date);
1237 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1238 day == G_DATE_BAD_DAY) {
1239 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1243 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1244 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1245 GST_FOURCC_ARGS (fourcc), str);
1246 atom_udta_add_str_tag (udta, fourcc, str);
1251 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1252 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1254 GValue value = { 0, };
1258 GstStructure *structure;
1262 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1264 if (!gst_tag_list_copy_value (&value, list, tag))
1267 sample = gst_value_get_sample (&value);
1272 buf = gst_sample_get_buffer (sample);
1276 caps = gst_sample_get_caps (sample);
1278 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1282 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1284 structure = gst_caps_get_structure (caps, 0);
1285 if (gst_structure_has_name (structure, "image/jpeg"))
1287 else if (gst_structure_has_name (structure, "image/png"))
1291 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1295 gst_buffer_map (buf, &map, GST_MAP_READ);
1296 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1297 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1298 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1299 gst_buffer_unmap (buf, &map);
1301 g_value_unset (&value);
1305 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1306 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1311 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1312 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1314 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1318 if (!gst_tag_list_get_uint (list, tag2, &number))
1322 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1323 GST_FOURCC_ARGS (fourcc), str);
1324 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1326 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1327 GST_FOURCC_ARGS (fourcc), str, number);
1328 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1335 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1336 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1341 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1343 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1346 year = g_date_get_year (date);
1349 if (year == G_DATE_BAD_YEAR) {
1350 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1354 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1355 GST_FOURCC_ARGS (fourcc), year);
1356 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1360 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1361 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1363 gdouble latitude = -360, longitude = -360, altitude = 0;
1364 gchar *location = NULL;
1365 guint8 *data, *ddata;
1366 gint size = 0, len = 0;
1367 gboolean ret = FALSE;
1369 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1371 ret = gst_tag_list_get_string (list, tag, &location);
1372 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1374 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1376 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1383 len = strlen (location);
1384 size += len + 1 + 2;
1386 /* role + (long, lat, alt) + body + notes */
1387 size += 1 + 3 * 4 + 1 + 1;
1389 data = ddata = g_malloc (size);
1392 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1395 memcpy (data + 2, location, len);
1396 GST_WRITE_UINT8 (data + 2 + len, 0);
1397 data += len + 1 + 2;
1399 GST_WRITE_UINT8 (data, 0);
1400 /* long, lat, alt */
1401 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1402 QT_WRITE_SFP32 (data + 1, longitude);
1403 QT_WRITE_SFP32 (data + 5, latitude);
1404 QT_WRITE_SFP32 (data + 9, altitude);
1405 /* neither astronomical body nor notes */
1406 GST_WRITE_UINT16_BE (data + 13, 0);
1408 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1409 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1414 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1415 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1417 gchar *keywords = NULL;
1418 guint8 *data, *ddata;
1422 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1424 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1427 kwds = g_strsplit (keywords, ",", 0);
1431 for (i = 0; kwds[i]; i++) {
1432 /* size byte + null-terminator */
1433 size += strlen (kwds[i]) + 1 + 1;
1436 /* language tag + count + keywords */
1439 data = ddata = g_malloc (size);
1442 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1444 GST_WRITE_UINT8 (data + 2, i);
1447 for (i = 0; kwds[i]; ++i) {
1448 gint len = strlen (kwds[i]);
1450 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1451 GST_FOURCC_ARGS (fourcc), kwds[i]);
1453 GST_WRITE_UINT8 (data, len + 1);
1454 memcpy (data + 1, kwds[i], len + 1);
1460 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1465 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1466 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1474 size = strlen (input);
1476 if (size < 4 + 3 + 1 + 1 + 1) {
1477 /* at least the minimum xxxx://y/z */
1478 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1483 /* read the fourcc */
1484 memcpy (&fourcc, data, 4);
1488 if (strncmp (data, "://", 3) != 0) {
1494 /* read the table number */
1495 if (sscanf (data, "%d", &table) != 1) {
1499 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1500 ", table numbers should be positive, ignoring tag", table);
1504 /* find the next / */
1505 while (size > 0 && data[0] != '/') {
1512 g_assert (data[0] == '/');
1521 /* read up the rest of the string */
1522 *p_content = g_strdup (data);
1523 *p_table = (guint16) table;
1529 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1530 "input (%s) didn't match the expected entitycode://table/content",
1537 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1538 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1540 gchar *clsf_data = NULL;
1544 gchar *content = NULL;
1547 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1549 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1552 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1553 GST_FOURCC_ARGS (fourcc), clsf_data);
1555 /* parse the string, format is:
1556 * entityfourcc://table/content
1558 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1562 size = strlen (content) + 1;
1564 /* now we have everything, build the atom
1565 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1566 data = g_malloc (4 + 2 + 2 + size);
1567 GST_WRITE_UINT32_LE (data, entity);
1568 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1569 GST_WRITE_UINT16_BE (data + 6, 0);
1570 memcpy (data + 8, content, size);
1573 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1577 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1578 const GstTagList * list, AtomUDTA * udta, const char *tag,
1579 const char *tag2, guint32 fourcc);
1582 * Struct to record mappings from gstreamer tags to fourcc codes
1584 typedef struct _GstTagToFourcc
1587 const gchar *gsttag;
1588 const gchar *gsttag2;
1589 const GstQTMuxAddUdtaTagFunc func;
1592 /* tag list tags to fourcc matching */
1593 static const GstTagToFourcc tag_matches_mp4[] = {
1594 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1595 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1596 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1597 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1598 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1599 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1600 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1601 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1602 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1603 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1604 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1605 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1606 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1607 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1608 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1609 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1610 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1611 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1612 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1613 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1614 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1615 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1616 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1617 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1618 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1619 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1620 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1621 gst_qt_mux_add_mp4_tag},
1622 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1623 gst_qt_mux_add_mp4_tag},
1624 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1625 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1629 static const GstTagToFourcc tag_matches_3gp[] = {
1630 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1631 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1632 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1633 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1634 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1635 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1636 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1637 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1638 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1639 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1640 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1641 gst_qt_mux_add_3gp_classification},
1645 /* qtdemux produces these for atoms it cannot parse */
1646 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1649 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1651 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1652 GstBuffer *xmp = NULL;
1654 /* adobe specs only have 'quicktime' and 'mp4',
1655 * but I guess we can extrapolate to gpp.
1656 * Keep mj2 out for now as we don't add any tags for it yet.
1657 * If you have further info about xmp on these formats, please share */
1658 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1661 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1663 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1664 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1667 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1670 /* for isom/mp4, it is a top level uuid atom */
1671 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1674 ainfo = build_uuid_xmp_atom (xmp);
1676 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1681 gst_buffer_unref (xmp);
1685 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1688 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1691 const gchar *tag, *tag2;
1692 const GstTagToFourcc *tag_matches;
1694 switch (qtmux_klass->format) {
1695 case GST_QT_MUX_FORMAT_3GP:
1696 tag_matches = tag_matches_3gp;
1698 case GST_QT_MUX_FORMAT_MJ2:
1702 /* sort of iTunes style for mp4 and QT (?) */
1703 tag_matches = tag_matches_mp4;
1710 /* Clear existing tags so we don't add them over and over */
1711 atom_udta_clear_tags (udta);
1713 for (i = 0; tag_matches[i].fourcc; i++) {
1714 fourcc = tag_matches[i].fourcc;
1715 tag = tag_matches[i].gsttag;
1716 tag2 = tag_matches[i].gsttag2;
1718 g_assert (tag_matches[i].func);
1719 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1722 /* add unparsed blobs if present */
1723 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1726 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1727 for (i = 0; i < num_tags; ++i) {
1728 GstSample *sample = NULL;
1730 const GstStructure *s;
1732 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1735 buf = gst_sample_get_buffer (sample);
1737 if (buf && (s = gst_sample_get_info (sample))) {
1738 const gchar *style = NULL;
1741 gst_buffer_map (buf, &map, GST_MAP_READ);
1742 GST_DEBUG_OBJECT (qtmux,
1743 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1744 GST_PTR_FORMAT, i, num_tags, map.size, s);
1745 if (s && (style = gst_structure_get_string (s, "style"))) {
1746 /* try to prevent some style tag ending up into another variant
1747 * (todo: make into a list if more cases) */
1748 if ((strcmp (style, "itunes") == 0 &&
1749 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1750 (strcmp (style, "iso") == 0 &&
1751 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1752 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1753 atom_udta_add_blob_tag (udta, map.data, map.size);
1756 gst_buffer_unmap (buf, &map);
1758 gst_sample_unref (sample);
1766 * Gets the tagsetter iface taglist and puts the known tags
1767 * into the output stream
1770 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1772 const GstTagList *tags = NULL;
1775 GST_OBJECT_LOCK (qtmux);
1776 if (qtmux->tags_changed) {
1777 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1778 qtmux->tags_changed = FALSE;
1780 GST_OBJECT_UNLOCK (qtmux);
1782 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1784 if (tags && !gst_tag_list_is_empty (tags)) {
1785 GstTagList *copy = gst_tag_list_copy (tags);
1787 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1788 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1789 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1790 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1792 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1793 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1794 gst_qt_mux_add_xmp_tags (qtmux, copy);
1795 gst_tag_list_unref (copy);
1797 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1800 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1801 GstCollectData *cdata = (GstCollectData *) walk->data;
1802 GstQTPad *qpad = (GstQTPad *) cdata;
1803 GstPad *pad = qpad->collect.pad;
1805 if (qpad->tags_changed && qpad->tags) {
1806 GST_DEBUG_OBJECT (pad, "Adding tags");
1807 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1808 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1809 qpad->tags_changed = FALSE;
1810 GST_DEBUG_OBJECT (pad, "Tags added");
1812 GST_DEBUG_OBJECT (pad, "No new tags received");
1817 static inline GstBuffer *
1818 _gst_buffer_new_take_data (guint8 * data, guint size)
1822 buf = gst_buffer_new ();
1823 gst_buffer_append_memory (buf,
1824 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1829 static GstFlowReturn
1830 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1836 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1838 size = gst_buffer_get_size (buf);
1839 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1841 if (mind_fast && qtmux->fast_start_file) {
1845 GST_LOG_OBJECT (qtmux, "to temporary file");
1846 gst_buffer_map (buf, &map, GST_MAP_READ);
1847 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1848 gst_buffer_unmap (buf, &map);
1849 gst_buffer_unref (buf);
1855 GST_LOG_OBJECT (qtmux, "downstream");
1856 res = gst_pad_push (qtmux->srcpad, buf);
1859 if (G_LIKELY (offset))
1867 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1868 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1869 return GST_FLOW_ERROR;
1874 gst_qt_mux_seek_to_beginning (FILE * f)
1877 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1879 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1880 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1883 if (fseek (f, (long) 0, SEEK_SET) != 0)
1889 static GstFlowReturn
1890 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1892 GstFlowReturn ret = GST_FLOW_OK;
1893 GstBuffer *buf = NULL;
1895 if (fflush (qtmux->fast_start_file))
1898 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1901 /* hm, this could all take a really really long time,
1902 * but there may not be another way to get moov atom first
1903 * (somehow optimize copy?) */
1904 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1905 while (ret == GST_FLOW_OK) {
1906 const int bufsize = 4096;
1910 buf = gst_buffer_new_and_alloc (bufsize);
1911 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1912 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1914 gst_buffer_unmap (buf, &map);
1917 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1918 gst_buffer_unmap (buf, &map);
1919 if (size != bufsize)
1920 gst_buffer_set_size (buf, size);
1921 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1925 gst_buffer_unref (buf);
1927 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1929 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1937 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1938 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1939 ret = GST_FLOW_ERROR;
1944 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1945 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1946 ret = GST_FLOW_ERROR;
1951 /* clear descriptor so we don't remove temp file later on,
1952 * might be possible to recover */
1953 fclose (qtmux->fast_start_file);
1954 qtmux->fast_start_file = NULL;
1960 * Sends the initial mdat atom fields (size fields and fourcc type),
1961 * the subsequent buffers are considered part of it's data.
1962 * As we can't predict the amount of data that we are going to place in mdat
1963 * we need to record the position of the size field in the stream so we can
1964 * seek back to it later and update when the streams have finished.
1966 static GstFlowReturn
1967 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1968 gboolean extended, gboolean fsync_after)
1973 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1974 "size %" G_GUINT64_FORMAT, size);
1976 /* if the qtmux state is EOS, really write the mdat, otherwise
1977 * allow size == 0 for a placeholder atom */
1978 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1982 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1983 /* Always write 16-bytes, but put a free atom first
1984 * if the size is < 4GB. */
1985 buf = gst_buffer_new_and_alloc (16);
1986 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1989 /* Write extended mdat header and large_size field */
1990 GST_WRITE_UINT32_BE (map.data, 1);
1991 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1992 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1994 /* Write an empty free atom, then standard 32-bit mdat */
1995 GST_WRITE_UINT32_BE (map.data, 8);
1996 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1997 GST_WRITE_UINT32_BE (map.data + 8, size);
1998 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2000 gst_buffer_unmap (buf, &map);
2002 buf = gst_buffer_new_and_alloc (8);
2003 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2005 /* Vanilla 32-bit mdat */
2006 GST_WRITE_UINT32_BE (map.data, size);
2007 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2008 gst_buffer_unmap (buf, &map);
2011 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2013 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2015 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2020 * We get the position of the mdat size field, seek back to it
2021 * and overwrite with the real value
2023 static GstFlowReturn
2024 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2025 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2029 /* We must have recorded the mdat position for this to work */
2030 g_assert (mdat_pos != 0);
2032 /* seek and rewrite the header */
2033 gst_segment_init (&segment, GST_FORMAT_BYTES);
2034 segment.start = mdat_pos;
2035 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2037 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2041 static GstFlowReturn
2042 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2045 guint64 size = 0, offset = 0;
2046 guint8 *data = NULL;
2048 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2050 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2051 goto serialize_error;
2053 buf = _gst_buffer_new_take_data (data, offset);
2055 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2056 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2061 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2062 ("Failed to serialize ftyp"));
2063 return GST_FLOW_ERROR;
2068 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2069 GstBuffer ** p_prefix)
2071 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2072 guint32 major, version;
2074 GstBuffer *prefix = NULL;
2075 AtomFTYP *ftyp = NULL;
2077 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2079 /* init and send context and ftyp based on current property state */
2080 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2081 &version, &comp, qtmux->moov, qtmux->longest_chunk,
2082 qtmux->fast_start_file != NULL);
2083 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2090 gst_buffer_unref (prefix);
2095 static GstFlowReturn
2096 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2098 GstFlowReturn ret = GST_FLOW_OK;
2099 GstBuffer *prefix = NULL;
2101 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2103 /* init and send context and ftyp based on current property state */
2105 atom_ftyp_free (qtmux->ftyp);
2108 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2110 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2111 if (ret != GST_FLOW_OK)
2114 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2118 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2120 GstStructure *structure;
2121 GValue array = { 0 };
2122 GValue value = { 0 };
2123 GstCaps *caps, *tcaps;
2125 tcaps = gst_pad_get_current_caps (mux->srcpad);
2126 caps = gst_caps_copy (tcaps);
2127 gst_caps_unref (tcaps);
2129 structure = gst_caps_get_structure (caps, 0);
2131 g_value_init (&array, GST_TYPE_ARRAY);
2133 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2134 g_value_init (&value, GST_TYPE_BUFFER);
2135 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2136 gst_value_array_append_value (&array, &value);
2137 g_value_unset (&value);
2139 gst_structure_set_value (structure, "streamheader", &array);
2140 g_value_unset (&array);
2141 gst_pad_set_caps (mux->srcpad, caps);
2142 gst_caps_unref (caps);
2146 * Write out a free space atom. The offset is adjusted by the full
2147 * size, but a smaller buffer is sent
2149 static GstFlowReturn
2150 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2151 gboolean fsync_after)
2155 guint8 *data = NULL;
2156 guint64 offset = 0, bsize = 0;
2159 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2161 /* We can't make a free space atom smaller than the header */
2165 node_header = g_malloc0 (sizeof (Atom));
2166 node_header->type = FOURCC_free;
2167 node_header->size = size;
2170 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2171 goto serialize_error;
2173 buf = _gst_buffer_new_take_data (data, offset);
2174 g_free (node_header);
2177 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2179 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2180 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2187 /* Make sure downstream position ends up at the end of this free box */
2188 gst_segment_init (&segment, GST_FORMAT_BYTES);
2189 segment.start = *off;
2190 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2198 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2199 ("Not enough free reserved space"));
2200 return GST_FLOW_ERROR;
2204 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2205 ("Failed to serialize mdat"));
2206 g_free (node_header);
2207 return GST_FLOW_ERROR;
2212 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2214 gboolean fragmented = FALSE;
2217 GST_OBJECT_LOCK (qtmux);
2218 timescale = qtmux->timescale;
2219 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2220 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2222 GST_OBJECT_UNLOCK (qtmux);
2224 /* inform lower layers of our property wishes, and determine duration.
2225 * Let moov take care of this using its list of traks;
2226 * so that released pads are also included */
2227 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2229 atom_moov_update_timescale (qtmux->moov, timescale);
2230 atom_moov_set_fragmented (qtmux->moov, fragmented);
2232 atom_moov_update_duration (qtmux->moov);
2235 static GstFlowReturn
2236 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2237 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2239 guint64 offset = 0, size = 0;
2242 GstFlowReturn ret = GST_FLOW_OK;
2244 guint64 current_time = atoms_get_current_qt_time ();
2246 /* update modification times */
2247 qtmux->moov->mvhd.time_info.modification_time = current_time;
2248 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2249 GstCollectData *cdata = (GstCollectData *) walk->data;
2250 GstQTPad *qtpad = (GstQTPad *) cdata;
2252 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2253 qtpad->trak->tkhd.modification_time = current_time;
2256 /* serialize moov */
2259 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2260 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2261 goto serialize_error;
2262 qtmux->last_moov_size = offset;
2264 /* Check we have enough reserved space for this and a Free atom */
2265 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2266 goto too_small_reserved;
2267 buf = _gst_buffer_new_take_data (data, offset);
2268 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2270 /* If at EOS, this is the final moov, put in the streamheader
2271 * (apparently used by a flumotion util) */
2272 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2273 gst_qt_mux_set_header_on_caps (qtmux, buf);
2276 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2277 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2279 /* Write out a free atom if needed */
2280 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2281 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2282 (guint32) (padded_moov_size - offset));
2284 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2291 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2292 ("Not enough free reserved header space"),
2293 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2294 offset, padded_moov_size));
2295 return GST_FLOW_ERROR;
2300 return GST_FLOW_ERROR;
2304 /* either calculates size of extra atoms or pushes them */
2305 static GstFlowReturn
2306 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2310 guint64 loffset = 0, size = 0;
2312 GstFlowReturn ret = GST_FLOW_OK;
2314 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2315 AtomInfo *ainfo = (AtomInfo *) walk->data;
2319 if (!ainfo->copy_data_func (ainfo->atom,
2320 send ? &data : NULL, &size, &loffset))
2321 goto serialize_error;
2326 GST_DEBUG_OBJECT (qtmux,
2327 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2328 GST_FOURCC_ARGS (ainfo->atom->type));
2329 buf = _gst_buffer_new_take_data (data, loffset);
2330 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2331 if (ret != GST_FLOW_OK)
2344 return GST_FLOW_ERROR;
2349 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2351 gboolean seekable = FALSE;
2352 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2354 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2355 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2356 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2358 /* have to assume seeking is not supported if query not handled downstream */
2359 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2362 gst_query_unref (query);
2368 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2371 gboolean fail = FALSE;
2372 AtomFTYP *ftyp = NULL;
2373 GstBuffer *prefix = NULL;
2375 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2376 qtmux->moov_recov_file_path);
2378 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2379 if (qtmux->moov_recov_file == NULL) {
2380 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2381 qtmux->moov_recov_file_path);
2385 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2387 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2388 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2389 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2393 atom_ftyp_free (ftyp);
2395 gst_buffer_unref (prefix);
2397 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2398 GstCollectData *cdata = (GstCollectData *) walk->data;
2399 GstQTPad *qpad = (GstQTPad *) cdata;
2400 /* write info for each stream */
2401 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2403 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2413 fclose (qtmux->moov_recov_file);
2414 qtmux->moov_recov_file = NULL;
2418 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2420 switch (qpad->fourcc) {
2429 return qpad->sample_offset;
2432 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2433 qpad->expected_sample_duration_n,
2434 qpad->expected_sample_duration_d *
2435 atom_trak_get_timescale (qpad->trak));
2442 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2444 switch (qpad->fourcc) {
2446 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2448 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2450 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2452 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2459 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2461 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2463 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2465 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2472 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2474 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2476 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2478 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2485 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2487 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2489 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2491 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2498 /* We always write both cdat and cdt2 atom in prefill mode */
2501 /* We're cheating a bit by always allocating 100bytes even if we use less */
2506 guint64 next_sample_offset;
2508 block_idx = prefill_get_block_index (qtmux, qpad);
2509 next_sample_offset =
2510 gst_util_uint64_scale (block_idx + 1,
2511 qpad->expected_sample_duration_d *
2512 atom_trak_get_timescale (qpad->trak),
2513 qpad->expected_sample_duration_n);
2515 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2520 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2528 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2530 switch (qpad->fourcc) {
2539 return gst_util_uint64_scale (qpad->sample_offset + 1,
2540 qpad->expected_sample_duration_d * GST_SECOND,
2541 qpad->expected_sample_duration_n);
2545 guint64 next_sample_offset;
2547 block_idx = prefill_get_block_index (qtmux, qpad);
2548 next_sample_offset =
2549 gst_util_uint64_scale (block_idx + 1,
2550 qpad->expected_sample_duration_d *
2551 atom_trak_get_timescale (qpad->trak),
2552 qpad->expected_sample_duration_n);
2554 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2555 atom_trak_get_timescale (qpad->trak));
2558 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2566 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2571 GstClockTime input_timestamp;
2572 guint64 input_timestamp_distance;
2575 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2577 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2578 qtpad->expected_sample_duration_n,
2579 qtpad->expected_sample_duration_d *
2580 atom_trak_get_timescale (qtpad->trak));
2582 gst_util_uint64_scale (block_idx + 1,
2583 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2584 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2586 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2587 GST_COLLECT_PADS_STATE_EOS)
2588 && gst_adapter_available (qtpad->raw_audio_adapter) <
2589 nsamples * qtpad->sample_size)
2590 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2595 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2596 &input_timestamp_distance);
2597 if (input_timestamp != GST_CLOCK_TIME_NONE)
2599 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2600 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2603 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2604 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2605 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2606 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2607 GST_BUFFER_PTS (buf) = input_timestamp;
2608 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2609 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2611 qtpad->raw_audio_adapter_offset += nsamples;
2613 /* Check if we have yet another block of raw audio in the adapter */
2615 gst_util_uint64_scale (block_idx + 2,
2616 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2617 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2618 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2619 nsamples * qtpad->sample_size) {
2621 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2622 &input_timestamp_distance);
2623 if (input_timestamp != GST_CLOCK_TIME_NONE)
2625 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2626 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2627 qtpad->raw_audio_adapter_pts = input_timestamp;
2629 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2636 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2640 /* Find the (first) video track and assume that we have to output
2642 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2643 GstCollectData *cdata = (GstCollectData *) walk->data;
2644 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2646 if (tmp_qpad->trak->is_video) {
2647 *dur_n = tmp_qpad->expected_sample_duration_n;
2648 *dur_d = tmp_qpad->expected_sample_duration_d;
2654 GST_INFO_OBJECT (qtmux,
2655 "Found no video framerate, using 40ms audio buffers");
2661 /* Called when all pads are prerolled to adjust and */
2663 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2665 switch (qpad->fourcc) {
2673 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2674 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2680 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2681 /* We need a "valid" duration */
2682 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2683 &qpad->expected_sample_duration_d);
2684 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2689 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2690 &qpad->expected_sample_duration_d);
2691 /* Set a prepare_buf_func that ensures this */
2692 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2693 qpad->raw_audio_adapter = gst_adapter_new ();
2694 qpad->raw_audio_adapter_offset = 0;
2695 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2704 /* Only called at startup when doing the "fake" iteration of all tracks in order
2705 * to prefill the sample tables in the header. */
2707 find_best_pad_prefill_start (GstQTMux * qtmux)
2710 GstQTPad *best_pad = NULL;
2712 /* If interleave limits have been specified and the current pad is within
2713 * those interleave limits, pick that one, otherwise let's try to figure out
2714 * the next best one. */
2715 if (qtmux->current_pad &&
2716 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2717 (qtmux->interleave_bytes == 0
2718 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2719 && (qtmux->interleave_time == 0
2720 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2721 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2722 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2724 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2725 best_pad = qtmux->current_pad;
2727 } else if (qtmux->collect->data->next) {
2728 /* Attempt to try another pad if we have one. Otherwise use the only pad
2730 best_pad = qtmux->current_pad = NULL;
2733 /* The next best pad is the one which has the lowest timestamp and hasn't
2734 * exceeded the reserved max duration */
2736 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2738 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2739 GstCollectData *cdata = (GstCollectData *) walk->data;
2740 GstQTPad *qtpad = (GstQTPad *) cdata;
2741 GstClockTime timestamp;
2743 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2746 timestamp = qtpad->total_duration;
2748 if (best_pad == NULL ||
2749 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2751 best_time = timestamp;
2759 /* Called when starting the file in prefill_mode to figure out all the entries
2760 * of the header based on the input stream and reserved maximum duration.
2762 * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2763 * will be updated and written on EOS. */
2765 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2769 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2771 /* Update expected sample sizes/durations as needed, this is for raw
2772 * audio where samples are actual audio samples. */
2773 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2774 GstCollectData *cdata = (GstCollectData *) walk->data;
2775 GstQTPad *qpad = (GstQTPad *) cdata;
2777 if (!prefill_update_sample_size (qtmux, qpad))
2781 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2782 /* For the first sample check/update timecode as needed. We do that before
2783 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2784 * initial buffer directly, not with last_buf */
2785 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2786 GstCollectData *cdata = (GstCollectData *) walk->data;
2787 GstQTPad *qpad = (GstQTPad *) cdata;
2789 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2790 GstVideoTimeCodeMeta *tc_meta;
2792 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2793 GstVideoTimeCode *tc = &tc_meta->tc;
2795 qpad->tc_trak = atom_trak_new (qtmux->context);
2796 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2798 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2799 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2801 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2802 qpad->trak->mdia.mdhd.time_info.timescale, tc);
2804 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2805 qtmux->mdat_size, FALSE, 0);
2807 qpad->tc_pos = qtmux->mdat_size;
2808 qpad->first_tc = gst_video_time_code_copy (tc);
2809 qpad->first_pts = GST_BUFFER_PTS (buffer);
2811 qtmux->current_chunk_offset = -1;
2812 qtmux->current_chunk_size = 0;
2813 qtmux->current_chunk_duration = 0;
2814 qtmux->mdat_size += 4;
2817 gst_buffer_unref (buffer);
2821 while ((qpad = find_best_pad_prefill_start (qtmux))) {
2822 GstClockTime timestamp, next_timestamp, duration;
2823 guint nsamples, sample_size;
2824 guint64 chunk_offset;
2825 gint64 scaled_duration;
2826 gint64 pts_offset = 0;
2827 gboolean sync = FALSE;
2828 TrakBufferEntryInfo sample_entry;
2830 sample_size = prefill_get_sample_size (qtmux, qpad);
2832 if (sample_size == -1) {
2837 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2839 timestamp = qpad->total_duration;
2840 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2841 duration = next_timestamp - timestamp;
2843 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2844 qpad->first_ts = timestamp;
2845 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2846 qpad->first_dts = timestamp;
2848 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2849 qtmux->current_pad = qpad;
2850 if (qtmux->current_chunk_offset == -1)
2851 qtmux->current_chunk_offset = qtmux->mdat_size;
2853 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2854 qtmux->current_chunk_size = 0;
2855 qtmux->current_chunk_duration = 0;
2857 if (qpad->sample_size)
2858 nsamples = sample_size / qpad->sample_size;
2861 qpad->last_dts = timestamp;
2862 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2863 atom_trak_get_timescale (qpad->trak),
2864 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2865 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2867 qtmux->current_chunk_size += sample_size;
2868 qtmux->current_chunk_duration += duration;
2869 qpad->total_bytes += sample_size;
2871 chunk_offset = qtmux->current_chunk_offset;
2873 /* I-frame only, no frame reordering */
2877 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2878 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2879 qtmux->longest_chunk = qtmux->current_chunk_duration;
2882 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2883 sample_entry.nsamples = nsamples;
2884 sample_entry.delta = scaled_duration / nsamples;
2885 sample_entry.size = sample_size / nsamples;
2886 sample_entry.chunk_offset = chunk_offset;
2887 sample_entry.pts_offset = pts_offset;
2888 sample_entry.sync = sync;
2889 sample_entry.do_pts = TRUE;
2890 g_array_append_val (qpad->samples, sample_entry);
2891 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2892 sample_size / nsamples, chunk_offset, sync, pts_offset);
2894 qpad->total_duration = next_timestamp;
2895 qtmux->mdat_size += sample_size;
2896 qpad->sample_offset += nsamples;
2902 static GstFlowReturn
2903 gst_qt_mux_start_file (GstQTMux * qtmux)
2905 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2906 GstFlowReturn ret = GST_FLOW_OK;
2910 GstClockTime reserved_max_duration;
2911 guint reserved_bytes_per_sec_per_trak;
2914 GST_DEBUG_OBJECT (qtmux, "starting file");
2916 GST_OBJECT_LOCK (qtmux);
2917 reserved_max_duration = qtmux->reserved_max_duration;
2918 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2919 GST_OBJECT_UNLOCK (qtmux);
2921 /* stream-start (FIXME: create id based on input ids) */
2922 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2923 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2925 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2926 /* qtmux has structure with and without variant, remove all but the first */
2927 while (gst_caps_get_size (caps) > 1)
2928 gst_caps_remove_structure (caps, 1);
2929 gst_pad_set_caps (qtmux->srcpad, caps);
2930 gst_caps_unref (caps);
2932 /* Default is 'normal' mode */
2933 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2935 /* Require a sensible fragment duration when muxing
2936 * using the ISML muxer */
2937 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2938 qtmux->fragment_duration == 0)
2941 if (qtmux->fragment_duration > 0) {
2942 if (qtmux->streamable)
2943 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2945 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2946 } else if (qtmux->fast_start) {
2947 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2948 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2949 if (qtmux->reserved_prefill)
2950 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2952 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2955 switch (qtmux->mux_mode) {
2956 case GST_QT_MUX_MODE_MOOV_AT_END:
2957 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2958 /* We have to be able to seek to rewrite the mdat header, or any
2959 * moov atom we write will not be visible in the file, because an
2960 * MDAT with 0 as the size covers the rest of the file. A file
2961 * with no moov is not playable, so error out now. */
2962 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2963 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2964 ("Downstream is not seekable - will not be able to create a playable file"),
2966 return GST_FLOW_ERROR;
2969 case GST_QT_MUX_MODE_FAST_START:
2970 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2971 break; /* Don't need seekability, ignore */
2972 case GST_QT_MUX_MODE_FRAGMENTED:
2973 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2974 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2975 "streamable=false. Will ignore that and create streamable output "
2977 qtmux->streamable = TRUE;
2978 g_object_notify (G_OBJECT (qtmux), "streamable");
2981 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2982 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2983 GST_WARNING_OBJECT (qtmux,
2984 "downstream is not seekable, will not be able "
2985 "to trim samples table at the end if less than reserved-duration is "
2991 /* let downstream know we think in BYTES and expect to do seeking later on */
2992 gst_segment_init (&segment, GST_FORMAT_BYTES);
2993 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2995 GST_OBJECT_LOCK (qtmux);
2997 if (qtmux->timescale == 0) {
2998 guint32 suggested_timescale = 0;
3001 /* Calculate a reasonable timescale for the moov:
3002 * If there is video, it is the biggest video track timescale or an even
3003 * multiple of it if it's smaller than 1800.
3004 * Otherwise it is 1800 */
3005 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3006 GstCollectData *cdata = (GstCollectData *) walk->data;
3007 GstQTPad *qpad = (GstQTPad *) cdata;
3013 if (!qpad->trak->mdia.minf.vmhd)
3016 suggested_timescale =
3017 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3020 if (suggested_timescale == 0)
3021 suggested_timescale = 1800;
3023 while (suggested_timescale < 1800)
3024 suggested_timescale *= 2;
3026 qtmux->timescale = suggested_timescale;
3029 /* initialize our moov recovery file */
3030 if (qtmux->moov_recov_file_path) {
3031 gst_qt_mux_prepare_moov_recovery (qtmux);
3034 /* Make sure the first time we update the moov, we'll
3035 * include any tagsetter tags */
3036 qtmux->tags_changed = TRUE;
3038 GST_OBJECT_UNLOCK (qtmux);
3041 * send mdat header if already needed, and mark position for later update.
3042 * We don't send ftyp now if we are on fast start mode, because we can
3043 * better fine tune using the information we gather to create the whole moov
3046 switch (qtmux->mux_mode) {
3047 case GST_QT_MUX_MODE_MOOV_AT_END:
3048 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3049 if (ret != GST_FLOW_OK)
3052 /* Store this as the mdat offset for later updating
3053 * when we write the moov */
3054 qtmux->mdat_pos = qtmux->header_size;
3055 /* extended atom in case we go over 4GB while writing and need
3056 * the full 64-bit atom */
3058 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3061 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3062 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3063 if (ret != GST_FLOW_OK)
3066 /* Pad ftyp out to an 8-byte boundary before starting the moov
3067 * ping pong region. It should be well less than 1 disk sector,
3068 * unless there's a bajillion compatible types listed,
3069 * but let's be sure the free atom doesn't cross a sector
3070 * boundary anyway */
3071 if (qtmux->header_size % 8) {
3072 /* Extra 8 bytes for the padding free atom header */
3073 guint padding = (guint) (16 - (qtmux->header_size % 8));
3074 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3076 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3078 if (ret != GST_FLOW_OK)
3082 /* Store this as the moov offset for later updating.
3083 * We record mdat position below */
3084 qtmux->moov_pos = qtmux->header_size;
3086 /* Set up the initial 'ping' state of the ping-pong buffers */
3087 qtmux->reserved_moov_first_active = TRUE;
3089 gst_qt_mux_configure_moov (qtmux);
3090 gst_qt_mux_setup_metadata (qtmux);
3091 /* Empty free atom to begin, starting on an 8-byte boundary */
3092 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3093 if (ret != GST_FLOW_OK)
3095 /* Moov header, not padded yet */
3096 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3097 if (ret != GST_FLOW_OK)
3099 /* The moov we just sent contains the 'base' size of the moov, before
3100 * we put in any time-dependent per-trak data. Use that to make
3101 * a good estimate of how much extra to reserve */
3102 /* Calculate how much space to reserve for our MOOV atom.
3103 * We actually reserve twice that, for ping-pong buffers */
3104 qtmux->base_moov_size = qtmux->last_moov_size;
3105 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3106 qtmux->base_moov_size);
3107 qtmux->reserved_moov_size = qtmux->base_moov_size +
3108 gst_util_uint64_scale (reserved_max_duration,
3109 reserved_bytes_per_sec_per_trak *
3110 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3112 /* Need space for at least 4 atom headers. More really, but
3113 * this as an absolute minimum */
3114 if (qtmux->reserved_moov_size < 4 * 8)
3115 goto reserved_moov_too_small;
3117 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3118 2 * qtmux->reserved_moov_size + 16);
3120 GST_OBJECT_LOCK (qtmux);
3121 qtmux->reserved_duration_remaining =
3122 gst_util_uint64_scale (qtmux->reserved_moov_size -
3123 qtmux->base_moov_size, GST_SECOND,
3124 reserved_bytes_per_sec_per_trak *
3125 atom_moov_get_trak_count (qtmux->moov));
3126 GST_OBJECT_UNLOCK (qtmux);
3128 /* Now that we know how much reserved space is targetted,
3129 * output a free atom to fill the extra reserved */
3130 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3131 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3132 if (ret != GST_FLOW_OK)
3135 /* Then a free atom containing 'pong' buffer, with an
3136 * extra 8 bytes to account for the free atom header itself */
3137 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3138 qtmux->reserved_moov_size + 8, FALSE);
3139 if (ret != GST_FLOW_OK)
3142 /* extra atoms go after the free/moov(s), before the mdat */
3144 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3145 if (ret != GST_FLOW_OK)
3148 qtmux->mdat_pos = qtmux->header_size;
3149 /* extended atom in case we go over 4GB while writing and need
3150 * the full 64-bit atom */
3152 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3155 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3156 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3157 if (ret != GST_FLOW_OK)
3160 /* Store this as the moov offset for later updating.
3161 * We record mdat position below */
3162 qtmux->moov_pos = qtmux->header_size;
3164 if (!gst_qt_mux_prefill_samples (qtmux)) {
3165 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3166 ("Unsupported codecs or configuration for prefill mode"), (NULL));
3168 return GST_FLOW_ERROR;
3171 gst_qt_mux_update_global_statistics (qtmux);
3172 gst_qt_mux_configure_moov (qtmux);
3173 gst_qt_mux_update_edit_lists (qtmux);
3174 gst_qt_mux_setup_metadata (qtmux);
3176 /* Moov header with pre-filled samples */
3177 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3178 if (ret != GST_FLOW_OK)
3181 /* last_moov_size now contains the full size of the moov, moov_pos the
3182 * position. This allows us to rewrite it in the very end as needed */
3183 qtmux->reserved_moov_size =
3184 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3186 /* Send an additional free atom at the end so we definitely have space
3187 * to rewrite the moov header at the end and remove the samples that
3188 * were not actually written */
3190 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3191 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3192 if (ret != GST_FLOW_OK)
3195 /* extra atoms go after the free/moov(s), before the mdat */
3197 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3198 if (ret != GST_FLOW_OK)
3201 qtmux->mdat_pos = qtmux->header_size;
3203 /* And now send the mdat header */
3205 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3206 qtmux->mdat_size, TRUE, FALSE);
3208 /* chunks position is set relative to the first byte of the
3209 * MDAT atom payload. Set the overall offset into the file */
3210 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3215 gst_segment_init (&segment, GST_FORMAT_BYTES);
3216 segment.start = qtmux->moov_pos;
3217 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3219 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3220 if (ret != GST_FLOW_OK)
3223 segment.start = qtmux->header_size;
3224 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3227 qtmux->current_chunk_size = 0;
3228 qtmux->current_chunk_duration = 0;
3229 qtmux->current_chunk_offset = -1;
3230 qtmux->mdat_size = 0;
3231 qtmux->current_pad = NULL;
3232 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3234 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3235 GstCollectData *cdata = (GstCollectData *) walk->data;
3236 GstQTPad *qtpad = (GstQTPad *) cdata;
3238 qtpad->total_bytes = 0;
3239 qtpad->total_duration = 0;
3240 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3241 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3242 qtpad->sample_offset = 0;
3246 case GST_QT_MUX_MODE_FAST_START:
3247 GST_OBJECT_LOCK (qtmux);
3248 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3249 if (!qtmux->fast_start_file)
3251 GST_OBJECT_UNLOCK (qtmux);
3252 /* send a dummy buffer for preroll */
3253 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3255 case GST_QT_MUX_MODE_FRAGMENTED:
3256 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3257 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3258 if (ret != GST_FLOW_OK)
3260 /* store the moov pos so we can update the duration later
3261 * in non-streamable mode */
3262 qtmux->moov_pos = qtmux->header_size;
3264 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3265 qtmux->fragment_duration);
3266 /* also used as snapshot marker to indicate fragmented file */
3267 qtmux->fragment_sequence = 1;
3268 /* prepare moov and/or tags */
3269 gst_qt_mux_configure_moov (qtmux);
3270 gst_qt_mux_setup_metadata (qtmux);
3271 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3272 if (ret != GST_FLOW_OK)
3276 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3277 if (ret != GST_FLOW_OK)
3279 /* prepare index if not streamable */
3280 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3281 qtmux->mfra = atom_mfra_new (qtmux->context);
3289 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3290 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3291 return GST_FLOW_ERROR;
3293 reserved_moov_too_small:
3295 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3296 ("Not enough reserved space for creating headers"), (NULL));
3297 return GST_FLOW_ERROR;
3301 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3302 (("Could not open temporary file \"%s\""),
3303 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3304 GST_OBJECT_UNLOCK (qtmux);
3305 return GST_FLOW_ERROR;
3309 static GstFlowReturn
3310 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3312 GstFlowReturn ret = GST_FLOW_OK;
3315 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3316 GstCollectData *cdata = (GstCollectData *) walk->data;
3317 GstQTPad *qtpad = (GstQTPad *) cdata;
3319 /* avoid add_buffer complaining if not negotiated
3320 * in which case no buffers either, so skipping */
3321 if (!qtpad->fourcc) {
3322 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3323 GST_PAD_NAME (qtpad->collect.pad));
3327 /* send last buffer; also flushes possibly queued buffers/ts */
3328 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3329 GST_PAD_NAME (qtpad->collect.pad));
3330 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3331 if (ret != GST_FLOW_OK) {
3332 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3333 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3334 gst_flow_get_name (ret));
3342 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3346 /* for setting some subtitles fields */
3347 guint max_width = 0;
3348 guint max_height = 0;
3350 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3352 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3353 GstCollectData *cdata = (GstCollectData *) walk->data;
3354 GstQTPad *qtpad = (GstQTPad *) cdata;
3356 if (!qtpad->fourcc) {
3357 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3358 GST_PAD_NAME (qtpad->collect.pad));
3362 /* having flushed above, can check for buffers now */
3363 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3364 GstClockTime first_pts_in = qtpad->first_ts;
3365 /* it should be, since we got first_ts by adding adjustment
3366 * to a positive incoming PTS */
3367 if (qtpad->dts_adjustment <= first_pts_in)
3368 first_pts_in -= qtpad->dts_adjustment;
3369 /* determine max stream duration */
3370 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3371 || qtpad->last_dts > qtmux->last_dts) {
3372 qtmux->last_dts = qtpad->last_dts;
3374 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3375 || first_pts_in < qtmux->first_ts) {
3376 /* we need the original incoming PTS here, as this first_ts
3377 * is used in update_edit_lists to construct the edit list that arrange
3378 * for sync'ed streams. The first_ts is most likely obtained from
3379 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3380 * so it makes no difference, though it matters in other cases */
3381 qtmux->first_ts = first_pts_in;
3385 /* subtitles need to know the video width/height,
3386 * it is stored shifted 16 bits to the left according to the
3388 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3389 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3391 /* update average bitrate of streams if needed */
3393 guint32 avgbitrate = 0;
3394 guint32 maxbitrate = qtpad->max_bitrate;
3396 if (qtpad->avg_bitrate)
3397 avgbitrate = qtpad->avg_bitrate;
3398 else if (qtpad->total_duration > 0)
3399 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3400 8 * GST_SECOND, qtpad->total_duration);
3402 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3406 /* need to update values on subtitle traks now that we know the
3407 * max width and height */
3408 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3409 GstCollectData *cdata = (GstCollectData *) walk->data;
3410 GstQTPad *qtpad = (GstQTPad *) cdata;
3412 if (!qtpad->fourcc) {
3413 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3414 GST_PAD_NAME (qtpad->collect.pad));
3418 if (qtpad->fourcc == FOURCC_tx3g) {
3419 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3424 /* Called after gst_qt_mux_update_global_statistics() updates the
3425 * first_ts tracking, to create/set edit lists for delayed streams */
3427 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3431 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3432 GST_TIME_ARGS (qtmux->first_ts));
3433 /* add/update EDTSs for late streams. configure_moov will have
3434 * set the trak durations above by summing the sample tables,
3435 * here we extend that if needing to insert an empty segment */
3436 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3437 GstCollectData *cdata = (GstCollectData *) walk->data;
3438 GstQTPad *qtpad = (GstQTPad *) cdata;
3440 atom_trak_edts_clear (qtpad->trak);
3442 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3443 guint32 lateness = 0;
3444 guint32 duration = qtpad->trak->tkhd.duration;
3447 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3452 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3453 lateness = gst_util_uint64_scale_round (diff,
3454 qtmux->timescale, GST_SECOND);
3457 GST_DEBUG_OBJECT (qtmux,
3458 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3459 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3461 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3462 (guint32) (1 * 65536.0));
3466 /* Always write an edit list for the whole track. In general this is not
3467 * necessary except for the case of having a gap or DTS adjustment but
3468 * it allows to give the whole track's duration in the usually more
3469 * accurate media timescale
3472 GstClockTime ctts = 0;
3473 guint32 media_start;
3475 if (qtpad->first_ts > qtpad->first_dts)
3476 ctts = qtpad->first_ts - qtpad->first_dts;
3478 media_start = gst_util_uint64_scale_round (ctts,
3479 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3481 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3482 * is empty because there's no gap added above, this call
3483 * will not replace index 1, it will create the entry at index 0.
3484 * Luckily, that's exactly what we want here */
3485 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3486 (guint32) (1 * 65536.0));
3489 /* need to add the empty time to the trak duration */
3490 duration += lateness;
3491 qtpad->trak->tkhd.duration = duration;
3492 if (qtpad->tc_trak) {
3493 qtpad->tc_trak->tkhd.duration = duration;
3494 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3497 /* And possibly grow the moov duration */
3498 if (duration > qtmux->moov->mvhd.time_info.duration) {
3499 qtmux->moov->mvhd.time_info.duration = duration;
3500 qtmux->moov->mvex.mehd.fragment_duration = duration;
3506 static GstFlowReturn
3507 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3512 guint64 offset = qtpad->tc_pos;
3513 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3515 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3518 g_assert (qtpad->tc_pos != -1);
3520 gst_segment_init (&segment, GST_FORMAT_BYTES);
3521 segment.start = offset;
3522 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3524 buf = gst_buffer_new_and_alloc (4);
3525 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3527 GST_WRITE_UINT32_BE (map.data,
3528 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3529 gst_buffer_unmap (buf, &map);
3531 /* Reset this value, so the timecode won't be re-rewritten */
3534 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3537 static GstFlowReturn
3538 gst_qt_mux_stop_file (GstQTMux * qtmux)
3540 gboolean ret = GST_FLOW_OK;
3541 guint64 offset = 0, size = 0;
3542 gboolean large_file;
3545 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3547 /* pushing last buffers for each pad */
3548 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3551 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3552 /* Streamable mode; no need to write duration or MFRA */
3553 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3557 gst_qt_mux_update_global_statistics (qtmux);
3558 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3559 GstQTPad *qtpad = (GstQTPad *) walk->data;
3561 if (qtpad->tc_pos != -1) {
3562 /* File is being stopped and timecode hasn't been updated. Update it now
3563 * with whatever we have */
3564 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3565 if (ret != GST_FLOW_OK)
3570 switch (qtmux->mux_mode) {
3571 case GST_QT_MUX_MODE_FRAGMENTED:{
3573 guint8 *data = NULL;
3577 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3578 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3579 goto serialize_error;
3580 buf = _gst_buffer_new_take_data (data, offset);
3581 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3582 if (ret != GST_FLOW_OK)
3585 /* only mvex duration is updated,
3586 * mvhd should be consistent with empty moov
3587 * (but TODO maybe some clients do not handle that well ?) */
3588 qtmux->moov->mvex.mehd.fragment_duration =
3589 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3590 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3591 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3592 /* seek and rewrite the header */
3593 gst_segment_init (&segment, GST_FORMAT_BYTES);
3594 segment.start = qtmux->moov_pos;
3595 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3596 /* no need to seek back */
3597 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3599 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3600 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3601 if (G_UNLIKELY (ret != GST_FLOW_OK))
3603 /* Finalise by writing the final size into the mdat. Up until now
3604 * it's been 0, which means 'rest of the file'
3605 * No need to seek back after this, we won't write any more */
3606 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3607 qtmux->mdat_size, NULL, TRUE);
3609 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3611 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3613 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3614 GstCollectData *cdata = (GstCollectData *) walk->data;
3615 GstQTPad *qpad = (GstQTPad *) cdata;
3616 const TrakBufferEntryInfo *sample_entry;
3618 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3620 /* Get the block index of the last sample we wrote, not of the next
3621 * sample we would write */
3622 block_idx = prefill_get_block_index (qtmux, qpad);
3623 g_assert (block_idx > 0);
3627 &g_array_index (qpad->samples, TrakBufferEntryInfo, block_idx);
3632 guint64 nsamples = 0;
3635 n = atom_array_get_len (&stbl->stts.entries);
3636 for (i = 0; i < n; i++) {
3637 entry = &atom_array_index (&stbl->stts.entries, i);
3638 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3639 entry->sample_count = qpad->sample_offset - nsamples;
3640 stbl->stts.entries.len = i + 1;
3643 nsamples += entry->sample_count;
3650 g_assert (stbl->stsz.entries.len == 0);
3651 stbl->stsz.table_size = qpad->sample_offset;
3657 guint64 nsamples = 0;
3658 gint chunk_index = 0;
3660 n = stbl->stco64.entries.len;
3661 for (i = 0; i < n; i++) {
3662 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3664 if (*entry == sample_entry->chunk_offset) {
3665 stbl->stco64.entries.len = i + 1;
3666 chunk_index = i + 1;
3671 g_assert (chunk_index > 0);
3673 n = stbl->stsc.entries.len;
3674 for (i = 0; i < n; i++) {
3675 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3677 if (entry->first_chunk >= chunk_index)
3682 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3684 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3685 i - 1).samples_per_chunk;
3691 STSCEntry *prev_entry =
3692 &atom_array_index (&stbl->stsc.entries, i - 1);
3695 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3696 if (qpad->sample_offset - nsamples > 0) {
3697 stbl->stsc.entries.len = i;
3698 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3699 qpad->sample_offset - nsamples);
3701 stbl->stsc.entries.len = i;
3702 stbl->stco64.entries.len--;
3705 /* Everything in a single chunk */
3706 stbl->stsc.entries.len = 0;
3707 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3708 qpad->sample_offset);
3715 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3716 AtomTREX *trex = walk2->data;
3718 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3719 trex->track_ID = next_track_id;
3724 qpad->trak->tkhd.track_ID = next_track_id++;
3727 qtmux->moov->mvhd.next_track_id = next_track_id;
3729 gst_qt_mux_update_global_statistics (qtmux);
3730 gst_qt_mux_configure_moov (qtmux);
3732 gst_qt_mux_update_edit_lists (qtmux);
3734 /* Check if any gap edit lists were added. We don't have any space
3735 * reserved for this in the moov and the pre-finalized moov would have
3736 * broken A/V synchronization. Error out here now
3738 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3739 GstCollectData *cdata = (GstCollectData *) walk->data;
3740 GstQTPad *qpad = (GstQTPad *) cdata;
3742 if (qpad->trak->edts
3743 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3744 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3745 ("Can't support gaps in prefill mode"));
3747 return GST_FLOW_ERROR;
3751 gst_qt_mux_setup_metadata (qtmux);
3752 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3757 gst_segment_init (&segment, GST_FORMAT_BYTES);
3758 segment.start = qtmux->moov_pos;
3759 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3762 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3764 if (ret != GST_FLOW_OK)
3767 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3769 gst_qt_mux_send_free_atom (qtmux, NULL,
3770 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3773 if (ret != GST_FLOW_OK)
3777 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3778 qtmux->mdat_size, NULL, FALSE);
3785 /* Moov-at-end or fast-start mode from here down */
3786 gst_qt_mux_configure_moov (qtmux);
3788 gst_qt_mux_update_edit_lists (qtmux);
3790 /* tags into file metadata */
3791 gst_qt_mux_setup_metadata (qtmux);
3793 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3795 switch (qtmux->mux_mode) {
3796 case GST_QT_MUX_MODE_FAST_START:{
3797 /* if faststart, update the offset of the atoms in the movie with the offset
3798 * that the movie headers before mdat will cause.
3799 * Also, send the ftyp */
3802 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3803 if (ret != GST_FLOW_OK) {
3806 /* copy into NULL to obtain size */
3807 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3808 goto serialize_error;
3809 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3811 offset += qtmux->header_size + (large_file ? 16 : 8);
3813 /* sum up with the extra atoms size */
3814 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3815 if (ret != GST_FLOW_OK)
3820 offset = qtmux->header_size;
3824 /* Now that we know the size of moov + extra atoms, we can adjust
3825 * the chunk offsets stored into the moov */
3826 atom_moov_chunks_set_offset (qtmux->moov, offset);
3828 /* write out moov and extra atoms */
3829 /* note: as of this point, we no longer care about tracking written data size,
3830 * since there is no more use for it anyway */
3831 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3832 if (ret != GST_FLOW_OK)
3836 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3837 if (ret != GST_FLOW_OK)
3840 switch (qtmux->mux_mode) {
3841 case GST_QT_MUX_MODE_MOOV_AT_END:
3843 /* mdat needs update iff not using faststart */
3844 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3845 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3846 qtmux->mdat_size, NULL, FALSE);
3847 /* note; no seeking back to the end of file is done,
3848 * since we no longer write anything anyway */
3851 case GST_QT_MUX_MODE_FAST_START:
3853 /* send mdat atom and move buffered data into it */
3854 /* mdat_size = accumulated (buffered data) */
3855 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3857 if (ret != GST_FLOW_OK)
3859 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3860 if (ret != GST_FLOW_OK)
3865 g_assert_not_reached ();
3873 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3874 ("Failed to serialize moov"));
3875 return GST_FLOW_ERROR;
3879 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3880 return GST_FLOW_ERROR;
3884 static GstFlowReturn
3885 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3886 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3887 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3889 GstFlowReturn ret = GST_FLOW_OK;
3891 /* setup if needed */
3892 if (G_UNLIKELY (!pad->traf || force))
3896 /* flush pad fragment if threshold reached,
3897 * or at new keyframe if we should be minding those in the first place */
3898 if (G_UNLIKELY (force || (sync && pad->sync) ||
3899 pad->fragment_duration < (gint64) delta)) {
3901 guint64 size = 0, offset = 0;
3902 guint8 *data = NULL;
3904 guint i, total_size;
3906 /* now we know where moof ends up, update offset in tfra */
3908 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3910 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3911 /* takes ownership */
3912 atom_moof_add_traf (moof, pad->traf);
3914 atom_moof_copy_data (moof, &data, &size, &offset);
3915 buffer = _gst_buffer_new_take_data (data, offset);
3916 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3917 gst_buffer_get_size (buffer));
3918 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3920 /* and actual data */
3922 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3924 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3927 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3928 atom_array_get_len (&pad->fragment_buffers), total_size);
3929 if (ret == GST_FLOW_OK)
3930 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3932 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3933 if (G_LIKELY (ret == GST_FLOW_OK))
3934 ret = gst_qt_mux_send_buffer (qtmux,
3935 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3938 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3941 atom_array_clear (&pad->fragment_buffers);
3942 atom_moof_free (moof);
3943 qtmux->fragment_sequence++;
3948 if (G_UNLIKELY (!pad->traf)) {
3949 GST_LOG_OBJECT (qtmux, "setting up new fragment");
3950 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3951 atom_array_init (&pad->fragment_buffers, 512);
3952 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3953 atom_trak_get_timescale (pad->trak), 1000);
3955 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3956 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3957 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3959 atom_traf_set_base_decode_time (pad->traf, dts);
3962 /* add buffer and metadata */
3963 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3965 atom_array_append (&pad->fragment_buffers, buf, 256);
3966 pad->fragment_duration -= delta;
3969 guint32 sn = atom_traf_get_sample_num (pad->traf);
3971 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3972 atom_tfra_add_entry (pad->tfra, dts, sn);
3975 if (G_UNLIKELY (force))
3981 /* Here's the clever bit of robust recording: Updating the moov
3982 * header is done using a ping-pong scheme inside 2 blocks of size
3983 * 'reserved_moov_size' at the start of the file, in such a way that the
3984 * file on-disk is always valid if interrupted.
3985 * Inside the reserved space, we have 2 pairs of free + moov atoms
3986 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3987 * at offset "reserved_moov_size".
3989 * 1. Free-A has 0 size payload, moov-A immediately after is
3990 * active/current, and is padded with an internal Free atom to
3991 * end at reserved_space/2. Free-B is at reserved_space/2, sized
3992 * to cover the remaining free space (including moov-B).
3993 * 2. We write moov-B (which is invisible inside free-B), and pad it to
3994 * end at the end of free space. Then, we update free-A to size
3995 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
3996 * free-B header, and makes moov-B active.
3997 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
3998 * Change the size of free-A to make moov-A active again.
3999 * 4. Rinse and repeat.
4002 static GstFlowReturn
4003 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4007 guint64 freeA_offset;
4008 guint32 new_freeA_size;
4009 guint64 new_moov_offset;
4011 /* Update moov info, then seek and rewrite the MOOV atom */
4012 gst_qt_mux_update_global_statistics (qtmux);
4013 gst_qt_mux_configure_moov (qtmux);
4015 gst_qt_mux_update_edit_lists (qtmux);
4017 /* tags into file metadata */
4018 gst_qt_mux_setup_metadata (qtmux);
4020 /* chunks position is set relative to the first byte of the
4021 * MDAT atom payload. Set the overall offset into the file */
4022 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4024 /* Calculate which moov to rewrite. qtmux->moov_pos points to
4025 * the start of the free-A header */
4026 freeA_offset = qtmux->moov_pos;
4027 if (qtmux->reserved_moov_first_active) {
4028 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4029 /* After this, freeA will include itself, moovA, plus the freeB
4031 new_freeA_size = qtmux->reserved_moov_size + 16;
4033 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4036 /* the moov we update is after free-A, calculate its offset */
4037 new_moov_offset = freeA_offset + new_freeA_size;
4039 /* Swap ping-pong cadence marker */
4040 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4042 /* seek and rewrite the MOOV atom */
4043 gst_segment_init (&segment, GST_FORMAT_BYTES);
4044 segment.start = new_moov_offset;
4045 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4048 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4050 if (ret != GST_FLOW_OK)
4053 /* Update the estimated recording space remaining, based on amount used so
4054 * far and duration muxed so far */
4055 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4056 GstClockTime remain;
4057 GstClockTime time_muxed = qtmux->last_dts;
4060 gst_util_uint64_scale (qtmux->reserved_moov_size -
4061 qtmux->last_moov_size, time_muxed,
4062 qtmux->last_moov_size - qtmux->base_moov_size);
4063 /* Always under-estimate slightly, so users
4064 * have time to stop muxing before we run out */
4065 if (remain < GST_SECOND / 2)
4068 remain -= GST_SECOND / 2;
4070 GST_INFO_OBJECT (qtmux,
4071 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4072 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4073 qtmux->reserved_moov_size, qtmux->last_moov_size,
4074 GST_TIME_ARGS (qtmux->last_dts),
4075 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4077 GST_OBJECT_LOCK (qtmux);
4078 qtmux->reserved_duration_remaining = remain;
4079 qtmux->muxed_since_last_update = 0;
4080 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4081 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4082 GST_OBJECT_UNLOCK (qtmux);
4086 /* Now update the moov-A size. Don't pass offset, since we don't need
4087 * send_free_atom() to seek for us - all our callers seek back to
4088 * where they need after this, or they don't need it */
4089 gst_segment_init (&segment, GST_FORMAT_BYTES);
4090 segment.start = freeA_offset;
4091 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4093 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4098 static GstFlowReturn
4099 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4102 GstFlowReturn flow_ret;
4104 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4106 GST_OBJECT_LOCK (qtmux);
4108 /* Update the offset of how much we've muxed, so the
4109 * report of remaining space keeps counting down */
4110 if (position > qtmux->last_moov_update &&
4111 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4112 GST_LOG_OBJECT (qtmux,
4113 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4114 qtmux->muxed_since_last_update);
4115 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4118 /* Next, check if we're supposed to send periodic moov updates downstream */
4119 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4120 GST_OBJECT_UNLOCK (qtmux);
4124 /* Update if position is > the threshold or there's been no update yet */
4125 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4126 (position <= qtmux->last_moov_update ||
4127 (position - qtmux->last_moov_update) <
4128 qtmux->reserved_moov_update_period)) {
4129 GST_OBJECT_UNLOCK (qtmux);
4130 return GST_FLOW_OK; /* No update needed yet */
4133 qtmux->last_moov_update = position;
4134 GST_OBJECT_UNLOCK (qtmux);
4136 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4137 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4138 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4140 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4141 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4144 /* Seek back to previous position */
4145 gst_segment_init (&segment, GST_FORMAT_BYTES);
4146 segment.start = mdat_offset;
4147 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4152 static GstFlowReturn
4153 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4154 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4155 gint64 last_dts, gint64 scaled_duration, guint sample_size,
4156 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4158 GstFlowReturn ret = GST_FLOW_OK;
4160 /* note that a new chunk is started each time (not fancy but works) */
4161 if (qtmux->moov_recov_file) {
4162 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4163 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4164 do_pts, pts_offset)) {
4165 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4166 "recovery file, disabling recovery");
4167 fclose (qtmux->moov_recov_file);
4168 qtmux->moov_recov_file = NULL;
4172 switch (qtmux->mux_mode) {
4173 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4174 const TrakBufferEntryInfo *sample_entry;
4175 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4177 if (block_idx >= pad->samples->len) {
4178 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4179 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4180 block_idx, pad->samples->len));
4181 gst_buffer_unref (buffer);
4182 return GST_FLOW_ERROR;
4185 /* Check if all values are as expected */
4187 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4189 /* Allow +/- 1 difference for the scaled_duration to allow
4190 * for some rounding errors
4192 if (sample_entry->nsamples != nsamples
4193 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4194 || sample_entry->size != sample_size
4195 || sample_entry->chunk_offset != chunk_offset
4196 || sample_entry->pts_offset != pts_offset
4197 || sample_entry->sync != sync) {
4198 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4199 ("Unexpected values in sample %" G_GUINT64_FORMAT,
4200 pad->sample_offset + 1));
4201 gst_buffer_unref (buffer);
4202 return GST_FLOW_ERROR;
4205 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4208 case GST_QT_MUX_MODE_MOOV_AT_END:
4209 case GST_QT_MUX_MODE_FAST_START:
4210 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4211 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4212 sample_size, chunk_offset, sync, pts_offset);
4213 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4214 /* Check if it's time to re-write the headers in robust-recording mode */
4215 if (ret == GST_FLOW_OK
4216 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4217 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4219 case GST_QT_MUX_MODE_FRAGMENTED:
4220 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4221 /* ensure that always sync samples are marked as such */
4222 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4223 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4224 sample_size, !pad->sync || sync, pts_offset);
4232 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4233 guint buffer_size, GstClockTime duration)
4235 /* not that much happens here,
4236 * but updating any of this very likely needs to happen all in sync,
4237 * unless there is a very good reason not to */
4239 /* for computing the avg bitrate */
4240 pad->total_bytes += buffer_size;
4241 pad->total_duration += duration;
4242 /* for keeping track of where we are in chunk;
4243 * ensures that data really is located as recorded in atoms */
4244 qtmux->current_chunk_size += buffer_size;
4245 qtmux->current_chunk_duration += duration;
4248 static GstFlowReturn
4249 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4250 GstBuffer * buf, GstFlowReturn ret)
4252 GstVideoTimeCodeMeta *tc_meta;
4253 GstVideoTimeCode *tc;
4256 guint32 frames_since_daily_jam;
4257 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4259 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4262 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4265 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4271 /* This means we never got a timecode before */
4272 if (pad->first_tc == NULL) {
4273 #ifndef GST_DISABLE_GST_DEBUG
4274 gchar *tc_str = gst_video_time_code_to_string (tc);
4275 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4278 g_assert (pad->tc_trak == NULL);
4279 pad->first_tc = gst_video_time_code_copy (tc);
4280 /* If frames are out of order, the frame we're currently getting might
4281 * not be the first one. Just write a 0 timecode for now and wait
4282 * until we receive a timecode that's lower than the current one */
4283 if (pad->is_out_of_order) {
4284 pad->first_pts = GST_BUFFER_PTS (buf);
4285 frames_since_daily_jam = 0;
4286 /* Position to rewrite */
4287 pad->tc_pos = qtmux->mdat_size;
4289 frames_since_daily_jam =
4290 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4291 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4293 /* Write the timecode trak now */
4294 pad->tc_trak = atom_trak_new (qtmux->context);
4295 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4297 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4298 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4300 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4301 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4303 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4304 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4305 g_assert (szret == 4);
4307 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4308 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4310 /* Need to reset the current chunk (of the previous pad) here because
4311 * some other data was written now above, and the pad has to start a
4313 qtmux->current_chunk_offset = -1;
4314 qtmux->current_chunk_size = 0;
4315 qtmux->current_chunk_duration = 0;
4316 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4317 frames_since_daily_jam =
4318 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4319 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4321 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4322 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4323 g_assert (szret == 4);
4325 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4328 qtmux->current_chunk_offset = -1;
4329 qtmux->current_chunk_size = 0;
4330 qtmux->current_chunk_duration = 0;
4331 } else if (pad->is_out_of_order) {
4332 /* Check for a lower timecode than the one stored */
4333 g_assert (pad->tc_trak != NULL);
4334 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4335 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4336 gst_video_time_code_free (pad->first_tc);
4337 pad->first_tc = gst_video_time_code_copy (tc);
4340 guint64 bk_size = qtmux->mdat_size;
4342 /* If this frame's DTS is after the first PTS received, it means
4343 * we've already received the first frame to be presented. Otherwise
4344 * the decoder would need to go back in time */
4345 gst_qt_mux_update_timecode (qtmux, pad);
4347 /* Reset writing position */
4348 gst_segment_init (&segment, GST_FORMAT_BYTES);
4349 segment.start = bk_size;
4350 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4358 * Here we push the buffer and update the tables in the track atoms
4360 static GstFlowReturn
4361 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4363 GstBuffer *last_buf = NULL;
4364 GstClockTime duration;
4365 guint nsamples, sample_size;
4366 guint64 chunk_offset;
4367 gint64 last_dts, scaled_duration;
4368 gint64 pts_offset = 0;
4369 gboolean sync = FALSE;
4370 GstFlowReturn ret = GST_FLOW_OK;
4374 goto not_negotiated;
4376 /* if this pad has a prepare function, call it */
4377 if (pad->prepare_buf_func != NULL) {
4380 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4381 if (buf && !new_buf)
4386 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4387 if (ret != GST_FLOW_OK) {
4389 gst_buffer_unref (buf);
4393 last_buf = pad->last_buf;
4394 pad->last_buf = buf;
4396 if (last_buf == NULL) {
4397 #ifndef GST_DISABLE_GST_DEBUG
4399 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4400 "received NULL buffer, doing nothing",
4401 GST_PAD_NAME (pad->collect.pad));
4403 GST_LOG_OBJECT (qtmux,
4404 "Pad %s has no previous buffer stored, storing now",
4405 GST_PAD_NAME (pad->collect.pad));
4411 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4414 /* if this is the first buffer, store the timestamp */
4415 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4416 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4417 pad->first_ts = GST_BUFFER_PTS (last_buf);
4418 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4419 pad->first_ts = GST_BUFFER_DTS (last_buf);
4422 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4423 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4424 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4425 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4428 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4429 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4431 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4432 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4433 pad->first_ts = pad->first_dts = 0;
4435 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4436 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4437 GST_TIME_ARGS (pad->first_ts));
4440 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4441 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4442 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4443 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4444 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4445 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4446 pad->last_buf = buf = gst_buffer_make_writable (buf);
4447 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4450 buffer_size = gst_buffer_get_size (last_buf);
4452 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4453 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4454 guint fill_size = required_buffer_size - buffer_size;
4458 if (required_buffer_size < buffer_size) {
4459 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4460 ("Sample size %u bigger than expected maximum %u", buffer_size,
4461 required_buffer_size));
4465 if (fill_size > 0) {
4466 GST_DEBUG_OBJECT (qtmux,
4467 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4468 required_buffer_size);
4469 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4470 gst_memory_map (mem, &map, GST_MAP_WRITE);
4471 memset (map.data, 0, map.size);
4472 gst_memory_unmap (mem, &map);
4473 last_buf = gst_buffer_make_writable (last_buf);
4474 gst_buffer_append_memory (last_buf, mem);
4475 buffer_size = required_buffer_size;
4479 /* duration actually means time delta between samples, so we calculate
4480 * the duration based on the difference in DTS or PTS, falling back
4481 * to DURATION if the other two don't exist, such as with the last
4482 * sample before EOS. Or use 0 if nothing else is available */
4483 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4484 duration = GST_BUFFER_DURATION (last_buf);
4488 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4489 && GST_BUFFER_DTS_IS_VALID (last_buf))
4490 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4491 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4492 && GST_BUFFER_PTS_IS_VALID (last_buf))
4493 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4496 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4497 GST_DEBUG_OBJECT (qtmux,
4498 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4499 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4500 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4501 qtmux->current_chunk_size,
4502 GST_TIME_ARGS (qtmux->current_chunk_duration));
4503 qtmux->current_pad = pad;
4504 if (qtmux->current_chunk_offset == -1)
4505 qtmux->current_chunk_offset = qtmux->mdat_size;
4507 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4508 qtmux->current_chunk_size = 0;
4509 qtmux->current_chunk_duration = 0;
4512 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4513 atom_trak_get_timescale (pad->trak), GST_SECOND);
4515 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4516 if (pad->sample_size && !qtmux->fragment_sequence) {
4517 GstClockTime expected_timestamp;
4519 /* Constant size packets: usually raw audio (with many samples per
4520 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4522 sample_size = pad->sample_size;
4523 if (buffer_size % sample_size != 0)
4524 goto fragmented_sample;
4526 /* note: qt raw audio storage warps it implicitly into a timewise
4527 * perfect stream, discarding buffer times.
4528 * If the difference between the current PTS and the expected one
4529 * becomes too big, we error out: there was a gap and we have no way to
4530 * represent that, causing A/V sync to be off */
4531 expected_timestamp =
4532 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4533 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4534 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4535 expected_timestamp) > qtmux->max_raw_audio_drift)
4536 goto raw_audio_timestamp_drift;
4538 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4539 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4540 atom_trak_get_timescale (pad->trak), GST_SECOND);
4541 duration = GST_BUFFER_DURATION (last_buf);
4543 nsamples = buffer_size / sample_size;
4545 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4546 atom_trak_get_timescale (pad->trak));
4549 /* timescale = samplerate */
4550 scaled_duration = 1;
4552 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4553 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4556 sample_size = buffer_size;
4557 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4558 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4560 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4561 pad->last_dts = GST_BUFFER_DTS (buf);
4563 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4565 if ((gint64) (pad->last_dts) < 0) {
4566 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4567 atom_trak_get_timescale (pad->trak), GST_SECOND);
4569 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4570 atom_trak_get_timescale (pad->trak), GST_SECOND);
4572 scaled_duration = scaled_dts - last_dts;
4573 last_dts = scaled_dts;
4575 /* first convert intended timestamp (in GstClockTime resolution) to
4576 * trak timescale, then derive delta;
4577 * this ensures sums of (scale)delta add up to converted timestamp,
4578 * which only deviates at most 1/scale from timestamp itself */
4579 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4580 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4581 pad->last_dts += duration;
4585 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4587 chunk_offset = qtmux->current_chunk_offset;
4589 GST_LOG_OBJECT (qtmux,
4590 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4591 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4592 GST_LOG_OBJECT (qtmux,
4593 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4594 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4595 nsamples, scaled_duration, sample_size, chunk_offset);
4597 /* might be a sync sample */
4599 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4600 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4601 GST_PAD_NAME (pad->collect.pad));
4605 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4606 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4607 atom_trak_get_timescale (pad->trak), GST_SECOND);
4609 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4610 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4613 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4614 atom_trak_get_timescale (pad->trak), GST_SECOND);
4616 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4617 " timebase_dts: %d pts_offset: %d",
4618 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4619 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4620 (int) (last_dts), (int) (pts_offset));
4622 if (GST_CLOCK_TIME_IS_VALID (duration)
4623 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4624 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4625 GST_DEBUG_OBJECT (qtmux,
4626 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4627 GST_TIME_ARGS (qtmux->current_chunk_duration),
4628 GST_PAD_NAME (pad->collect.pad));
4629 qtmux->longest_chunk = qtmux->current_chunk_duration;
4632 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4633 const TrakBufferEntryInfo *sample_entry;
4634 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4636 if (block_idx >= pad->samples->len) {
4637 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4638 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4639 block_idx, pad->samples->len));
4643 /* Check if all values are as expected */
4645 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4647 if (chunk_offset < sample_entry->chunk_offset) {
4648 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4649 GstBuffer *fill_buf;
4651 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4652 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4654 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4655 if (ret != GST_FLOW_OK)
4657 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4658 qtmux->current_chunk_size = buffer_size;
4659 qtmux->current_chunk_duration = duration;
4660 } else if (chunk_offset != sample_entry->chunk_offset) {
4661 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4662 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4663 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4668 /* now we go and register this buffer/sample all over */
4669 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4670 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4671 chunk_offset, sync, TRUE, pts_offset);
4672 pad->sample_offset += nsamples;
4674 /* if this is sparse and we have a next buffer, check if there is any gap
4675 * between them to insert an empty sample */
4676 if (pad->sparse && buf) {
4677 if (pad->create_empty_buffer) {
4678 GstBuffer *empty_buf;
4679 gint64 empty_duration =
4680 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4681 gint64 empty_duration_scaled;
4684 empty_buf = pad->create_empty_buffer (pad, empty_duration);
4686 pad->last_dts = GST_BUFFER_PTS (buf);
4687 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4688 atom_trak_get_timescale (pad->trak), GST_SECOND)
4689 - (last_dts + scaled_duration);
4690 empty_size = gst_buffer_get_size (empty_buf);
4692 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4696 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4697 last_dts + scaled_duration, empty_duration_scaled,
4698 empty_size, chunk_offset, sync, TRUE, 0);
4699 } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4700 /* This assert is kept here to make sure implementors of new
4701 * sparse input format decide whether there needs to be special
4702 * gap handling or not */
4703 g_assert_not_reached ();
4704 GST_WARNING_OBJECT (qtmux,
4705 "no empty buffer creation function found for pad %s",
4706 GST_PAD_NAME (pad->collect.pad));
4717 gst_buffer_unref (last_buf);
4718 return GST_FLOW_ERROR;
4722 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4723 ("Audio buffer contains fragmented sample."));
4726 raw_audio_timestamp_drift:
4728 /* TODO: Could in theory be implemented with edit lists */
4729 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4730 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4731 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4732 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4733 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4735 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4740 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4745 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4746 ("format wasn't negotiated before buffer flow on pad %s",
4747 GST_PAD_NAME (pad->collect.pad)));
4749 gst_buffer_unref (buf);
4750 return GST_FLOW_NOT_NEGOTIATED;
4755 * DTS running time can be negative. There is no way to represent that in
4756 * MP4 however, thus we need to offset DTS so that it starts from 0.
4759 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4760 GstCollectData * cdata, GstBuffer ** buf)
4765 pts = GST_BUFFER_PTS (*buf);
4766 dts = GST_COLLECT_PADS_DTS (cdata);
4768 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4769 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4770 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4772 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4773 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4774 pad->dts_adjustment = -dts;
4776 pad->dts_adjustment = 0;
4779 if (pad->dts_adjustment > 0) {
4780 *buf = gst_buffer_make_writable (*buf);
4782 dts += pad->dts_adjustment;
4784 if (GST_CLOCK_TIME_IS_VALID (pts))
4785 pts += pad->dts_adjustment;
4787 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4788 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4793 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4797 GST_BUFFER_PTS (*buf) = pts;
4798 GST_BUFFER_DTS (*buf) = dts;
4800 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4801 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4806 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4809 GstQTPad *best_pad = NULL;
4811 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4812 guint64 smallest_offset = G_MAXUINT64;
4813 guint64 chunk_offset = 0;
4815 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4816 GstCollectData *cdata = (GstCollectData *) walk->data;
4817 GstQTPad *qtpad = (GstQTPad *) cdata;
4818 const TrakBufferEntryInfo *sample_entry;
4819 guint64 block_idx, current_block_idx;
4820 guint64 chunk_offset_offset = 0;
4821 GstBuffer *tmp_buf =
4822 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4824 /* Check for EOS pads and just skip them */
4825 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4826 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4829 gst_buffer_unref (tmp_buf);
4831 /* Find the exact offset where the next sample of this track is supposed
4832 * to be written at */
4833 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4835 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4836 while (block_idx > 0) {
4837 const TrakBufferEntryInfo *tmp =
4838 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4840 if (tmp->chunk_offset != sample_entry->chunk_offset)
4842 chunk_offset_offset += tmp->size * tmp->nsamples;
4846 /* Except for the previously selected pad being EOS we always have
4847 * qtmux->current_chunk_offset + qtmux->current_chunk_size
4849 * sample_entry->chunk_offset + chunk_offset_offset
4850 * for the best pad. Instead of checking that, we just return the
4851 * pad that has the smallest offset for the next to-be-written sample.
4853 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4854 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4856 chunk_offset = sample_entry->chunk_offset;
4860 if (chunk_offset != qtmux->current_chunk_offset) {
4861 qtmux->current_pad = NULL;
4867 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4868 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4869 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4870 && (qtmux->interleave_time == 0
4871 || qtmux->current_chunk_duration <= qtmux->interleave_time)
4872 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4873 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4874 GstBuffer *tmp_buf =
4875 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4877 if (tmp_buf || qtmux->current_pad->last_buf) {
4878 best_pad = qtmux->current_pad;
4880 gst_buffer_unref (tmp_buf);
4881 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4882 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4884 } else if (qtmux->collect->data->next) {
4885 /* Only switch pads if we have more than one, otherwise
4886 * we can just put everything into a single chunk and save
4887 * a few bytes of offsets
4889 if (qtmux->current_pad)
4890 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4891 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4892 best_pad = qtmux->current_pad = NULL;
4896 GstClockTime best_time = GST_CLOCK_TIME_NONE;
4898 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4899 GstCollectData *cdata = (GstCollectData *) walk->data;
4900 GstQTPad *qtpad = (GstQTPad *) cdata;
4902 GstClockTime timestamp;
4904 tmp_buf = gst_collect_pads_peek (pads, cdata);
4906 /* This one is newly EOS now, finish it for real */
4907 if (qtpad->last_buf) {
4908 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4913 if (qtpad->last_buf)
4914 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4916 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4919 if (best_pad == NULL ||
4920 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4922 best_time = timestamp;
4926 gst_buffer_unref (tmp_buf);
4930 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4931 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4933 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4940 static GstFlowReturn
4941 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4943 GstFlowReturn ret = GST_FLOW_OK;
4944 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4945 GstQTPad *best_pad = NULL;
4947 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4948 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4951 qtmux->state = GST_QT_MUX_STATE_DATA;
4954 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4955 return GST_FLOW_EOS;
4957 best_pad = find_best_pad (qtmux, pads);
4959 /* clipping already converted to running time */
4960 if (best_pad != NULL) {
4961 GstBuffer *buf = NULL;
4963 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4964 best_pad->raw_audio_adapter == NULL ||
4965 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4966 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4968 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4969 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4972 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
4973 (GstCollectData *) best_pad, &buf);
4975 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
4977 qtmux->state = GST_QT_MUX_STATE_EOS;
4978 ret = gst_qt_mux_stop_file (qtmux);
4979 if (ret == GST_FLOW_OK) {
4980 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
4981 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
4984 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
4985 gst_flow_get_name (ret));
4993 check_field (GQuark field_id, const GValue * value, gpointer user_data)
4995 GstStructure *structure = (GstStructure *) user_data;
4996 const GValue *other = gst_structure_id_get_value (structure, field_id);
4999 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5003 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5006 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5007 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5009 return gst_structure_foreach (sub_s, check_field, sup_s);
5012 /* will unref @qtmux */
5014 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5016 GstCaps *current_caps;
5018 /* does not go well to renegotiate stream mid-way, unless
5019 * the old caps are a subset of the new one (this means upstream
5020 * added more info to the caps, as both should be 'fixed' caps) */
5021 current_caps = gst_pad_get_current_caps (pad);
5022 g_assert (caps != NULL);
5024 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5025 gst_caps_unref (current_caps);
5026 GST_WARNING_OBJECT (qtmux,
5027 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5028 GST_PAD_NAME (pad), caps);
5029 gst_object_unref (qtmux);
5033 GST_DEBUG_OBJECT (qtmux,
5034 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5035 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5036 gst_object_unref (qtmux);
5037 gst_caps_unref (current_caps);
5043 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5045 GstPad *pad = qtpad->collect.pad;
5046 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5047 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5048 GstStructure *structure;
5049 const gchar *mimetype;
5050 gint rate, channels;
5051 const GValue *value = NULL;
5052 const GstBuffer *codec_data = NULL;
5053 GstQTMuxFormat format;
5054 AudioSampleEntry entry = { 0, };
5055 AtomInfo *ext_atom = NULL;
5056 gint constant_size = 0;
5057 const gchar *stream_format;
5061 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5063 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5064 GST_DEBUG_PAD_NAME (pad), caps);
5066 qtpad->prepare_buf_func = NULL;
5068 format = qtmux_klass->format;
5069 structure = gst_caps_get_structure (caps, 0);
5070 mimetype = gst_structure_get_name (structure);
5073 if (!gst_structure_get_int (structure, "channels", &channels) ||
5074 !gst_structure_get_int (structure, "rate", &rate)) {
5079 value = gst_structure_get_value (structure, "codec_data");
5081 codec_data = gst_value_get_buffer (value);
5083 qtpad->is_out_of_order = FALSE;
5085 /* set common properties */
5086 entry.sample_rate = rate;
5087 entry.channels = channels;
5089 entry.sample_size = 16;
5090 /* this is the typical compressed case */
5091 if (format == GST_QT_MUX_FORMAT_QT) {
5093 entry.compression_id = -2;
5096 /* now map onto a fourcc, and some extra properties */
5097 if (strcmp (mimetype, "audio/mpeg") == 0) {
5098 gint mpegversion = 0, mpegaudioversion = 0;
5101 gst_structure_get_int (structure, "mpegversion", &mpegversion);
5102 switch (mpegversion) {
5104 gst_structure_get_int (structure, "layer", &layer);
5105 gst_structure_get_int (structure, "mpegaudioversion",
5109 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5110 if (format == GST_QT_MUX_FORMAT_QT)
5111 entry.fourcc = FOURCC__mp3;
5113 entry.fourcc = FOURCC_mp4a;
5115 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5116 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5117 qtpad->max_bitrate);
5120 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5121 || format == GST_QT_MUX_FORMAT_QT);
5122 entry.samples_per_packet = 384;
5123 } else if (layer == 2) {
5124 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5125 || format == GST_QT_MUX_FORMAT_QT);
5126 entry.samples_per_packet = 1152;
5128 g_warn_if_fail (layer == 3);
5129 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5131 entry.bytes_per_sample = 2;
5135 /* check stream-format */
5136 stream_format = gst_structure_get_string (structure, "stream-format");
5137 if (stream_format) {
5138 if (strcmp (stream_format, "raw") != 0) {
5139 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5140 "please use 'raw'", stream_format);
5144 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5148 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5149 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5154 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5155 /* warn if not Low Complexity profile */
5158 GST_WARNING_OBJECT (qtmux,
5159 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5163 entry.fourcc = FOURCC_mp4a;
5165 if (format == GST_QT_MUX_FORMAT_QT)
5166 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5167 qtpad->avg_bitrate, qtpad->max_bitrate);
5170 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5171 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5172 qtpad->max_bitrate);
5177 } else if (strcmp (mimetype, "audio/AMR") == 0) {
5178 entry.fourcc = FOURCC_samr;
5179 entry.sample_size = 16;
5180 entry.samples_per_packet = 160;
5181 entry.bytes_per_sample = 2;
5182 ext_atom = build_amr_extension ();
5183 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5184 entry.fourcc = FOURCC_sawb;
5185 entry.sample_size = 16;
5186 entry.samples_per_packet = 320;
5187 entry.bytes_per_sample = 2;
5188 ext_atom = build_amr_extension ();
5189 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5192 gst_audio_info_init (&info);
5193 if (!gst_audio_info_from_caps (&info, caps))
5196 /* spec has no place for a distinction in these */
5197 if (info.finfo->width != info.finfo->depth) {
5198 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5202 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5203 if (info.finfo->endianness == G_LITTLE_ENDIAN)
5204 entry.fourcc = FOURCC_sowt;
5205 else if (info.finfo->endianness == G_BIG_ENDIAN)
5206 entry.fourcc = FOURCC_twos;
5208 entry.fourcc = FOURCC_sowt;
5209 /* maximum backward compatibility; only new version for > 16 bit */
5210 if (info.finfo->depth <= 16)
5212 /* not compressed in any case */
5213 entry.compression_id = 0;
5214 /* QT spec says: max at 16 bit even if sample size were actually larger,
5215 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5216 entry.sample_size = info.finfo->depth;
5217 entry.bytes_per_sample = info.finfo->depth / 8;
5218 entry.samples_per_packet = 1;
5219 entry.bytes_per_packet = info.finfo->depth / 8;
5220 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5222 if (info.finfo->width == 8 && info.finfo->depth == 8) {
5223 /* fall back to old 8-bit version */
5224 entry.fourcc = FOURCC_raw_;
5226 entry.compression_id = 0;
5227 entry.sample_size = 8;
5229 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5233 constant_size = (info.finfo->depth / 8) * info.channels;
5234 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5235 entry.fourcc = FOURCC_alaw;
5236 entry.samples_per_packet = 1023;
5237 entry.bytes_per_sample = 2;
5238 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5239 entry.fourcc = FOURCC_ulaw;
5240 entry.samples_per_packet = 1023;
5241 entry.bytes_per_sample = 2;
5242 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5244 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5245 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5248 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5250 entry.fourcc = MS_WAVE_FOURCC (0x11);
5251 /* 4 byte header per channel (including one sample). 2 samples per byte
5252 remaining. Simplifying gives the following (samples per block per
5254 entry.samples_per_packet = 2 * blocksize / channels - 7;
5255 entry.bytes_per_sample = 2;
5257 entry.bytes_per_frame = blocksize;
5258 entry.bytes_per_packet = blocksize / channels;
5259 /* ADPCM has constant size packets */
5261 /* TODO: I don't really understand why this helps, but it does! Constant
5262 * size and compression_id of -2 seem to be incompatible, and other files
5263 * in the wild use this too. */
5264 entry.compression_id = -1;
5266 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5267 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5268 GstBuffer *codec_config;
5272 entry.fourcc = FOURCC_alac;
5273 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5274 /* let's check if codec data already comes with 'alac' atom prefix */
5275 if (!codec_data || (len = map.size) < 28) {
5276 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5277 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5280 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5283 gst_buffer_copy_region ((GstBuffer *) codec_data,
5284 GST_BUFFER_COPY_MEMORY, 8, len);
5286 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5288 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5290 /* does not look good, but perhaps some trailing unneeded stuff */
5291 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5293 if (format == GST_QT_MUX_FORMAT_QT)
5294 ext_atom = build_mov_alac_extension (codec_config);
5296 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5297 /* set some more info */
5298 gst_buffer_map (codec_config, &map, GST_MAP_READ);
5299 entry.bytes_per_sample = 2;
5300 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5301 gst_buffer_unmap (codec_config, &map);
5302 gst_buffer_unref (codec_config);
5303 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5304 entry.fourcc = FOURCC_ac_3;
5306 /* Fixed values according to TS 102 366 but it also mentions that
5307 * they should be ignored */
5309 entry.sample_size = 16;
5311 /* AC-3 needs an extension atom but its data can only be obtained from
5312 * the stream itself. Abuse the prepare_buf_func so we parse a frame
5313 * and get the needed data */
5314 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5315 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5316 /* Based on the specification defined in:
5317 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5318 guint8 channels, mapping_family, stream_count, coupled_count;
5322 guint8 channel_mapping[256];
5323 const GValue *streamheader;
5324 const GValue *first_element;
5327 entry.fourcc = FOURCC_opus;
5328 entry.sample_size = 16;
5330 streamheader = gst_structure_get_value (structure, "streamheader");
5331 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5332 gst_value_array_get_size (streamheader) != 0) {
5333 first_element = gst_value_array_get_value (streamheader, 0);
5334 header = gst_value_get_buffer (first_element);
5335 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5336 &mapping_family, &stream_count, &coupled_count, channel_mapping,
5337 &pre_skip, &output_gain)) {
5338 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5342 GST_WARNING_OBJECT (qtmux,
5343 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5345 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5346 &mapping_family, &stream_count, &coupled_count,
5348 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5355 entry.channels = channels;
5356 ext_atom = build_opus_extension (rate, channels, mapping_family,
5357 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5363 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5364 if (!timescale && qtmux->trak_timescale)
5365 timescale = qtmux->trak_timescale;
5366 else if (!timescale)
5367 timescale = entry.sample_rate;
5369 /* ok, set the pad info accordingly */
5370 qtpad->fourcc = entry.fourcc;
5371 qtpad->sample_size = constant_size;
5373 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5374 qtmux->context, &entry, timescale, ext_atom, constant_size);
5376 gst_object_unref (qtmux);
5382 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5383 GST_PAD_NAME (pad), caps);
5384 gst_object_unref (qtmux);
5390 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5392 GstPad *pad = qtpad->collect.pad;
5393 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5394 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5395 GstStructure *structure;
5396 const gchar *mimetype;
5397 gint width, height, depth = -1;
5398 gint framerate_num, framerate_den;
5400 const GValue *value = NULL;
5401 const GstBuffer *codec_data = NULL;
5402 VisualSampleEntry entry = { 0, };
5403 GstQTMuxFormat format;
5404 AtomInfo *ext_atom = NULL;
5405 GList *ext_atom_list = NULL;
5406 gboolean sync = FALSE;
5407 int par_num, par_den;
5408 const gchar *multiview_mode;
5411 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5413 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5414 GST_DEBUG_PAD_NAME (pad), caps);
5416 qtpad->prepare_buf_func = NULL;
5418 format = qtmux_klass->format;
5419 structure = gst_caps_get_structure (caps, 0);
5420 mimetype = gst_structure_get_name (structure);
5422 /* required parts */
5423 if (!gst_structure_get_int (structure, "width", &width) ||
5424 !gst_structure_get_int (structure, "height", &height))
5429 /* works as a default timebase */
5430 framerate_num = 10000;
5432 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5434 gst_structure_get_int (structure, "depth", &depth);
5435 value = gst_structure_get_value (structure, "codec_data");
5437 codec_data = gst_value_get_buffer (value);
5441 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5444 qtpad->is_out_of_order = FALSE;
5446 /* bring frame numerator into a range that ensures both reasonable resolution
5447 * as well as a fair duration */
5448 qtpad->expected_sample_duration_n = framerate_num;
5449 qtpad->expected_sample_duration_d = framerate_den;
5451 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5452 if (!rate && qtmux->trak_timescale)
5453 rate = qtmux->trak_timescale;
5455 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5457 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5460 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5461 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5462 GstVideoMultiviewMode mode;
5463 GstVideoMultiviewFlags flags = 0;
5465 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5466 gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5468 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5469 qtpad->trak->mdia.minf.stbl.svmi =
5471 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5473 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5474 qtpad->trak->mdia.minf.stbl.svmi =
5476 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5478 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5479 qtpad->trak->mdia.minf.stbl.svmi =
5481 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5484 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5490 /* set common properties */
5491 entry.width = width;
5492 entry.height = height;
5493 entry.par_n = par_num;
5494 entry.par_d = par_den;
5495 /* should be OK according to qt and iso spec, override if really needed */
5496 entry.color_table_id = -1;
5497 entry.frame_count = 1;
5500 /* sync entries by default */
5503 /* now map onto a fourcc, and some extra properties */
5504 if (strcmp (mimetype, "video/x-raw") == 0) {
5505 const gchar *format;
5507 const GstVideoFormatInfo *vinfo;
5509 format = gst_structure_get_string (structure, "format");
5510 fmt = gst_video_format_from_string (format);
5511 vinfo = gst_video_format_get_info (fmt);
5514 case GST_VIDEO_FORMAT_UYVY:
5517 entry.fourcc = FOURCC_2vuy;
5518 entry.depth = depth;
5521 case GST_VIDEO_FORMAT_v210:
5524 entry.fourcc = FOURCC_v210;
5525 entry.depth = depth;
5529 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5530 entry.fourcc = FOURCC_raw_;
5531 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5536 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5538 if (format == GST_QT_MUX_FORMAT_QT)
5539 entry.fourcc = FOURCC_h263;
5541 entry.fourcc = FOURCC_s263;
5542 ext_atom = build_h263_extension ();
5543 if (ext_atom != NULL)
5544 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5545 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5546 strcmp (mimetype, "video/mpeg") == 0) {
5549 if (strcmp (mimetype, "video/x-divx") == 0) {
5550 gst_structure_get_int (structure, "divxversion", &version);
5551 version = version == 5 ? 1 : 0;
5553 gst_structure_get_int (structure, "mpegversion", &version);
5554 version = version == 4 ? 1 : 0;
5557 entry.fourcc = FOURCC_mp4v;
5559 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5560 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5561 qtpad->max_bitrate);
5562 if (ext_atom != NULL)
5563 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5565 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5566 "output might not play in Apple QuickTime (try global-headers?)");
5568 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5570 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5574 entry.fourcc = FOURCC_avc1;
5576 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5577 if (ext_atom != NULL)
5578 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5579 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5580 if (ext_atom != NULL)
5581 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5582 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5583 const gchar *format;
5586 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5590 format = gst_structure_get_string (structure, "stream-format");
5591 if (strcmp (format, "hvc1") == 0)
5592 entry.fourcc = FOURCC_hvc1;
5593 else if (strcmp (format, "hev1") == 0)
5594 entry.fourcc = FOURCC_hev1;
5596 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5597 if (ext_atom != NULL)
5598 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5600 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5601 if (ext_atom != NULL)
5602 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5604 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5606 const GstBuffer *seqh = NULL;
5607 const GValue *seqh_value;
5610 gst_structure_get_int (structure, "svqversion", &version);
5612 entry.fourcc = FOURCC_SVQ3;
5616 seqh_value = gst_structure_get_value (structure, "seqh");
5618 seqh = gst_value_get_buffer (seqh_value);
5619 ext_atom = build_SMI_atom (seqh);
5621 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5624 /* we need to add the gamma anyway because quicktime might crash
5625 * when it doesn't find it */
5626 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5627 /* it seems that using 0 here makes it ignored */
5630 ext_atom = build_gama_atom (gamma);
5632 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5634 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5635 "a bug at http://bugzilla.gnome.org", version);
5637 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5639 gboolean pal = TRUE;
5642 if (framerate_num != 25 || framerate_den != 1)
5644 gst_structure_get_int (structure, "dvversion", &version);
5645 /* fall back to typical one */
5651 entry.fourcc = FOURCC_dvcp;
5653 entry.fourcc = FOURCC_dvc_;
5657 entry.fourcc = FOURCC_dv5p;
5659 entry.fourcc = FOURCC_dv5n;
5662 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5665 } else if (strcmp (mimetype, "image/jpeg") == 0) {
5666 entry.fourcc = FOURCC_jpeg;
5668 } else if (strcmp (mimetype, "image/png") == 0) {
5669 entry.fourcc = FOURCC_png;
5671 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5672 strcmp (mimetype, "image/x-jpc") == 0) {
5673 const gchar *colorspace;
5674 const GValue *cmap_array;
5675 const GValue *cdef_array;
5678 if (strcmp (mimetype, "image/x-jpc") == 0) {
5679 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5682 gst_structure_get_int (structure, "num-components", &ncomp);
5683 cmap_array = gst_structure_get_value (structure, "component-map");
5684 cdef_array = gst_structure_get_value (structure, "channel-definitions");
5687 entry.fourcc = FOURCC_mjp2;
5690 colorspace = gst_structure_get_string (structure, "colorspace");
5693 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5694 cdef_array)) != NULL) {
5695 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5697 ext_atom = build_jp2x_extension (codec_data);
5699 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5701 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5704 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5705 entry.fourcc = FOURCC_vp08;
5706 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5707 entry.fourcc = FOURCC_vp09;
5708 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5709 entry.fourcc = FOURCC_drac;
5710 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5713 gst_structure_get_uint (structure, "format", &fourcc);
5714 entry.fourcc = fourcc;
5715 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5718 gst_structure_get_uint (structure, "format", &fourcc);
5719 entry.fourcc = fourcc;
5720 } else if (strcmp (mimetype, "video/x-prores") == 0) {
5721 const gchar *variant;
5723 variant = gst_structure_get_string (structure, "variant");
5724 if (!variant || !g_strcmp0 (variant, "standard"))
5725 entry.fourcc = FOURCC_apcn;
5726 else if (!g_strcmp0 (variant, "lt"))
5727 entry.fourcc = FOURCC_apcs;
5728 else if (!g_strcmp0 (variant, "hq"))
5729 entry.fourcc = FOURCC_apch;
5730 else if (!g_strcmp0 (variant, "proxy"))
5731 entry.fourcc = FOURCC_apco;
5732 else if (!g_strcmp0 (variant, "4444"))
5733 entry.fourcc = FOURCC_ap4h;
5734 else if (!g_strcmp0 (variant, "4444xq"))
5735 entry.fourcc = FOURCC_ap4x;
5739 if (!qtmux->interleave_time_set)
5740 qtmux->interleave_time = 500 * GST_MSECOND;
5741 if (!qtmux->interleave_bytes_set)
5742 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5743 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5744 entry.fourcc = FOURCC_cfhd;
5751 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5752 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5754 GstVideoColorimetry colorimetry;
5756 s = gst_structure_get_string (structure, "colorimetry");
5757 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5759 build_colr_extension (&colorimetry,
5760 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5762 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5766 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5767 || strcmp (mimetype, "image/x-j2c") == 0
5768 || strcmp (mimetype, "image/x-jpc") == 0) {
5770 GstVideoInterlaceMode interlace_mode;
5771 GstVideoFieldOrder field_order;
5774 if (strcmp (mimetype, "image/x-j2c") == 0 ||
5775 strcmp (mimetype, "image/x-jpc") == 0) {
5778 gst_structure_get_int (structure, "fields", &fields);
5781 s = gst_structure_get_string (structure, "interlace-mode");
5783 interlace_mode = gst_video_interlace_mode_from_string (s);
5787 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5788 GST_VIDEO_INTERLACE_MODE_MIXED;
5790 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5791 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5792 s = gst_structure_get_string (structure, "field-order");
5794 field_order = gst_video_field_order_from_string (s);
5797 ext_atom = build_fiel_extension (interlace_mode, field_order);
5799 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5803 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5804 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5805 /* The 'clap' extension is also defined for MP4 but inventing values in
5806 * general seems a bit tricky for this one. We only write it for
5807 * SD resolution in MOV, where it is a requirement.
5808 * The same goes for the 'tapt' extension, just that it is not defined for
5809 * MP4 and only for MOV
5811 gint dar_num, dar_den;
5812 gint clef_width, clef_height, prof_width;
5813 gint clap_width_n, clap_width_d, clap_height;
5817 /* First, guess display aspect ratio based on pixel aspect ratio,
5818 * width and height. We assume that display aspect ratio is either
5821 approx_dar = (gdouble) (width * par_num) / (height * par_den);
5822 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5825 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5829 dar_num = width * par_num;
5830 dar_den = height * par_den;
5831 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5836 /* Then, calculate clean-aperture values (clap and clef)
5837 * using the guessed DAR.
5839 clef_height = clap_height = (height == 486 ? 480 : height);
5840 clef_width = gst_util_uint64_scale (clef_height,
5841 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5842 prof_width = gst_util_uint64_scale (width,
5843 par_num * G_GUINT64_CONSTANT (65536), par_den);
5844 clap_width_n = clap_height * dar_num * par_den;
5845 clap_width_d = dar_den * par_num;
5846 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5847 clap_width_n /= cdiv;
5848 clap_width_d /= cdiv;
5850 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5851 height << 16, width << 16, height << 16);
5852 qtpad->trak->tapt = ext_atom;
5854 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5855 clap_height, 1, 0, 1, 0, 1);
5857 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5860 /* ok, set the pad info accordingly */
5861 qtpad->fourcc = entry.fourcc;
5864 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5865 qtmux->context, &entry, rate, ext_atom_list);
5866 if (strcmp (mimetype, "video/x-prores") == 0) {
5867 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5868 const gchar *compressor = NULL;
5869 mp4v->spatial_quality = 0x3FF;
5870 mp4v->temporal_quality = 0;
5871 mp4v->vendor = FOURCC_appl;
5872 mp4v->horizontal_resolution = 72 << 16;
5873 mp4v->vertical_resolution = 72 << 16;
5874 mp4v->depth = (entry.fourcc == FOURCC_ap4h
5875 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5877 /* Set compressor name, required by some software */
5878 switch (entry.fourcc) {
5880 compressor = "Apple ProRes 422";
5883 compressor = "Apple ProRes 422 LT";
5886 compressor = "Apple ProRes 422 HQ";
5889 compressor = "Apple ProRes 422 Proxy";
5892 compressor = "Apple ProRes 4444";
5895 compressor = "Apple ProRes 4444 XQ";
5899 strcpy ((gchar *) mp4v->compressor + 1, compressor);
5900 mp4v->compressor[0] = strlen (compressor);
5904 gst_object_unref (qtmux);
5910 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5911 GST_PAD_NAME (pad), caps);
5912 gst_object_unref (qtmux);
5918 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5920 GstPad *pad = qtpad->collect.pad;
5921 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5922 GstStructure *structure;
5923 SubtitleSampleEntry entry = { 0, };
5926 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5928 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5929 GST_DEBUG_PAD_NAME (pad), caps);
5931 /* subtitles default */
5932 subtitle_sample_entry_init (&entry);
5933 qtpad->is_out_of_order = FALSE;
5934 qtpad->sync = FALSE;
5935 qtpad->sparse = TRUE;
5936 qtpad->prepare_buf_func = NULL;
5938 structure = gst_caps_get_structure (caps, 0);
5940 if (gst_structure_has_name (structure, "text/x-raw")) {
5941 const gchar *format = gst_structure_get_string (structure, "format");
5942 if (format && strcmp (format, "utf8") == 0) {
5943 entry.fourcc = FOURCC_tx3g;
5944 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
5945 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
5952 qtpad->fourcc = entry.fourcc;
5954 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
5955 qtmux->context, &entry);
5957 gst_object_unref (qtmux);
5963 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5964 GST_PAD_NAME (pad), caps);
5965 gst_object_unref (qtmux);
5971 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5973 GstPad *pad = qtpad->collect.pad;
5974 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5975 GstStructure *structure;
5976 guint32 fourcc_entry;
5980 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5982 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5983 GST_DEBUG_PAD_NAME (pad), caps);
5985 /* captions default */
5986 qtpad->is_out_of_order = FALSE;
5987 qtpad->sync = FALSE;
5988 qtpad->sparse = TRUE;
5989 /* Closed caption data are within atoms */
5990 qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
5992 structure = gst_caps_get_structure (caps, 0);
5994 /* We know we only handle 608,format=cc_data and 708,format=cdp */
5995 if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
5996 fourcc_entry = FOURCC_c608;
5997 } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
5998 fourcc_entry = FOURCC_c708;
6002 /* FIXME: Get the timescale from the video track ? */
6003 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6004 if (!timescale && qtmux->trak_timescale)
6005 timescale = qtmux->trak_timescale;
6006 else if (!timescale)
6009 qtpad->fourcc = fourcc_entry;
6011 (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6012 qtmux->context, timescale, fourcc_entry);
6014 gst_object_unref (qtmux);
6020 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6021 GST_PAD_NAME (pad), caps);
6022 gst_object_unref (qtmux);
6028 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6029 GstEvent * event, gpointer user_data)
6032 guint32 avg_bitrate = 0, max_bitrate = 0;
6033 GstPad *pad = data->pad;
6034 gboolean ret = TRUE;
6036 qtmux = GST_QT_MUX_CAST (user_data);
6037 switch (GST_EVENT_TYPE (event)) {
6038 case GST_EVENT_CAPS:
6041 GstQTPad *collect_pad;
6043 gst_event_parse_caps (event, &caps);
6045 /* find stream data */
6046 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6047 g_assert (collect_pad);
6048 g_assert (collect_pad->set_caps);
6050 ret = collect_pad->set_caps (collect_pad, caps);
6051 gst_event_unref (event);
6055 case GST_EVENT_TAG:{
6057 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6058 GstTagMergeMode mode;
6060 GstQTPad *collect_pad;
6062 GST_OBJECT_LOCK (qtmux);
6063 mode = gst_tag_setter_get_tag_merge_mode (setter);
6064 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6066 gst_event_parse_tag (event, &list);
6067 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6068 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6070 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6071 gst_tag_setter_merge_tags (setter, list, mode);
6072 qtmux->tags_changed = TRUE;
6074 if (!collect_pad->tags)
6075 collect_pad->tags = gst_tag_list_new_empty ();
6076 gst_tag_list_insert (collect_pad->tags, list, mode);
6077 collect_pad->tags_changed = TRUE;
6079 GST_OBJECT_UNLOCK (qtmux);
6081 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6082 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6083 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6086 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6087 qtpad->avg_bitrate = avg_bitrate;
6088 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6089 qtpad->max_bitrate = max_bitrate;
6092 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6093 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6095 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6098 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6099 qtpad->trak->mdia.mdhd.language_code =
6100 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
6101 (iso_code[2] - 0x60);
6107 gst_event_unref (event);
6117 return gst_collect_pads_event_default (pads, data, event, FALSE);
6123 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6125 GstQTMux *mux = GST_QT_MUX_CAST (element);
6128 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6130 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6131 GstQTPad *qtpad = (GstQTPad *) walk->data;
6132 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6133 if (qtpad->collect.pad == pad) {
6134 /* this is it, remove */
6135 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6136 gst_element_remove_pad (element, pad);
6141 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6142 mux->current_pad = NULL;
6143 mux->current_chunk_size = 0;
6144 mux->current_chunk_duration = 0;
6147 gst_collect_pads_remove_pad (mux->collect, pad);
6149 if (mux->sinkpads == NULL) {
6150 /* No more outstanding request pads, reset our counters */
6151 mux->video_pads = 0;
6152 mux->audio_pads = 0;
6153 mux->subtitle_pads = 0;
6158 gst_qt_mux_request_new_pad (GstElement * element,
6159 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6161 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6162 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6163 GstQTPad *collect_pad;
6165 GstQTPadSetCapsFunc setcaps_func;
6168 gboolean lock = TRUE;
6170 if (templ->direction != GST_PAD_SINK)
6171 goto wrong_direction;
6173 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6176 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6177 setcaps_func = gst_qt_mux_audio_sink_set_caps;
6178 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6179 name = g_strdup (req_name);
6181 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6183 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6184 setcaps_func = gst_qt_mux_video_sink_set_caps;
6185 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6186 name = g_strdup (req_name);
6188 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6190 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6191 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6192 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6193 name = g_strdup (req_name);
6195 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6198 } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6199 setcaps_func = gst_qt_mux_caption_sink_set_caps;
6200 if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6201 name = g_strdup (req_name);
6203 name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6207 goto wrong_template;
6209 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6211 /* create pad and add to collections */
6213 g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6214 templ->direction, "template", templ, NULL);
6216 collect_pad = (GstQTPad *)
6217 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6218 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6220 gst_qt_mux_pad_reset (collect_pad);
6221 collect_pad->trak = atom_trak_new (qtmux->context);
6222 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6224 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6226 /* set up pad functions */
6227 collect_pad->set_caps = setcaps_func;
6229 gst_pad_set_active (newpad, TRUE);
6230 gst_element_add_pad (element, newpad);
6237 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6242 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6247 GST_WARNING_OBJECT (qtmux, "This is not our template!");
6253 gst_qt_mux_get_property (GObject * object,
6254 guint prop_id, GValue * value, GParamSpec * pspec)
6256 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6258 GST_OBJECT_LOCK (qtmux);
6260 case PROP_MOVIE_TIMESCALE:
6261 g_value_set_uint (value, qtmux->timescale);
6263 case PROP_TRAK_TIMESCALE:
6264 g_value_set_uint (value, qtmux->trak_timescale);
6267 g_value_set_boolean (value, qtmux->guess_pts);
6269 #ifndef GST_REMOVE_DEPRECATED
6270 case PROP_DTS_METHOD:
6271 g_value_set_enum (value, qtmux->dts_method);
6274 case PROP_FAST_START:
6275 g_value_set_boolean (value, qtmux->fast_start);
6277 case PROP_FAST_START_TEMP_FILE:
6278 g_value_set_string (value, qtmux->fast_start_file_path);
6280 case PROP_MOOV_RECOV_FILE:
6281 g_value_set_string (value, qtmux->moov_recov_file_path);
6283 case PROP_FRAGMENT_DURATION:
6284 g_value_set_uint (value, qtmux->fragment_duration);
6286 case PROP_STREAMABLE:
6287 g_value_set_boolean (value, qtmux->streamable);
6289 case PROP_RESERVED_MAX_DURATION:
6290 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6292 case PROP_RESERVED_DURATION_REMAINING:
6293 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6294 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6296 GstClockTime remaining = qtmux->reserved_duration_remaining;
6298 /* Report the remaining space as the calculated remaining, minus
6299 * however much we've muxed since the last update */
6300 if (remaining > qtmux->muxed_since_last_update)
6301 remaining -= qtmux->muxed_since_last_update;
6304 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6305 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6306 remaining, qtmux->reserved_duration_remaining,
6307 qtmux->muxed_since_last_update);
6308 g_value_set_uint64 (value, remaining);
6311 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6312 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6314 case PROP_RESERVED_BYTES_PER_SEC:
6315 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6317 case PROP_RESERVED_PREFILL:
6318 g_value_set_boolean (value, qtmux->reserved_prefill);
6320 case PROP_INTERLEAVE_BYTES:
6321 g_value_set_uint64 (value, qtmux->interleave_bytes);
6323 case PROP_INTERLEAVE_TIME:
6324 g_value_set_uint64 (value, qtmux->interleave_time);
6326 case PROP_MAX_RAW_AUDIO_DRIFT:
6327 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6330 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6333 GST_OBJECT_UNLOCK (qtmux);
6337 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6341 g_free (qtmux->fast_start_file_path);
6342 qtmux->fast_start_file_path = NULL;
6344 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6345 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6350 gst_qt_mux_set_property (GObject * object,
6351 guint prop_id, const GValue * value, GParamSpec * pspec)
6353 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6355 GST_OBJECT_LOCK (qtmux);
6357 case PROP_MOVIE_TIMESCALE:
6358 qtmux->timescale = g_value_get_uint (value);
6360 case PROP_TRAK_TIMESCALE:
6361 qtmux->trak_timescale = g_value_get_uint (value);
6364 qtmux->guess_pts = g_value_get_boolean (value);
6366 #ifndef GST_REMOVE_DEPRECATED
6367 case PROP_DTS_METHOD:
6368 qtmux->dts_method = g_value_get_enum (value);
6371 case PROP_FAST_START:
6372 qtmux->fast_start = g_value_get_boolean (value);
6374 case PROP_FAST_START_TEMP_FILE:
6375 g_free (qtmux->fast_start_file_path);
6376 qtmux->fast_start_file_path = g_value_dup_string (value);
6377 /* NULL means to generate a random one */
6378 if (!qtmux->fast_start_file_path) {
6379 gst_qt_mux_generate_fast_start_file_path (qtmux);
6382 case PROP_MOOV_RECOV_FILE:
6383 g_free (qtmux->moov_recov_file_path);
6384 qtmux->moov_recov_file_path = g_value_dup_string (value);
6386 case PROP_FRAGMENT_DURATION:
6387 qtmux->fragment_duration = g_value_get_uint (value);
6389 case PROP_STREAMABLE:{
6390 GstQTMuxClass *qtmux_klass =
6391 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6392 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6393 qtmux->streamable = g_value_get_boolean (value);
6397 case PROP_RESERVED_MAX_DURATION:
6398 qtmux->reserved_max_duration = g_value_get_uint64 (value);
6400 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6401 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6403 case PROP_RESERVED_BYTES_PER_SEC:
6404 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6406 case PROP_RESERVED_PREFILL:
6407 qtmux->reserved_prefill = g_value_get_boolean (value);
6409 case PROP_INTERLEAVE_BYTES:
6410 qtmux->interleave_bytes = g_value_get_uint64 (value);
6411 qtmux->interleave_bytes_set = TRUE;
6413 case PROP_INTERLEAVE_TIME:
6414 qtmux->interleave_time = g_value_get_uint64 (value);
6415 qtmux->interleave_time_set = TRUE;
6417 case PROP_MAX_RAW_AUDIO_DRIFT:
6418 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6421 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6424 GST_OBJECT_UNLOCK (qtmux);
6427 static GstStateChangeReturn
6428 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6430 GstStateChangeReturn ret;
6431 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6433 switch (transition) {
6434 case GST_STATE_CHANGE_NULL_TO_READY:
6436 case GST_STATE_CHANGE_READY_TO_PAUSED:
6437 gst_collect_pads_start (qtmux->collect);
6438 qtmux->state = GST_QT_MUX_STATE_STARTED;
6440 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6442 case GST_STATE_CHANGE_PAUSED_TO_READY:
6443 gst_collect_pads_stop (qtmux->collect);
6449 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6451 switch (transition) {
6452 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6454 case GST_STATE_CHANGE_PAUSED_TO_READY:
6455 gst_qt_mux_reset (qtmux, TRUE);
6457 case GST_STATE_CHANGE_READY_TO_NULL:
6467 gst_qt_mux_register (GstPlugin * plugin)
6469 GTypeInfo typeinfo = {
6470 sizeof (GstQTMuxClass),
6471 (GBaseInitFunc) gst_qt_mux_base_init,
6473 (GClassInitFunc) gst_qt_mux_class_init,
6478 (GInstanceInitFunc) gst_qt_mux_init,
6480 static const GInterfaceInfo tag_setter_info = {
6483 static const GInterfaceInfo tag_xmp_writer_info = {
6486 static const GInterfaceInfo preset_info = {
6490 GstQTMuxFormat format;
6491 GstQTMuxClassParams *params;
6494 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6496 GST_LOG ("Registering muxers");
6499 GstQTMuxFormatProp *prop;
6500 GstCaps *subtitle_caps, *caption_caps;
6502 prop = &gst_qt_mux_format_list[i];
6503 format = prop->format;
6504 if (format == GST_QT_MUX_FORMAT_NONE)
6507 /* create a cache for these properties */
6508 params = g_new0 (GstQTMuxClassParams, 1);
6509 params->prop = prop;
6510 params->src_caps = gst_static_caps_get (&prop->src_caps);
6511 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6512 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6513 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6514 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6515 params->subtitle_sink_caps = subtitle_caps;
6517 gst_caps_unref (subtitle_caps);
6519 caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6520 if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6521 params->caption_sink_caps = caption_caps;
6523 gst_caps_unref (caption_caps);
6526 /* create the type now */
6527 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6529 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6530 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6531 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6532 &tag_xmp_writer_info);
6533 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6535 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6541 GST_LOG ("Finished registering muxers");
6543 /* FIXME: ideally classification tag should be added and
6544 registered in gstreamer core gsttaglist
6547 GST_LOG ("Registering tags");
6549 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6550 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6551 gst_tag_merge_use_first);
6553 GST_LOG ("Finished registering tags");