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;
943 extract_608_field_from_cc_data (inmap.data, inmap.size, 1, &cdat);
945 extract_608_field_from_cc_data (inmap.data, inmap.size, 2, &cdt2);
948 total_size += cdat_size + 8;
950 total_size += cdt2_size + 8;
951 if (total_size == 0) {
952 GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
953 /* FIXME : We might want to *always* store something, even if
954 * it's "empty" CC (i.e. 0x80 0x80) */
958 newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
959 /* Let's copy over all metadata and not the memory */
960 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
962 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
963 if (cdat_size || in_prefill) {
964 GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
965 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
967 memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
969 /* Write 'empty' CC */
973 write_offs = in_prefill ? 10 : cdat_size + 8;
978 if (cdt2_size || in_prefill) {
979 GST_WRITE_UINT32_BE (map.data + write_offs,
980 in_prefill ? 10 : cdt2_size + 8);
981 GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
983 memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
985 /* Write 'empty' CC */
986 map.data[write_offs + 8] = 0x80;
987 map.data[write_offs + 9] = 0x80;
992 gst_buffer_unmap (newbuf, &map);
998 /* Take the whole CDP */
999 if (in_prefill && size > 92) {
1000 GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1003 newbuf = gst_buffer_new_and_alloc (in_prefill ? 100 : size + 8);
1005 /* Let's copy over all metadata and not the memory */
1006 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1008 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1010 GST_WRITE_UINT32_BE (map.data, size + 8);
1011 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1012 memcpy (map.data + 8, inmap.data, inmap.size);
1014 gst_buffer_unmap (newbuf, &map);
1018 /* theoretically this should never happen, but let's keep this here in case */
1019 GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1023 gst_buffer_unmap (buf, &inmap);
1024 gst_buffer_unref (buf);
1030 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1037 const guint8 *dataend;
1039 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1044 gst_buffer_map (buf, &frommap, GST_MAP_READ);
1046 dataend = memchr (frommap.data, 0, frommap.size);
1047 size = dataend ? dataend - frommap.data : frommap.size;
1048 newbuf = gst_buffer_new_and_alloc (size + 2);
1050 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1052 GST_WRITE_UINT16_BE (tomap.data, size);
1053 memcpy (tomap.data + 2, frommap.data, size);
1055 gst_buffer_unmap (newbuf, &tomap);
1056 gst_buffer_unmap (buf, &frommap);
1058 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1060 /* gst_buffer_copy_into is trying to be too clever and
1061 * won't copy duration when size is different */
1062 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1064 gst_buffer_unref (buf);
1070 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1071 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1076 g_return_if_fail (qtpad->trak_ste);
1078 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
1080 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1084 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1088 GstByteReader reader;
1091 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1092 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1096 if (G_UNLIKELY (map.size < 8))
1099 gst_byte_reader_init (&reader, map.data, map.size);
1100 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1105 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1107 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1110 gst_bit_reader_init (&bits, map.data, map.size);
1112 /* off + sync + crc */
1113 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1115 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1116 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1117 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1118 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1119 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1121 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1122 gst_bit_reader_skip_unchecked (&bits, 2);
1123 if ((acmod & 0x4)) /* if a surround channel exists */
1124 gst_bit_reader_skip_unchecked (&bits, 2);
1125 if (acmod == 0x2) /* if in 2/0 mode */
1126 gst_bit_reader_skip_unchecked (&bits, 2);
1128 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1130 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1131 bsmod, acmod, lfe_on);
1133 /* AC-3 spec says that those values should be constant for the
1134 * whole stream when muxed in mp4. We trust the input follows it */
1135 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1136 "prepare buffer function");
1137 qtpad->prepare_buf_func = NULL;
1141 gst_buffer_unmap (buf, &map);
1146 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1150 data = g_malloc (2);
1151 GST_WRITE_UINT16_BE (data, 0);
1153 return gst_buffer_new_wrapped (data, 2);
1157 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1158 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1160 switch (gst_tag_get_type (tag)) {
1166 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1168 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1169 GST_FOURCC_ARGS (fourcc), str);
1170 atom_udta_add_str_tag (udta, fourcc, str);
1179 if (!gst_tag_list_get_double (list, tag, &value))
1181 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1182 GST_FOURCC_ARGS (fourcc), (gint) value);
1183 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1190 /* paired unsigned integers */
1194 got_tag = gst_tag_list_get_uint (list, tag, &value);
1195 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1198 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1199 GST_FOURCC_ARGS (fourcc), value, count);
1200 atom_udta_add_uint_tag (udta, fourcc, 0,
1201 value << 16 | (count & 0xFFFF));
1203 /* unpaired unsigned integers */
1204 if (!gst_tag_list_get_uint (list, tag, &value))
1206 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1207 GST_FOURCC_ARGS (fourcc), value);
1208 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1213 g_assert_not_reached ();
1219 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1220 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1228 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1230 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1233 year = g_date_get_year (date);
1234 month = g_date_get_month (date);
1235 day = g_date_get_day (date);
1239 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1240 day == G_DATE_BAD_DAY) {
1241 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1245 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1246 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1247 GST_FOURCC_ARGS (fourcc), str);
1248 atom_udta_add_str_tag (udta, fourcc, str);
1253 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1254 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1256 GValue value = { 0, };
1260 GstStructure *structure;
1264 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1266 if (!gst_tag_list_copy_value (&value, list, tag))
1269 sample = gst_value_get_sample (&value);
1274 buf = gst_sample_get_buffer (sample);
1278 caps = gst_sample_get_caps (sample);
1280 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1284 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1286 structure = gst_caps_get_structure (caps, 0);
1287 if (gst_structure_has_name (structure, "image/jpeg"))
1289 else if (gst_structure_has_name (structure, "image/png"))
1293 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1297 gst_buffer_map (buf, &map, GST_MAP_READ);
1298 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1299 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1300 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1301 gst_buffer_unmap (buf, &map);
1303 g_value_unset (&value);
1307 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1308 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1313 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1314 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1316 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1320 if (!gst_tag_list_get_uint (list, tag2, &number))
1324 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1325 GST_FOURCC_ARGS (fourcc), str);
1326 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1328 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1329 GST_FOURCC_ARGS (fourcc), str, number);
1330 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1337 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1338 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1343 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1345 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1348 year = g_date_get_year (date);
1351 if (year == G_DATE_BAD_YEAR) {
1352 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1356 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1357 GST_FOURCC_ARGS (fourcc), year);
1358 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1362 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1363 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1365 gdouble latitude = -360, longitude = -360, altitude = 0;
1366 gchar *location = NULL;
1367 guint8 *data, *ddata;
1368 gint size = 0, len = 0;
1369 gboolean ret = FALSE;
1371 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1373 ret = gst_tag_list_get_string (list, tag, &location);
1374 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1376 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1378 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1385 len = strlen (location);
1386 size += len + 1 + 2;
1388 /* role + (long, lat, alt) + body + notes */
1389 size += 1 + 3 * 4 + 1 + 1;
1391 data = ddata = g_malloc (size);
1394 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1397 memcpy (data + 2, location, len);
1398 GST_WRITE_UINT8 (data + 2 + len, 0);
1399 data += len + 1 + 2;
1401 GST_WRITE_UINT8 (data, 0);
1402 /* long, lat, alt */
1403 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1404 QT_WRITE_SFP32 (data + 1, longitude);
1405 QT_WRITE_SFP32 (data + 5, latitude);
1406 QT_WRITE_SFP32 (data + 9, altitude);
1407 /* neither astronomical body nor notes */
1408 GST_WRITE_UINT16_BE (data + 13, 0);
1410 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1411 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1416 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1417 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1419 gchar *keywords = NULL;
1420 guint8 *data, *ddata;
1424 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1426 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1429 kwds = g_strsplit (keywords, ",", 0);
1433 for (i = 0; kwds[i]; i++) {
1434 /* size byte + null-terminator */
1435 size += strlen (kwds[i]) + 1 + 1;
1438 /* language tag + count + keywords */
1441 data = ddata = g_malloc (size);
1444 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1446 GST_WRITE_UINT8 (data + 2, i);
1449 for (i = 0; kwds[i]; ++i) {
1450 gint len = strlen (kwds[i]);
1452 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1453 GST_FOURCC_ARGS (fourcc), kwds[i]);
1455 GST_WRITE_UINT8 (data, len + 1);
1456 memcpy (data + 1, kwds[i], len + 1);
1462 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1467 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1468 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1476 size = strlen (input);
1478 if (size < 4 + 3 + 1 + 1 + 1) {
1479 /* at least the minimum xxxx://y/z */
1480 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1485 /* read the fourcc */
1486 memcpy (&fourcc, data, 4);
1490 if (strncmp (data, "://", 3) != 0) {
1496 /* read the table number */
1497 if (sscanf (data, "%d", &table) != 1) {
1501 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1502 ", table numbers should be positive, ignoring tag", table);
1506 /* find the next / */
1507 while (size > 0 && data[0] != '/') {
1514 g_assert (data[0] == '/');
1523 /* read up the rest of the string */
1524 *p_content = g_strdup (data);
1525 *p_table = (guint16) table;
1531 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1532 "input (%s) didn't match the expected entitycode://table/content",
1539 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1540 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1542 gchar *clsf_data = NULL;
1546 gchar *content = NULL;
1549 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1551 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1554 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1555 GST_FOURCC_ARGS (fourcc), clsf_data);
1557 /* parse the string, format is:
1558 * entityfourcc://table/content
1560 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1564 size = strlen (content) + 1;
1566 /* now we have everything, build the atom
1567 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1568 data = g_malloc (4 + 2 + 2 + size);
1569 GST_WRITE_UINT32_LE (data, entity);
1570 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1571 GST_WRITE_UINT16_BE (data + 6, 0);
1572 memcpy (data + 8, content, size);
1575 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1579 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1580 const GstTagList * list, AtomUDTA * udta, const char *tag,
1581 const char *tag2, guint32 fourcc);
1584 * Struct to record mappings from gstreamer tags to fourcc codes
1586 typedef struct _GstTagToFourcc
1589 const gchar *gsttag;
1590 const gchar *gsttag2;
1591 const GstQTMuxAddUdtaTagFunc func;
1594 /* tag list tags to fourcc matching */
1595 static const GstTagToFourcc tag_matches_mp4[] = {
1596 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1597 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1598 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1599 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1600 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1601 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1602 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1603 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1604 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1605 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1606 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1607 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1608 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1609 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1610 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1611 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1612 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1613 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1614 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1615 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1616 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1617 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1618 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1619 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1620 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1621 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1622 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1623 gst_qt_mux_add_mp4_tag},
1624 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1625 gst_qt_mux_add_mp4_tag},
1626 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1627 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1631 static const GstTagToFourcc tag_matches_3gp[] = {
1632 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1633 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1634 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1635 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1636 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1637 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1638 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1639 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1640 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1641 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1642 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1643 gst_qt_mux_add_3gp_classification},
1647 /* qtdemux produces these for atoms it cannot parse */
1648 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1651 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1653 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1654 GstBuffer *xmp = NULL;
1656 /* adobe specs only have 'quicktime' and 'mp4',
1657 * but I guess we can extrapolate to gpp.
1658 * Keep mj2 out for now as we don't add any tags for it yet.
1659 * If you have further info about xmp on these formats, please share */
1660 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1663 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1665 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1666 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1669 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1672 /* for isom/mp4, it is a top level uuid atom */
1673 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1676 ainfo = build_uuid_xmp_atom (xmp);
1678 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1683 gst_buffer_unref (xmp);
1687 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1690 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1693 const gchar *tag, *tag2;
1694 const GstTagToFourcc *tag_matches;
1696 switch (qtmux_klass->format) {
1697 case GST_QT_MUX_FORMAT_3GP:
1698 tag_matches = tag_matches_3gp;
1700 case GST_QT_MUX_FORMAT_MJ2:
1704 /* sort of iTunes style for mp4 and QT (?) */
1705 tag_matches = tag_matches_mp4;
1712 /* Clear existing tags so we don't add them over and over */
1713 atom_udta_clear_tags (udta);
1715 for (i = 0; tag_matches[i].fourcc; i++) {
1716 fourcc = tag_matches[i].fourcc;
1717 tag = tag_matches[i].gsttag;
1718 tag2 = tag_matches[i].gsttag2;
1720 g_assert (tag_matches[i].func);
1721 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1724 /* add unparsed blobs if present */
1725 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1728 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1729 for (i = 0; i < num_tags; ++i) {
1730 GstSample *sample = NULL;
1732 const GstStructure *s;
1734 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1737 buf = gst_sample_get_buffer (sample);
1739 if (buf && (s = gst_sample_get_info (sample))) {
1740 const gchar *style = NULL;
1743 gst_buffer_map (buf, &map, GST_MAP_READ);
1744 GST_DEBUG_OBJECT (qtmux,
1745 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1746 GST_PTR_FORMAT, i, num_tags, map.size, s);
1747 if (s && (style = gst_structure_get_string (s, "style"))) {
1748 /* try to prevent some style tag ending up into another variant
1749 * (todo: make into a list if more cases) */
1750 if ((strcmp (style, "itunes") == 0 &&
1751 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1752 (strcmp (style, "iso") == 0 &&
1753 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1754 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1755 atom_udta_add_blob_tag (udta, map.data, map.size);
1758 gst_buffer_unmap (buf, &map);
1760 gst_sample_unref (sample);
1768 * Gets the tagsetter iface taglist and puts the known tags
1769 * into the output stream
1772 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1774 const GstTagList *tags = NULL;
1777 GST_OBJECT_LOCK (qtmux);
1778 if (qtmux->tags_changed) {
1779 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1780 qtmux->tags_changed = FALSE;
1782 GST_OBJECT_UNLOCK (qtmux);
1784 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1786 if (tags && !gst_tag_list_is_empty (tags)) {
1787 GstTagList *copy = gst_tag_list_copy (tags);
1789 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1790 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1791 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1792 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1794 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1795 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1796 gst_qt_mux_add_xmp_tags (qtmux, copy);
1797 gst_tag_list_unref (copy);
1799 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1802 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1803 GstCollectData *cdata = (GstCollectData *) walk->data;
1804 GstQTPad *qpad = (GstQTPad *) cdata;
1805 GstPad *pad = qpad->collect.pad;
1807 if (qpad->tags_changed && qpad->tags) {
1808 GST_DEBUG_OBJECT (pad, "Adding tags");
1809 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1810 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1811 qpad->tags_changed = FALSE;
1812 GST_DEBUG_OBJECT (pad, "Tags added");
1814 GST_DEBUG_OBJECT (pad, "No new tags received");
1819 static inline GstBuffer *
1820 _gst_buffer_new_take_data (guint8 * data, guint size)
1824 buf = gst_buffer_new ();
1825 gst_buffer_append_memory (buf,
1826 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1831 static GstFlowReturn
1832 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1838 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1840 size = gst_buffer_get_size (buf);
1841 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1843 if (mind_fast && qtmux->fast_start_file) {
1847 GST_LOG_OBJECT (qtmux, "to temporary file");
1848 gst_buffer_map (buf, &map, GST_MAP_READ);
1849 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1850 gst_buffer_unmap (buf, &map);
1851 gst_buffer_unref (buf);
1857 GST_LOG_OBJECT (qtmux, "downstream");
1858 res = gst_pad_push (qtmux->srcpad, buf);
1861 if (G_LIKELY (offset))
1869 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1870 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1871 return GST_FLOW_ERROR;
1876 gst_qt_mux_seek_to_beginning (FILE * f)
1879 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1881 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1882 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1885 if (fseek (f, (long) 0, SEEK_SET) != 0)
1891 static GstFlowReturn
1892 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1894 GstFlowReturn ret = GST_FLOW_OK;
1895 GstBuffer *buf = NULL;
1897 if (fflush (qtmux->fast_start_file))
1900 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1903 /* hm, this could all take a really really long time,
1904 * but there may not be another way to get moov atom first
1905 * (somehow optimize copy?) */
1906 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1907 while (ret == GST_FLOW_OK) {
1908 const int bufsize = 4096;
1912 buf = gst_buffer_new_and_alloc (bufsize);
1913 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1914 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1916 gst_buffer_unmap (buf, &map);
1919 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1920 gst_buffer_unmap (buf, &map);
1921 if (size != bufsize)
1922 gst_buffer_set_size (buf, size);
1923 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1927 gst_buffer_unref (buf);
1929 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1931 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1939 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1940 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1941 ret = GST_FLOW_ERROR;
1946 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1947 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1948 ret = GST_FLOW_ERROR;
1953 /* clear descriptor so we don't remove temp file later on,
1954 * might be possible to recover */
1955 fclose (qtmux->fast_start_file);
1956 qtmux->fast_start_file = NULL;
1962 * Sends the initial mdat atom fields (size fields and fourcc type),
1963 * the subsequent buffers are considered part of it's data.
1964 * As we can't predict the amount of data that we are going to place in mdat
1965 * we need to record the position of the size field in the stream so we can
1966 * seek back to it later and update when the streams have finished.
1968 static GstFlowReturn
1969 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1970 gboolean extended, gboolean fsync_after)
1975 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1976 "size %" G_GUINT64_FORMAT, size);
1978 /* if the qtmux state is EOS, really write the mdat, otherwise
1979 * allow size == 0 for a placeholder atom */
1980 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1984 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1985 /* Always write 16-bytes, but put a free atom first
1986 * if the size is < 4GB. */
1987 buf = gst_buffer_new_and_alloc (16);
1988 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1991 /* Write extended mdat header and large_size field */
1992 GST_WRITE_UINT32_BE (map.data, 1);
1993 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1994 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1996 /* Write an empty free atom, then standard 32-bit mdat */
1997 GST_WRITE_UINT32_BE (map.data, 8);
1998 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1999 GST_WRITE_UINT32_BE (map.data + 8, size);
2000 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2002 gst_buffer_unmap (buf, &map);
2004 buf = gst_buffer_new_and_alloc (8);
2005 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2007 /* Vanilla 32-bit mdat */
2008 GST_WRITE_UINT32_BE (map.data, size);
2009 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2010 gst_buffer_unmap (buf, &map);
2013 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2015 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2017 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2022 * We get the position of the mdat size field, seek back to it
2023 * and overwrite with the real value
2025 static GstFlowReturn
2026 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2027 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2031 /* We must have recorded the mdat position for this to work */
2032 g_assert (mdat_pos != 0);
2034 /* seek and rewrite the header */
2035 gst_segment_init (&segment, GST_FORMAT_BYTES);
2036 segment.start = mdat_pos;
2037 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2039 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2043 static GstFlowReturn
2044 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2047 guint64 size = 0, offset = 0;
2048 guint8 *data = NULL;
2050 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2052 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2053 goto serialize_error;
2055 buf = _gst_buffer_new_take_data (data, offset);
2057 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2058 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2063 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2064 ("Failed to serialize ftyp"));
2065 return GST_FLOW_ERROR;
2070 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2071 GstBuffer ** p_prefix)
2073 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2074 guint32 major, version;
2076 GstBuffer *prefix = NULL;
2077 AtomFTYP *ftyp = NULL;
2079 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2081 /* init and send context and ftyp based on current property state */
2082 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2083 &version, &comp, qtmux->moov, qtmux->longest_chunk,
2084 qtmux->fast_start_file != NULL);
2085 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2092 gst_buffer_unref (prefix);
2097 static GstFlowReturn
2098 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2100 GstFlowReturn ret = GST_FLOW_OK;
2101 GstBuffer *prefix = NULL;
2103 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2105 /* init and send context and ftyp based on current property state */
2107 atom_ftyp_free (qtmux->ftyp);
2110 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2112 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2113 if (ret != GST_FLOW_OK)
2116 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2120 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2122 GstStructure *structure;
2123 GValue array = { 0 };
2124 GValue value = { 0 };
2125 GstCaps *caps, *tcaps;
2127 tcaps = gst_pad_get_current_caps (mux->srcpad);
2128 caps = gst_caps_copy (tcaps);
2129 gst_caps_unref (tcaps);
2131 structure = gst_caps_get_structure (caps, 0);
2133 g_value_init (&array, GST_TYPE_ARRAY);
2135 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2136 g_value_init (&value, GST_TYPE_BUFFER);
2137 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2138 gst_value_array_append_value (&array, &value);
2139 g_value_unset (&value);
2141 gst_structure_set_value (structure, "streamheader", &array);
2142 g_value_unset (&array);
2143 gst_pad_set_caps (mux->srcpad, caps);
2144 gst_caps_unref (caps);
2148 * Write out a free space atom. The offset is adjusted by the full
2149 * size, but a smaller buffer is sent
2151 static GstFlowReturn
2152 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2153 gboolean fsync_after)
2157 guint8 *data = NULL;
2158 guint64 offset = 0, bsize = 0;
2161 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2163 /* We can't make a free space atom smaller than the header */
2167 node_header = g_malloc0 (sizeof (Atom));
2168 node_header->type = FOURCC_free;
2169 node_header->size = size;
2172 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2173 goto serialize_error;
2175 buf = _gst_buffer_new_take_data (data, offset);
2176 g_free (node_header);
2179 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2181 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2182 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2189 /* Make sure downstream position ends up at the end of this free box */
2190 gst_segment_init (&segment, GST_FORMAT_BYTES);
2191 segment.start = *off;
2192 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2200 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2201 ("Not enough free reserved space"));
2202 return GST_FLOW_ERROR;
2206 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2207 ("Failed to serialize mdat"));
2208 g_free (node_header);
2209 return GST_FLOW_ERROR;
2214 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2216 gboolean fragmented = FALSE;
2219 GST_OBJECT_LOCK (qtmux);
2220 timescale = qtmux->timescale;
2221 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2222 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2224 GST_OBJECT_UNLOCK (qtmux);
2226 /* inform lower layers of our property wishes, and determine duration.
2227 * Let moov take care of this using its list of traks;
2228 * so that released pads are also included */
2229 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2231 atom_moov_update_timescale (qtmux->moov, timescale);
2232 atom_moov_set_fragmented (qtmux->moov, fragmented);
2234 atom_moov_update_duration (qtmux->moov);
2237 static GstFlowReturn
2238 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2239 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2241 guint64 offset = 0, size = 0;
2244 GstFlowReturn ret = GST_FLOW_OK;
2246 guint64 current_time = atoms_get_current_qt_time ();
2248 /* update modification times */
2249 qtmux->moov->mvhd.time_info.modification_time = current_time;
2250 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2251 GstCollectData *cdata = (GstCollectData *) walk->data;
2252 GstQTPad *qtpad = (GstQTPad *) cdata;
2254 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2255 qtpad->trak->tkhd.modification_time = current_time;
2258 /* serialize moov */
2261 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2262 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2263 goto serialize_error;
2264 qtmux->last_moov_size = offset;
2266 /* Check we have enough reserved space for this and a Free atom */
2267 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2268 goto too_small_reserved;
2269 buf = _gst_buffer_new_take_data (data, offset);
2270 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2272 /* If at EOS, this is the final moov, put in the streamheader
2273 * (apparently used by a flumotion util) */
2274 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2275 gst_qt_mux_set_header_on_caps (qtmux, buf);
2278 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2279 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2281 /* Write out a free atom if needed */
2282 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2283 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2284 (guint32) (padded_moov_size - offset));
2286 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2293 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2294 ("Not enough free reserved header space"),
2295 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2296 offset, padded_moov_size));
2297 return GST_FLOW_ERROR;
2302 return GST_FLOW_ERROR;
2306 /* either calculates size of extra atoms or pushes them */
2307 static GstFlowReturn
2308 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2312 guint64 loffset = 0, size = 0;
2314 GstFlowReturn ret = GST_FLOW_OK;
2316 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2317 AtomInfo *ainfo = (AtomInfo *) walk->data;
2321 if (!ainfo->copy_data_func (ainfo->atom,
2322 send ? &data : NULL, &size, &loffset))
2323 goto serialize_error;
2328 GST_DEBUG_OBJECT (qtmux,
2329 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2330 GST_FOURCC_ARGS (ainfo->atom->type));
2331 buf = _gst_buffer_new_take_data (data, loffset);
2332 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2333 if (ret != GST_FLOW_OK)
2346 return GST_FLOW_ERROR;
2351 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2353 gboolean seekable = FALSE;
2354 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2356 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2357 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2358 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2360 /* have to assume seeking is not supported if query not handled downstream */
2361 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2364 gst_query_unref (query);
2370 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2373 gboolean fail = FALSE;
2374 AtomFTYP *ftyp = NULL;
2375 GstBuffer *prefix = NULL;
2377 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2378 qtmux->moov_recov_file_path);
2380 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2381 if (qtmux->moov_recov_file == NULL) {
2382 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2383 qtmux->moov_recov_file_path);
2387 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2389 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2390 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2391 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2395 atom_ftyp_free (ftyp);
2397 gst_buffer_unref (prefix);
2399 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2400 GstCollectData *cdata = (GstCollectData *) walk->data;
2401 GstQTPad *qpad = (GstQTPad *) cdata;
2402 /* write info for each stream */
2403 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2405 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2415 fclose (qtmux->moov_recov_file);
2416 qtmux->moov_recov_file = NULL;
2420 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2422 switch (qpad->fourcc) {
2431 return qpad->sample_offset;
2434 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2435 qpad->expected_sample_duration_n,
2436 qpad->expected_sample_duration_d *
2437 atom_trak_get_timescale (qpad->trak));
2444 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2446 switch (qpad->fourcc) {
2448 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2450 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2452 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2454 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2461 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2463 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2465 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2467 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2474 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2476 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2478 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2480 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2487 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2489 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2491 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2493 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2500 /* We always write both cdat and cdt2 atom in prefill mode */
2503 /* We're cheating a bit by always allocating 100bytes even if we use less */
2508 guint64 next_sample_offset;
2510 block_idx = prefill_get_block_index (qtmux, qpad);
2511 next_sample_offset =
2512 gst_util_uint64_scale (block_idx + 1,
2513 qpad->expected_sample_duration_d *
2514 atom_trak_get_timescale (qpad->trak),
2515 qpad->expected_sample_duration_n);
2517 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2522 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2530 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2532 switch (qpad->fourcc) {
2541 return gst_util_uint64_scale (qpad->sample_offset + 1,
2542 qpad->expected_sample_duration_d * GST_SECOND,
2543 qpad->expected_sample_duration_n);
2547 guint64 next_sample_offset;
2549 block_idx = prefill_get_block_index (qtmux, qpad);
2550 next_sample_offset =
2551 gst_util_uint64_scale (block_idx + 1,
2552 qpad->expected_sample_duration_d *
2553 atom_trak_get_timescale (qpad->trak),
2554 qpad->expected_sample_duration_n);
2556 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2557 atom_trak_get_timescale (qpad->trak));
2560 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2568 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2573 GstClockTime input_timestamp;
2574 guint64 input_timestamp_distance;
2577 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2579 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2580 qtpad->expected_sample_duration_n,
2581 qtpad->expected_sample_duration_d *
2582 atom_trak_get_timescale (qtpad->trak));
2584 gst_util_uint64_scale (block_idx + 1,
2585 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2586 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2588 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2589 GST_COLLECT_PADS_STATE_EOS)
2590 && gst_adapter_available (qtpad->raw_audio_adapter) <
2591 nsamples * qtpad->sample_size)
2592 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2597 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2598 &input_timestamp_distance);
2599 if (input_timestamp != GST_CLOCK_TIME_NONE)
2601 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2602 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2605 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2606 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2607 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2608 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2609 GST_BUFFER_PTS (buf) = input_timestamp;
2610 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2611 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2613 qtpad->raw_audio_adapter_offset += nsamples;
2615 /* Check if we have yet another block of raw audio in the adapter */
2617 gst_util_uint64_scale (block_idx + 2,
2618 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2619 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2620 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2621 nsamples * qtpad->sample_size) {
2623 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2624 &input_timestamp_distance);
2625 if (input_timestamp != GST_CLOCK_TIME_NONE)
2627 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2628 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2629 qtpad->raw_audio_adapter_pts = input_timestamp;
2631 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2638 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2642 /* Find the (first) video track and assume that we have to output
2644 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2645 GstCollectData *cdata = (GstCollectData *) walk->data;
2646 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2648 if (tmp_qpad->trak->is_video) {
2649 *dur_n = tmp_qpad->expected_sample_duration_n;
2650 *dur_d = tmp_qpad->expected_sample_duration_d;
2656 GST_INFO_OBJECT (qtmux,
2657 "Found no video framerate, using 40ms audio buffers");
2663 /* Called when all pads are prerolled to adjust and */
2665 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2667 switch (qpad->fourcc) {
2675 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2676 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2682 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2683 /* We need a "valid" duration */
2684 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2685 &qpad->expected_sample_duration_d);
2686 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2691 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2692 &qpad->expected_sample_duration_d);
2693 /* Set a prepare_buf_func that ensures this */
2694 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2695 qpad->raw_audio_adapter = gst_adapter_new ();
2696 qpad->raw_audio_adapter_offset = 0;
2697 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2706 /* Only called at startup when doing the "fake" iteration of all tracks in order
2707 * to prefill the sample tables in the header. */
2709 find_best_pad_prefill_start (GstQTMux * qtmux)
2712 GstQTPad *best_pad = NULL;
2714 /* If interleave limits have been specified and the current pad is within
2715 * those interleave limits, pick that one, otherwise let's try to figure out
2716 * the next best one. */
2717 if (qtmux->current_pad &&
2718 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2719 (qtmux->interleave_bytes == 0
2720 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2721 && (qtmux->interleave_time == 0
2722 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2723 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2724 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2726 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2727 best_pad = qtmux->current_pad;
2729 } else if (qtmux->collect->data->next) {
2730 /* Attempt to try another pad if we have one. Otherwise use the only pad
2732 best_pad = qtmux->current_pad = NULL;
2735 /* The next best pad is the one which has the lowest timestamp and hasn't
2736 * exceeded the reserved max duration */
2738 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2740 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2741 GstCollectData *cdata = (GstCollectData *) walk->data;
2742 GstQTPad *qtpad = (GstQTPad *) cdata;
2743 GstClockTime timestamp;
2745 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2748 timestamp = qtpad->total_duration;
2750 if (best_pad == NULL ||
2751 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2753 best_time = timestamp;
2761 /* Called when starting the file in prefill_mode to figure out all the entries
2762 * of the header based on the input stream and reserved maximum duration.
2764 * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2765 * will be updated and written on EOS. */
2767 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2771 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2773 /* Update expected sample sizes/durations as needed, this is for raw
2774 * audio where samples are actual audio samples. */
2775 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2776 GstCollectData *cdata = (GstCollectData *) walk->data;
2777 GstQTPad *qpad = (GstQTPad *) cdata;
2779 if (!prefill_update_sample_size (qtmux, qpad))
2783 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2784 /* For the first sample check/update timecode as needed. We do that before
2785 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2786 * initial buffer directly, not with last_buf */
2787 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2788 GstCollectData *cdata = (GstCollectData *) walk->data;
2789 GstQTPad *qpad = (GstQTPad *) cdata;
2791 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2792 GstVideoTimeCodeMeta *tc_meta;
2794 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2795 GstVideoTimeCode *tc = &tc_meta->tc;
2797 qpad->tc_trak = atom_trak_new (qtmux->context);
2798 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2800 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2801 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2803 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2804 qpad->trak->mdia.mdhd.time_info.timescale, tc);
2806 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2807 qtmux->mdat_size, FALSE, 0);
2809 qpad->tc_pos = qtmux->mdat_size;
2810 qpad->first_tc = gst_video_time_code_copy (tc);
2811 qpad->first_pts = GST_BUFFER_PTS (buffer);
2813 qtmux->current_chunk_offset = -1;
2814 qtmux->current_chunk_size = 0;
2815 qtmux->current_chunk_duration = 0;
2816 qtmux->mdat_size += 4;
2819 gst_buffer_unref (buffer);
2823 while ((qpad = find_best_pad_prefill_start (qtmux))) {
2824 GstClockTime timestamp, next_timestamp, duration;
2825 guint nsamples, sample_size;
2826 guint64 chunk_offset;
2827 gint64 scaled_duration;
2828 gint64 pts_offset = 0;
2829 gboolean sync = FALSE;
2830 TrakBufferEntryInfo sample_entry;
2832 sample_size = prefill_get_sample_size (qtmux, qpad);
2834 if (sample_size == -1) {
2839 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2841 timestamp = qpad->total_duration;
2842 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2843 duration = next_timestamp - timestamp;
2845 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2846 qpad->first_ts = timestamp;
2847 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2848 qpad->first_dts = timestamp;
2850 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2851 qtmux->current_pad = qpad;
2852 if (qtmux->current_chunk_offset == -1)
2853 qtmux->current_chunk_offset = qtmux->mdat_size;
2855 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2856 qtmux->current_chunk_size = 0;
2857 qtmux->current_chunk_duration = 0;
2859 if (qpad->sample_size)
2860 nsamples = sample_size / qpad->sample_size;
2863 qpad->last_dts = timestamp;
2864 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2865 atom_trak_get_timescale (qpad->trak),
2866 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2867 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2869 qtmux->current_chunk_size += sample_size;
2870 qtmux->current_chunk_duration += duration;
2871 qpad->total_bytes += sample_size;
2873 chunk_offset = qtmux->current_chunk_offset;
2875 /* I-frame only, no frame reordering */
2879 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2880 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2881 qtmux->longest_chunk = qtmux->current_chunk_duration;
2884 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2885 sample_entry.nsamples = nsamples;
2886 sample_entry.delta = scaled_duration / nsamples;
2887 sample_entry.size = sample_size / nsamples;
2888 sample_entry.chunk_offset = chunk_offset;
2889 sample_entry.pts_offset = pts_offset;
2890 sample_entry.sync = sync;
2891 sample_entry.do_pts = TRUE;
2892 g_array_append_val (qpad->samples, sample_entry);
2893 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2894 sample_size / nsamples, chunk_offset, sync, pts_offset);
2896 qpad->total_duration = next_timestamp;
2897 qtmux->mdat_size += sample_size;
2898 qpad->sample_offset += nsamples;
2904 static GstFlowReturn
2905 gst_qt_mux_start_file (GstQTMux * qtmux)
2907 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2908 GstFlowReturn ret = GST_FLOW_OK;
2912 GstClockTime reserved_max_duration;
2913 guint reserved_bytes_per_sec_per_trak;
2916 GST_DEBUG_OBJECT (qtmux, "starting file");
2918 GST_OBJECT_LOCK (qtmux);
2919 reserved_max_duration = qtmux->reserved_max_duration;
2920 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2921 GST_OBJECT_UNLOCK (qtmux);
2923 /* stream-start (FIXME: create id based on input ids) */
2924 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2925 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2927 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2928 /* qtmux has structure with and without variant, remove all but the first */
2929 while (gst_caps_get_size (caps) > 1)
2930 gst_caps_remove_structure (caps, 1);
2931 gst_pad_set_caps (qtmux->srcpad, caps);
2932 gst_caps_unref (caps);
2934 /* Default is 'normal' mode */
2935 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2937 /* Require a sensible fragment duration when muxing
2938 * using the ISML muxer */
2939 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2940 qtmux->fragment_duration == 0)
2943 if (qtmux->fragment_duration > 0) {
2944 if (qtmux->streamable)
2945 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2947 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2948 } else if (qtmux->fast_start) {
2949 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2950 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2951 if (qtmux->reserved_prefill)
2952 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2954 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2957 switch (qtmux->mux_mode) {
2958 case GST_QT_MUX_MODE_MOOV_AT_END:
2959 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2960 /* We have to be able to seek to rewrite the mdat header, or any
2961 * moov atom we write will not be visible in the file, because an
2962 * MDAT with 0 as the size covers the rest of the file. A file
2963 * with no moov is not playable, so error out now. */
2964 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2965 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2966 ("Downstream is not seekable - will not be able to create a playable file"),
2968 return GST_FLOW_ERROR;
2971 case GST_QT_MUX_MODE_FAST_START:
2972 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2973 break; /* Don't need seekability, ignore */
2974 case GST_QT_MUX_MODE_FRAGMENTED:
2975 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2976 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2977 "streamable=false. Will ignore that and create streamable output "
2979 qtmux->streamable = TRUE;
2980 g_object_notify (G_OBJECT (qtmux), "streamable");
2983 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2984 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2985 GST_WARNING_OBJECT (qtmux,
2986 "downstream is not seekable, will not be able "
2987 "to trim samples table at the end if less than reserved-duration is "
2993 /* let downstream know we think in BYTES and expect to do seeking later on */
2994 gst_segment_init (&segment, GST_FORMAT_BYTES);
2995 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2997 GST_OBJECT_LOCK (qtmux);
2999 if (qtmux->timescale == 0) {
3000 guint32 suggested_timescale = 0;
3003 /* Calculate a reasonable timescale for the moov:
3004 * If there is video, it is the biggest video track timescale or an even
3005 * multiple of it if it's smaller than 1800.
3006 * Otherwise it is 1800 */
3007 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3008 GstCollectData *cdata = (GstCollectData *) walk->data;
3009 GstQTPad *qpad = (GstQTPad *) cdata;
3015 if (!qpad->trak->mdia.minf.vmhd)
3018 suggested_timescale =
3019 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3022 if (suggested_timescale == 0)
3023 suggested_timescale = 1800;
3025 while (suggested_timescale < 1800)
3026 suggested_timescale *= 2;
3028 qtmux->timescale = suggested_timescale;
3031 /* initialize our moov recovery file */
3032 if (qtmux->moov_recov_file_path) {
3033 gst_qt_mux_prepare_moov_recovery (qtmux);
3036 /* Make sure the first time we update the moov, we'll
3037 * include any tagsetter tags */
3038 qtmux->tags_changed = TRUE;
3040 GST_OBJECT_UNLOCK (qtmux);
3043 * send mdat header if already needed, and mark position for later update.
3044 * We don't send ftyp now if we are on fast start mode, because we can
3045 * better fine tune using the information we gather to create the whole moov
3048 switch (qtmux->mux_mode) {
3049 case GST_QT_MUX_MODE_MOOV_AT_END:
3050 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3051 if (ret != GST_FLOW_OK)
3054 /* Store this as the mdat offset for later updating
3055 * when we write the moov */
3056 qtmux->mdat_pos = qtmux->header_size;
3057 /* extended atom in case we go over 4GB while writing and need
3058 * the full 64-bit atom */
3060 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3063 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3064 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3065 if (ret != GST_FLOW_OK)
3068 /* Pad ftyp out to an 8-byte boundary before starting the moov
3069 * ping pong region. It should be well less than 1 disk sector,
3070 * unless there's a bajillion compatible types listed,
3071 * but let's be sure the free atom doesn't cross a sector
3072 * boundary anyway */
3073 if (qtmux->header_size % 8) {
3074 /* Extra 8 bytes for the padding free atom header */
3075 guint padding = (guint) (16 - (qtmux->header_size % 8));
3076 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3078 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3080 if (ret != GST_FLOW_OK)
3084 /* Store this as the moov offset for later updating.
3085 * We record mdat position below */
3086 qtmux->moov_pos = qtmux->header_size;
3088 /* Set up the initial 'ping' state of the ping-pong buffers */
3089 qtmux->reserved_moov_first_active = TRUE;
3091 gst_qt_mux_configure_moov (qtmux);
3092 gst_qt_mux_setup_metadata (qtmux);
3093 /* Empty free atom to begin, starting on an 8-byte boundary */
3094 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3095 if (ret != GST_FLOW_OK)
3097 /* Moov header, not padded yet */
3098 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3099 if (ret != GST_FLOW_OK)
3101 /* The moov we just sent contains the 'base' size of the moov, before
3102 * we put in any time-dependent per-trak data. Use that to make
3103 * a good estimate of how much extra to reserve */
3104 /* Calculate how much space to reserve for our MOOV atom.
3105 * We actually reserve twice that, for ping-pong buffers */
3106 qtmux->base_moov_size = qtmux->last_moov_size;
3107 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3108 qtmux->base_moov_size);
3109 qtmux->reserved_moov_size = qtmux->base_moov_size +
3110 gst_util_uint64_scale (reserved_max_duration,
3111 reserved_bytes_per_sec_per_trak *
3112 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3114 /* Need space for at least 4 atom headers. More really, but
3115 * this as an absolute minimum */
3116 if (qtmux->reserved_moov_size < 4 * 8)
3117 goto reserved_moov_too_small;
3119 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3120 2 * qtmux->reserved_moov_size + 16);
3122 GST_OBJECT_LOCK (qtmux);
3123 qtmux->reserved_duration_remaining =
3124 gst_util_uint64_scale (qtmux->reserved_moov_size -
3125 qtmux->base_moov_size, GST_SECOND,
3126 reserved_bytes_per_sec_per_trak *
3127 atom_moov_get_trak_count (qtmux->moov));
3128 GST_OBJECT_UNLOCK (qtmux);
3130 /* Now that we know how much reserved space is targetted,
3131 * output a free atom to fill the extra reserved */
3132 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3133 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3134 if (ret != GST_FLOW_OK)
3137 /* Then a free atom containing 'pong' buffer, with an
3138 * extra 8 bytes to account for the free atom header itself */
3139 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3140 qtmux->reserved_moov_size + 8, FALSE);
3141 if (ret != GST_FLOW_OK)
3144 /* extra atoms go after the free/moov(s), before the mdat */
3146 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3147 if (ret != GST_FLOW_OK)
3150 qtmux->mdat_pos = qtmux->header_size;
3151 /* extended atom in case we go over 4GB while writing and need
3152 * the full 64-bit atom */
3154 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3157 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3158 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3159 if (ret != GST_FLOW_OK)
3162 /* Store this as the moov offset for later updating.
3163 * We record mdat position below */
3164 qtmux->moov_pos = qtmux->header_size;
3166 if (!gst_qt_mux_prefill_samples (qtmux)) {
3167 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3168 ("Unsupported codecs or configuration for prefill mode"), (NULL));
3170 return GST_FLOW_ERROR;
3173 gst_qt_mux_update_global_statistics (qtmux);
3174 gst_qt_mux_configure_moov (qtmux);
3175 gst_qt_mux_update_edit_lists (qtmux);
3176 gst_qt_mux_setup_metadata (qtmux);
3178 /* Moov header with pre-filled samples */
3179 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3180 if (ret != GST_FLOW_OK)
3183 /* last_moov_size now contains the full size of the moov, moov_pos the
3184 * position. This allows us to rewrite it in the very end as needed */
3185 qtmux->reserved_moov_size =
3186 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3188 /* Send an additional free atom at the end so we definitely have space
3189 * to rewrite the moov header at the end and remove the samples that
3190 * were not actually written */
3192 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3193 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3194 if (ret != GST_FLOW_OK)
3197 /* extra atoms go after the free/moov(s), before the mdat */
3199 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3200 if (ret != GST_FLOW_OK)
3203 qtmux->mdat_pos = qtmux->header_size;
3205 /* And now send the mdat header */
3207 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3208 qtmux->mdat_size, TRUE, FALSE);
3210 /* chunks position is set relative to the first byte of the
3211 * MDAT atom payload. Set the overall offset into the file */
3212 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3217 gst_segment_init (&segment, GST_FORMAT_BYTES);
3218 segment.start = qtmux->moov_pos;
3219 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3221 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3222 if (ret != GST_FLOW_OK)
3225 segment.start = qtmux->header_size;
3226 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3229 qtmux->current_chunk_size = 0;
3230 qtmux->current_chunk_duration = 0;
3231 qtmux->current_chunk_offset = -1;
3232 qtmux->mdat_size = 0;
3233 qtmux->current_pad = NULL;
3234 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3236 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3237 GstCollectData *cdata = (GstCollectData *) walk->data;
3238 GstQTPad *qtpad = (GstQTPad *) cdata;
3240 qtpad->total_bytes = 0;
3241 qtpad->total_duration = 0;
3242 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3243 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3244 qtpad->sample_offset = 0;
3248 case GST_QT_MUX_MODE_FAST_START:
3249 GST_OBJECT_LOCK (qtmux);
3250 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3251 if (!qtmux->fast_start_file)
3253 GST_OBJECT_UNLOCK (qtmux);
3254 /* send a dummy buffer for preroll */
3255 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3257 case GST_QT_MUX_MODE_FRAGMENTED:
3258 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3259 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3260 if (ret != GST_FLOW_OK)
3262 /* store the moov pos so we can update the duration later
3263 * in non-streamable mode */
3264 qtmux->moov_pos = qtmux->header_size;
3266 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3267 qtmux->fragment_duration);
3268 /* also used as snapshot marker to indicate fragmented file */
3269 qtmux->fragment_sequence = 1;
3270 /* prepare moov and/or tags */
3271 gst_qt_mux_configure_moov (qtmux);
3272 gst_qt_mux_setup_metadata (qtmux);
3273 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3274 if (ret != GST_FLOW_OK)
3278 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3279 if (ret != GST_FLOW_OK)
3281 /* prepare index if not streamable */
3282 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3283 qtmux->mfra = atom_mfra_new (qtmux->context);
3291 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3292 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3293 return GST_FLOW_ERROR;
3295 reserved_moov_too_small:
3297 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3298 ("Not enough reserved space for creating headers"), (NULL));
3299 return GST_FLOW_ERROR;
3303 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3304 (("Could not open temporary file \"%s\""),
3305 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3306 GST_OBJECT_UNLOCK (qtmux);
3307 return GST_FLOW_ERROR;
3311 static GstFlowReturn
3312 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3314 GstFlowReturn ret = GST_FLOW_OK;
3317 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3318 GstCollectData *cdata = (GstCollectData *) walk->data;
3319 GstQTPad *qtpad = (GstQTPad *) cdata;
3321 /* avoid add_buffer complaining if not negotiated
3322 * in which case no buffers either, so skipping */
3323 if (!qtpad->fourcc) {
3324 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3325 GST_PAD_NAME (qtpad->collect.pad));
3329 /* send last buffer; also flushes possibly queued buffers/ts */
3330 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3331 GST_PAD_NAME (qtpad->collect.pad));
3332 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3333 if (ret != GST_FLOW_OK) {
3334 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3335 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3336 gst_flow_get_name (ret));
3344 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3348 /* for setting some subtitles fields */
3349 guint max_width = 0;
3350 guint max_height = 0;
3352 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3354 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3355 GstCollectData *cdata = (GstCollectData *) walk->data;
3356 GstQTPad *qtpad = (GstQTPad *) cdata;
3358 if (!qtpad->fourcc) {
3359 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3360 GST_PAD_NAME (qtpad->collect.pad));
3364 /* having flushed above, can check for buffers now */
3365 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3366 GstClockTime first_pts_in = qtpad->first_ts;
3367 /* it should be, since we got first_ts by adding adjustment
3368 * to a positive incoming PTS */
3369 if (qtpad->dts_adjustment <= first_pts_in)
3370 first_pts_in -= qtpad->dts_adjustment;
3371 /* determine max stream duration */
3372 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3373 || qtpad->last_dts > qtmux->last_dts) {
3374 qtmux->last_dts = qtpad->last_dts;
3376 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3377 || first_pts_in < qtmux->first_ts) {
3378 /* we need the original incoming PTS here, as this first_ts
3379 * is used in update_edit_lists to construct the edit list that arrange
3380 * for sync'ed streams. The first_ts is most likely obtained from
3381 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3382 * so it makes no difference, though it matters in other cases */
3383 qtmux->first_ts = first_pts_in;
3387 /* subtitles need to know the video width/height,
3388 * it is stored shifted 16 bits to the left according to the
3390 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3391 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3393 /* update average bitrate of streams if needed */
3395 guint32 avgbitrate = 0;
3396 guint32 maxbitrate = qtpad->max_bitrate;
3398 if (qtpad->avg_bitrate)
3399 avgbitrate = qtpad->avg_bitrate;
3400 else if (qtpad->total_duration > 0)
3401 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3402 8 * GST_SECOND, qtpad->total_duration);
3404 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3408 /* need to update values on subtitle traks now that we know the
3409 * max width and height */
3410 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3411 GstCollectData *cdata = (GstCollectData *) walk->data;
3412 GstQTPad *qtpad = (GstQTPad *) cdata;
3414 if (!qtpad->fourcc) {
3415 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3416 GST_PAD_NAME (qtpad->collect.pad));
3420 if (qtpad->fourcc == FOURCC_tx3g) {
3421 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3426 /* Called after gst_qt_mux_update_global_statistics() updates the
3427 * first_ts tracking, to create/set edit lists for delayed streams */
3429 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3433 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3434 GST_TIME_ARGS (qtmux->first_ts));
3435 /* add/update EDTSs for late streams. configure_moov will have
3436 * set the trak durations above by summing the sample tables,
3437 * here we extend that if needing to insert an empty segment */
3438 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3439 GstCollectData *cdata = (GstCollectData *) walk->data;
3440 GstQTPad *qtpad = (GstQTPad *) cdata;
3442 atom_trak_edts_clear (qtpad->trak);
3444 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3445 guint32 lateness = 0;
3446 guint32 duration = qtpad->trak->tkhd.duration;
3449 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3454 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3455 lateness = gst_util_uint64_scale_round (diff,
3456 qtmux->timescale, GST_SECOND);
3459 GST_DEBUG_OBJECT (qtmux,
3460 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3461 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3463 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3464 (guint32) (1 * 65536.0));
3468 /* Always write an edit list for the whole track. In general this is not
3469 * necessary except for the case of having a gap or DTS adjustment but
3470 * it allows to give the whole track's duration in the usually more
3471 * accurate media timescale
3474 GstClockTime ctts = 0;
3475 guint32 media_start;
3477 if (qtpad->first_ts > qtpad->first_dts)
3478 ctts = qtpad->first_ts - qtpad->first_dts;
3480 media_start = gst_util_uint64_scale_round (ctts,
3481 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3483 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3484 * is empty because there's no gap added above, this call
3485 * will not replace index 1, it will create the entry at index 0.
3486 * Luckily, that's exactly what we want here */
3487 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3488 (guint32) (1 * 65536.0));
3491 /* need to add the empty time to the trak duration */
3492 duration += lateness;
3493 qtpad->trak->tkhd.duration = duration;
3494 if (qtpad->tc_trak) {
3495 qtpad->tc_trak->tkhd.duration = duration;
3496 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3499 /* And possibly grow the moov duration */
3500 if (duration > qtmux->moov->mvhd.time_info.duration) {
3501 qtmux->moov->mvhd.time_info.duration = duration;
3502 qtmux->moov->mvex.mehd.fragment_duration = duration;
3508 static GstFlowReturn
3509 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3514 guint64 offset = qtpad->tc_pos;
3515 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3517 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3520 g_assert (qtpad->tc_pos != -1);
3522 gst_segment_init (&segment, GST_FORMAT_BYTES);
3523 segment.start = offset;
3524 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3526 buf = gst_buffer_new_and_alloc (4);
3527 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3529 GST_WRITE_UINT32_BE (map.data,
3530 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3531 gst_buffer_unmap (buf, &map);
3533 /* Reset this value, so the timecode won't be re-rewritten */
3536 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3539 static GstFlowReturn
3540 gst_qt_mux_stop_file (GstQTMux * qtmux)
3542 gboolean ret = GST_FLOW_OK;
3543 guint64 offset = 0, size = 0;
3544 gboolean large_file;
3547 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3549 /* pushing last buffers for each pad */
3550 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3553 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3554 /* Streamable mode; no need to write duration or MFRA */
3555 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3559 gst_qt_mux_update_global_statistics (qtmux);
3560 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3561 GstQTPad *qtpad = (GstQTPad *) walk->data;
3563 if (qtpad->tc_pos != -1) {
3564 /* File is being stopped and timecode hasn't been updated. Update it now
3565 * with whatever we have */
3566 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3567 if (ret != GST_FLOW_OK)
3572 switch (qtmux->mux_mode) {
3573 case GST_QT_MUX_MODE_FRAGMENTED:{
3575 guint8 *data = NULL;
3579 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3580 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3581 goto serialize_error;
3582 buf = _gst_buffer_new_take_data (data, offset);
3583 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3584 if (ret != GST_FLOW_OK)
3587 /* only mvex duration is updated,
3588 * mvhd should be consistent with empty moov
3589 * (but TODO maybe some clients do not handle that well ?) */
3590 qtmux->moov->mvex.mehd.fragment_duration =
3591 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3592 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3593 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3594 /* seek and rewrite the header */
3595 gst_segment_init (&segment, GST_FORMAT_BYTES);
3596 segment.start = qtmux->moov_pos;
3597 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3598 /* no need to seek back */
3599 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3601 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3602 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3603 if (G_UNLIKELY (ret != GST_FLOW_OK))
3605 /* Finalise by writing the final size into the mdat. Up until now
3606 * it's been 0, which means 'rest of the file'
3607 * No need to seek back after this, we won't write any more */
3608 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3609 qtmux->mdat_size, NULL, TRUE);
3611 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3613 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3615 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3616 GstCollectData *cdata = (GstCollectData *) walk->data;
3617 GstQTPad *qpad = (GstQTPad *) cdata;
3618 const TrakBufferEntryInfo *sample_entry;
3620 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3622 /* Get the block index of the last sample we wrote, not of the next
3623 * sample we would write */
3624 block_idx = prefill_get_block_index (qtmux, qpad);
3625 g_assert (block_idx > 0);
3629 &g_array_index (qpad->samples, TrakBufferEntryInfo, block_idx);
3634 guint64 nsamples = 0;
3637 n = atom_array_get_len (&stbl->stts.entries);
3638 for (i = 0; i < n; i++) {
3639 entry = &atom_array_index (&stbl->stts.entries, i);
3640 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3641 entry->sample_count = qpad->sample_offset - nsamples;
3642 stbl->stts.entries.len = i + 1;
3645 nsamples += entry->sample_count;
3652 g_assert (stbl->stsz.entries.len == 0);
3653 stbl->stsz.table_size = qpad->sample_offset;
3659 guint64 nsamples = 0;
3660 gint chunk_index = 0;
3662 n = stbl->stco64.entries.len;
3663 for (i = 0; i < n; i++) {
3664 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3666 if (*entry == sample_entry->chunk_offset) {
3667 stbl->stco64.entries.len = i + 1;
3668 chunk_index = i + 1;
3673 g_assert (chunk_index > 0);
3675 n = stbl->stsc.entries.len;
3676 for (i = 0; i < n; i++) {
3677 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3679 if (entry->first_chunk >= chunk_index)
3684 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3686 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3687 i - 1).samples_per_chunk;
3693 STSCEntry *prev_entry =
3694 &atom_array_index (&stbl->stsc.entries, i - 1);
3697 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3698 if (qpad->sample_offset - nsamples > 0) {
3699 stbl->stsc.entries.len = i;
3700 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3701 qpad->sample_offset - nsamples);
3703 stbl->stsc.entries.len = i;
3704 stbl->stco64.entries.len--;
3707 /* Everything in a single chunk */
3708 stbl->stsc.entries.len = 0;
3709 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3710 qpad->sample_offset);
3717 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3718 AtomTREX *trex = walk2->data;
3720 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3721 trex->track_ID = next_track_id;
3726 qpad->trak->tkhd.track_ID = next_track_id++;
3729 qtmux->moov->mvhd.next_track_id = next_track_id;
3731 gst_qt_mux_update_global_statistics (qtmux);
3732 gst_qt_mux_configure_moov (qtmux);
3734 gst_qt_mux_update_edit_lists (qtmux);
3736 /* Check if any gap edit lists were added. We don't have any space
3737 * reserved for this in the moov and the pre-finalized moov would have
3738 * broken A/V synchronization. Error out here now
3740 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3741 GstCollectData *cdata = (GstCollectData *) walk->data;
3742 GstQTPad *qpad = (GstQTPad *) cdata;
3744 if (qpad->trak->edts
3745 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3746 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3747 ("Can't support gaps in prefill mode"));
3749 return GST_FLOW_ERROR;
3753 gst_qt_mux_setup_metadata (qtmux);
3754 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3759 gst_segment_init (&segment, GST_FORMAT_BYTES);
3760 segment.start = qtmux->moov_pos;
3761 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3764 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3766 if (ret != GST_FLOW_OK)
3769 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3771 gst_qt_mux_send_free_atom (qtmux, NULL,
3772 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3775 if (ret != GST_FLOW_OK)
3779 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3780 qtmux->mdat_size, NULL, FALSE);
3787 /* Moov-at-end or fast-start mode from here down */
3788 gst_qt_mux_configure_moov (qtmux);
3790 gst_qt_mux_update_edit_lists (qtmux);
3792 /* tags into file metadata */
3793 gst_qt_mux_setup_metadata (qtmux);
3795 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3797 switch (qtmux->mux_mode) {
3798 case GST_QT_MUX_MODE_FAST_START:{
3799 /* if faststart, update the offset of the atoms in the movie with the offset
3800 * that the movie headers before mdat will cause.
3801 * Also, send the ftyp */
3804 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3805 if (ret != GST_FLOW_OK) {
3808 /* copy into NULL to obtain size */
3809 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3810 goto serialize_error;
3811 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3813 offset += qtmux->header_size + (large_file ? 16 : 8);
3815 /* sum up with the extra atoms size */
3816 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3817 if (ret != GST_FLOW_OK)
3822 offset = qtmux->header_size;
3826 /* Now that we know the size of moov + extra atoms, we can adjust
3827 * the chunk offsets stored into the moov */
3828 atom_moov_chunks_set_offset (qtmux->moov, offset);
3830 /* write out moov and extra atoms */
3831 /* note: as of this point, we no longer care about tracking written data size,
3832 * since there is no more use for it anyway */
3833 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3834 if (ret != GST_FLOW_OK)
3838 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3839 if (ret != GST_FLOW_OK)
3842 switch (qtmux->mux_mode) {
3843 case GST_QT_MUX_MODE_MOOV_AT_END:
3845 /* mdat needs update iff not using faststart */
3846 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3847 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3848 qtmux->mdat_size, NULL, FALSE);
3849 /* note; no seeking back to the end of file is done,
3850 * since we no longer write anything anyway */
3853 case GST_QT_MUX_MODE_FAST_START:
3855 /* send mdat atom and move buffered data into it */
3856 /* mdat_size = accumulated (buffered data) */
3857 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3859 if (ret != GST_FLOW_OK)
3861 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3862 if (ret != GST_FLOW_OK)
3867 g_assert_not_reached ();
3875 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3876 ("Failed to serialize moov"));
3877 return GST_FLOW_ERROR;
3881 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3882 return GST_FLOW_ERROR;
3886 static GstFlowReturn
3887 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3888 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3889 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3891 GstFlowReturn ret = GST_FLOW_OK;
3893 /* setup if needed */
3894 if (G_UNLIKELY (!pad->traf || force))
3898 /* flush pad fragment if threshold reached,
3899 * or at new keyframe if we should be minding those in the first place */
3900 if (G_UNLIKELY (force || (sync && pad->sync) ||
3901 pad->fragment_duration < (gint64) delta)) {
3903 guint64 size = 0, offset = 0;
3904 guint8 *data = NULL;
3906 guint i, total_size;
3908 /* now we know where moof ends up, update offset in tfra */
3910 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3912 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3913 /* takes ownership */
3914 atom_moof_add_traf (moof, pad->traf);
3916 atom_moof_copy_data (moof, &data, &size, &offset);
3917 buffer = _gst_buffer_new_take_data (data, offset);
3918 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3919 gst_buffer_get_size (buffer));
3920 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3922 /* and actual data */
3924 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3926 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3929 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3930 atom_array_get_len (&pad->fragment_buffers), total_size);
3931 if (ret == GST_FLOW_OK)
3932 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3934 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3935 if (G_LIKELY (ret == GST_FLOW_OK))
3936 ret = gst_qt_mux_send_buffer (qtmux,
3937 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3940 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3943 atom_array_clear (&pad->fragment_buffers);
3944 atom_moof_free (moof);
3945 qtmux->fragment_sequence++;
3950 if (G_UNLIKELY (!pad->traf)) {
3951 GST_LOG_OBJECT (qtmux, "setting up new fragment");
3952 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3953 atom_array_init (&pad->fragment_buffers, 512);
3954 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3955 atom_trak_get_timescale (pad->trak), 1000);
3957 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3958 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3959 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3961 atom_traf_set_base_decode_time (pad->traf, dts);
3964 /* add buffer and metadata */
3965 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3967 atom_array_append (&pad->fragment_buffers, buf, 256);
3968 pad->fragment_duration -= delta;
3971 guint32 sn = atom_traf_get_sample_num (pad->traf);
3973 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3974 atom_tfra_add_entry (pad->tfra, dts, sn);
3977 if (G_UNLIKELY (force))
3983 /* Here's the clever bit of robust recording: Updating the moov
3984 * header is done using a ping-pong scheme inside 2 blocks of size
3985 * 'reserved_moov_size' at the start of the file, in such a way that the
3986 * file on-disk is always valid if interrupted.
3987 * Inside the reserved space, we have 2 pairs of free + moov atoms
3988 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3989 * at offset "reserved_moov_size".
3991 * 1. Free-A has 0 size payload, moov-A immediately after is
3992 * active/current, and is padded with an internal Free atom to
3993 * end at reserved_space/2. Free-B is at reserved_space/2, sized
3994 * to cover the remaining free space (including moov-B).
3995 * 2. We write moov-B (which is invisible inside free-B), and pad it to
3996 * end at the end of free space. Then, we update free-A to size
3997 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
3998 * free-B header, and makes moov-B active.
3999 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4000 * Change the size of free-A to make moov-A active again.
4001 * 4. Rinse and repeat.
4004 static GstFlowReturn
4005 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4009 guint64 freeA_offset;
4010 guint32 new_freeA_size;
4011 guint64 new_moov_offset;
4013 /* Update moov info, then seek and rewrite the MOOV atom */
4014 gst_qt_mux_update_global_statistics (qtmux);
4015 gst_qt_mux_configure_moov (qtmux);
4017 gst_qt_mux_update_edit_lists (qtmux);
4019 /* tags into file metadata */
4020 gst_qt_mux_setup_metadata (qtmux);
4022 /* chunks position is set relative to the first byte of the
4023 * MDAT atom payload. Set the overall offset into the file */
4024 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4026 /* Calculate which moov to rewrite. qtmux->moov_pos points to
4027 * the start of the free-A header */
4028 freeA_offset = qtmux->moov_pos;
4029 if (qtmux->reserved_moov_first_active) {
4030 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4031 /* After this, freeA will include itself, moovA, plus the freeB
4033 new_freeA_size = qtmux->reserved_moov_size + 16;
4035 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4038 /* the moov we update is after free-A, calculate its offset */
4039 new_moov_offset = freeA_offset + new_freeA_size;
4041 /* Swap ping-pong cadence marker */
4042 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4044 /* seek and rewrite the MOOV atom */
4045 gst_segment_init (&segment, GST_FORMAT_BYTES);
4046 segment.start = new_moov_offset;
4047 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4050 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4052 if (ret != GST_FLOW_OK)
4055 /* Update the estimated recording space remaining, based on amount used so
4056 * far and duration muxed so far */
4057 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4058 GstClockTime remain;
4059 GstClockTime time_muxed = qtmux->last_dts;
4062 gst_util_uint64_scale (qtmux->reserved_moov_size -
4063 qtmux->last_moov_size, time_muxed,
4064 qtmux->last_moov_size - qtmux->base_moov_size);
4065 /* Always under-estimate slightly, so users
4066 * have time to stop muxing before we run out */
4067 if (remain < GST_SECOND / 2)
4070 remain -= GST_SECOND / 2;
4072 GST_INFO_OBJECT (qtmux,
4073 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4074 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4075 qtmux->reserved_moov_size, qtmux->last_moov_size,
4076 GST_TIME_ARGS (qtmux->last_dts),
4077 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4079 GST_OBJECT_LOCK (qtmux);
4080 qtmux->reserved_duration_remaining = remain;
4081 qtmux->muxed_since_last_update = 0;
4082 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4083 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4084 GST_OBJECT_UNLOCK (qtmux);
4088 /* Now update the moov-A size. Don't pass offset, since we don't need
4089 * send_free_atom() to seek for us - all our callers seek back to
4090 * where they need after this, or they don't need it */
4091 gst_segment_init (&segment, GST_FORMAT_BYTES);
4092 segment.start = freeA_offset;
4093 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4095 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4100 static GstFlowReturn
4101 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4104 GstFlowReturn flow_ret;
4106 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4108 GST_OBJECT_LOCK (qtmux);
4110 /* Update the offset of how much we've muxed, so the
4111 * report of remaining space keeps counting down */
4112 if (position > qtmux->last_moov_update &&
4113 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4114 GST_LOG_OBJECT (qtmux,
4115 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4116 qtmux->muxed_since_last_update);
4117 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4120 /* Next, check if we're supposed to send periodic moov updates downstream */
4121 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4122 GST_OBJECT_UNLOCK (qtmux);
4126 /* Update if position is > the threshold or there's been no update yet */
4127 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4128 (position <= qtmux->last_moov_update ||
4129 (position - qtmux->last_moov_update) <
4130 qtmux->reserved_moov_update_period)) {
4131 GST_OBJECT_UNLOCK (qtmux);
4132 return GST_FLOW_OK; /* No update needed yet */
4135 qtmux->last_moov_update = position;
4136 GST_OBJECT_UNLOCK (qtmux);
4138 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4139 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4140 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4142 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4143 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4146 /* Seek back to previous position */
4147 gst_segment_init (&segment, GST_FORMAT_BYTES);
4148 segment.start = mdat_offset;
4149 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4154 static GstFlowReturn
4155 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4156 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4157 gint64 last_dts, gint64 scaled_duration, guint sample_size,
4158 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4160 GstFlowReturn ret = GST_FLOW_OK;
4162 /* note that a new chunk is started each time (not fancy but works) */
4163 if (qtmux->moov_recov_file) {
4164 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4165 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4166 do_pts, pts_offset)) {
4167 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4168 "recovery file, disabling recovery");
4169 fclose (qtmux->moov_recov_file);
4170 qtmux->moov_recov_file = NULL;
4174 switch (qtmux->mux_mode) {
4175 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4176 const TrakBufferEntryInfo *sample_entry;
4177 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4179 if (block_idx >= pad->samples->len) {
4180 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4181 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4182 block_idx, pad->samples->len));
4183 gst_buffer_unref (buffer);
4184 return GST_FLOW_ERROR;
4187 /* Check if all values are as expected */
4189 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4191 /* Allow +/- 1 difference for the scaled_duration to allow
4192 * for some rounding errors
4194 if (sample_entry->nsamples != nsamples
4195 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4196 || sample_entry->size != sample_size
4197 || sample_entry->chunk_offset != chunk_offset
4198 || sample_entry->pts_offset != pts_offset
4199 || sample_entry->sync != sync) {
4200 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4201 ("Unexpected values in sample %" G_GUINT64_FORMAT,
4202 pad->sample_offset + 1));
4203 GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4204 "chunk offset %" G_GUINT64_FORMAT ", "
4205 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4206 sample_entry->nsamples,
4207 sample_entry->delta,
4209 sample_entry->chunk_offset,
4210 sample_entry->pts_offset, sample_entry->sync);
4211 GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4212 "chunk offset %" G_GUINT64_FORMAT ", "
4213 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4215 (guint) scaled_duration,
4216 sample_size, chunk_offset, pts_offset, sync);
4218 gst_buffer_unref (buffer);
4219 return GST_FLOW_ERROR;
4222 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4225 case GST_QT_MUX_MODE_MOOV_AT_END:
4226 case GST_QT_MUX_MODE_FAST_START:
4227 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4228 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4229 sample_size, chunk_offset, sync, pts_offset);
4230 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4231 /* Check if it's time to re-write the headers in robust-recording mode */
4232 if (ret == GST_FLOW_OK
4233 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4234 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4236 case GST_QT_MUX_MODE_FRAGMENTED:
4237 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4238 /* ensure that always sync samples are marked as such */
4239 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4240 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4241 sample_size, !pad->sync || sync, pts_offset);
4249 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4250 guint buffer_size, GstClockTime duration)
4252 /* not that much happens here,
4253 * but updating any of this very likely needs to happen all in sync,
4254 * unless there is a very good reason not to */
4256 /* for computing the avg bitrate */
4257 pad->total_bytes += buffer_size;
4258 pad->total_duration += duration;
4259 /* for keeping track of where we are in chunk;
4260 * ensures that data really is located as recorded in atoms */
4261 qtmux->current_chunk_size += buffer_size;
4262 qtmux->current_chunk_duration += duration;
4265 static GstFlowReturn
4266 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4267 GstBuffer * buf, GstFlowReturn ret)
4269 GstVideoTimeCodeMeta *tc_meta;
4270 GstVideoTimeCode *tc;
4273 guint32 frames_since_daily_jam;
4274 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4276 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4279 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4282 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4288 /* This means we never got a timecode before */
4289 if (pad->first_tc == NULL) {
4290 #ifndef GST_DISABLE_GST_DEBUG
4291 gchar *tc_str = gst_video_time_code_to_string (tc);
4292 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4295 g_assert (pad->tc_trak == NULL);
4296 pad->first_tc = gst_video_time_code_copy (tc);
4297 /* If frames are out of order, the frame we're currently getting might
4298 * not be the first one. Just write a 0 timecode for now and wait
4299 * until we receive a timecode that's lower than the current one */
4300 if (pad->is_out_of_order) {
4301 pad->first_pts = GST_BUFFER_PTS (buf);
4302 frames_since_daily_jam = 0;
4303 /* Position to rewrite */
4304 pad->tc_pos = qtmux->mdat_size;
4306 frames_since_daily_jam =
4307 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4308 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4310 /* Write the timecode trak now */
4311 pad->tc_trak = atom_trak_new (qtmux->context);
4312 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4314 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4315 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4317 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4318 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4320 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4321 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4322 g_assert (szret == 4);
4324 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4325 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4327 /* Need to reset the current chunk (of the previous pad) here because
4328 * some other data was written now above, and the pad has to start a
4330 qtmux->current_chunk_offset = -1;
4331 qtmux->current_chunk_size = 0;
4332 qtmux->current_chunk_duration = 0;
4333 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4334 frames_since_daily_jam =
4335 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4336 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4338 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4339 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4340 g_assert (szret == 4);
4342 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4345 qtmux->current_chunk_offset = -1;
4346 qtmux->current_chunk_size = 0;
4347 qtmux->current_chunk_duration = 0;
4348 } else if (pad->is_out_of_order) {
4349 /* Check for a lower timecode than the one stored */
4350 g_assert (pad->tc_trak != NULL);
4351 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4352 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4353 gst_video_time_code_free (pad->first_tc);
4354 pad->first_tc = gst_video_time_code_copy (tc);
4357 guint64 bk_size = qtmux->mdat_size;
4359 /* If this frame's DTS is after the first PTS received, it means
4360 * we've already received the first frame to be presented. Otherwise
4361 * the decoder would need to go back in time */
4362 gst_qt_mux_update_timecode (qtmux, pad);
4364 /* Reset writing position */
4365 gst_segment_init (&segment, GST_FORMAT_BYTES);
4366 segment.start = bk_size;
4367 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4375 * Here we push the buffer and update the tables in the track atoms
4377 static GstFlowReturn
4378 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4380 GstBuffer *last_buf = NULL;
4381 GstClockTime duration;
4382 guint nsamples, sample_size;
4383 guint64 chunk_offset;
4384 gint64 last_dts, scaled_duration;
4385 gint64 pts_offset = 0;
4386 gboolean sync = FALSE;
4387 GstFlowReturn ret = GST_FLOW_OK;
4391 goto not_negotiated;
4393 /* if this pad has a prepare function, call it */
4394 if (pad->prepare_buf_func != NULL) {
4397 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4398 if (buf && !new_buf)
4403 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4404 if (ret != GST_FLOW_OK) {
4406 gst_buffer_unref (buf);
4410 last_buf = pad->last_buf;
4411 pad->last_buf = buf;
4413 if (last_buf == NULL) {
4414 #ifndef GST_DISABLE_GST_DEBUG
4416 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4417 "received NULL buffer, doing nothing",
4418 GST_PAD_NAME (pad->collect.pad));
4420 GST_LOG_OBJECT (qtmux,
4421 "Pad %s has no previous buffer stored, storing now",
4422 GST_PAD_NAME (pad->collect.pad));
4428 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4431 /* if this is the first buffer, store the timestamp */
4432 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4433 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4434 pad->first_ts = GST_BUFFER_PTS (last_buf);
4435 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4436 pad->first_ts = GST_BUFFER_DTS (last_buf);
4439 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4440 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4441 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4442 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4445 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4446 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4448 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4449 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4450 pad->first_ts = pad->first_dts = 0;
4452 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4453 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4454 GST_TIME_ARGS (pad->first_ts));
4457 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4458 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4459 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4460 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4461 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4462 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4463 pad->last_buf = buf = gst_buffer_make_writable (buf);
4464 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4467 buffer_size = gst_buffer_get_size (last_buf);
4469 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4470 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4471 guint fill_size = required_buffer_size - buffer_size;
4475 if (required_buffer_size < buffer_size) {
4476 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4477 ("Sample size %u bigger than expected maximum %u", buffer_size,
4478 required_buffer_size));
4482 if (fill_size > 0) {
4483 GST_DEBUG_OBJECT (qtmux,
4484 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4485 required_buffer_size);
4486 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4487 gst_memory_map (mem, &map, GST_MAP_WRITE);
4488 memset (map.data, 0, map.size);
4489 gst_memory_unmap (mem, &map);
4490 last_buf = gst_buffer_make_writable (last_buf);
4491 gst_buffer_append_memory (last_buf, mem);
4492 buffer_size = required_buffer_size;
4496 /* duration actually means time delta between samples, so we calculate
4497 * the duration based on the difference in DTS or PTS, falling back
4498 * to DURATION if the other two don't exist, such as with the last
4499 * sample before EOS. Or use 0 if nothing else is available */
4500 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4501 duration = GST_BUFFER_DURATION (last_buf);
4505 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4506 && GST_BUFFER_DTS_IS_VALID (last_buf))
4507 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4508 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4509 && GST_BUFFER_PTS_IS_VALID (last_buf))
4510 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4513 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4514 GST_DEBUG_OBJECT (qtmux,
4515 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4516 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4517 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4518 qtmux->current_chunk_size,
4519 GST_TIME_ARGS (qtmux->current_chunk_duration));
4520 qtmux->current_pad = pad;
4521 if (qtmux->current_chunk_offset == -1)
4522 qtmux->current_chunk_offset = qtmux->mdat_size;
4524 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4525 qtmux->current_chunk_size = 0;
4526 qtmux->current_chunk_duration = 0;
4529 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4530 atom_trak_get_timescale (pad->trak), GST_SECOND);
4532 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4533 if (pad->sample_size && !qtmux->fragment_sequence) {
4534 GstClockTime expected_timestamp;
4536 /* Constant size packets: usually raw audio (with many samples per
4537 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4539 sample_size = pad->sample_size;
4540 if (buffer_size % sample_size != 0)
4541 goto fragmented_sample;
4543 /* note: qt raw audio storage warps it implicitly into a timewise
4544 * perfect stream, discarding buffer times.
4545 * If the difference between the current PTS and the expected one
4546 * becomes too big, we error out: there was a gap and we have no way to
4547 * represent that, causing A/V sync to be off */
4548 expected_timestamp =
4549 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4550 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4551 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4552 expected_timestamp) > qtmux->max_raw_audio_drift)
4553 goto raw_audio_timestamp_drift;
4555 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4556 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4557 atom_trak_get_timescale (pad->trak), GST_SECOND);
4558 duration = GST_BUFFER_DURATION (last_buf);
4560 nsamples = buffer_size / sample_size;
4562 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4563 atom_trak_get_timescale (pad->trak));
4566 /* timescale = samplerate */
4567 scaled_duration = 1;
4569 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4570 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4573 sample_size = buffer_size;
4574 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4575 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4577 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4578 pad->last_dts = GST_BUFFER_DTS (buf);
4580 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4582 if ((gint64) (pad->last_dts) < 0) {
4583 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4584 atom_trak_get_timescale (pad->trak), GST_SECOND);
4586 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4587 atom_trak_get_timescale (pad->trak), GST_SECOND);
4589 scaled_duration = scaled_dts - last_dts;
4590 last_dts = scaled_dts;
4592 /* first convert intended timestamp (in GstClockTime resolution) to
4593 * trak timescale, then derive delta;
4594 * this ensures sums of (scale)delta add up to converted timestamp,
4595 * which only deviates at most 1/scale from timestamp itself */
4596 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4597 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4598 pad->last_dts += duration;
4602 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4604 chunk_offset = qtmux->current_chunk_offset;
4606 GST_LOG_OBJECT (qtmux,
4607 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4608 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4609 GST_LOG_OBJECT (qtmux,
4610 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4611 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4612 nsamples, scaled_duration, sample_size, chunk_offset);
4614 /* might be a sync sample */
4616 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4617 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4618 GST_PAD_NAME (pad->collect.pad));
4622 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4623 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4624 atom_trak_get_timescale (pad->trak), GST_SECOND);
4626 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4627 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4630 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4631 atom_trak_get_timescale (pad->trak), GST_SECOND);
4633 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4634 " timebase_dts: %d pts_offset: %d",
4635 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4636 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4637 (int) (last_dts), (int) (pts_offset));
4639 if (GST_CLOCK_TIME_IS_VALID (duration)
4640 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4641 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4642 GST_DEBUG_OBJECT (qtmux,
4643 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4644 GST_TIME_ARGS (qtmux->current_chunk_duration),
4645 GST_PAD_NAME (pad->collect.pad));
4646 qtmux->longest_chunk = qtmux->current_chunk_duration;
4649 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4650 const TrakBufferEntryInfo *sample_entry;
4651 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4653 if (block_idx >= pad->samples->len) {
4654 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4655 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4656 block_idx, pad->samples->len));
4660 /* Check if all values are as expected */
4662 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4664 if (chunk_offset < sample_entry->chunk_offset) {
4665 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4666 GstBuffer *fill_buf;
4668 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4669 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4671 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4672 if (ret != GST_FLOW_OK)
4674 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4675 qtmux->current_chunk_size = buffer_size;
4676 qtmux->current_chunk_duration = duration;
4677 } else if (chunk_offset != sample_entry->chunk_offset) {
4678 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4679 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4680 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4685 /* now we go and register this buffer/sample all over */
4686 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4687 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4688 chunk_offset, sync, TRUE, pts_offset);
4689 pad->sample_offset += nsamples;
4691 /* if this is sparse and we have a next buffer, check if there is any gap
4692 * between them to insert an empty sample */
4693 if (pad->sparse && buf) {
4694 if (pad->create_empty_buffer) {
4695 GstBuffer *empty_buf;
4696 gint64 empty_duration =
4697 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4698 gint64 empty_duration_scaled;
4701 empty_buf = pad->create_empty_buffer (pad, empty_duration);
4703 pad->last_dts = GST_BUFFER_PTS (buf);
4704 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4705 atom_trak_get_timescale (pad->trak), GST_SECOND)
4706 - (last_dts + scaled_duration);
4707 empty_size = gst_buffer_get_size (empty_buf);
4709 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4713 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4714 last_dts + scaled_duration, empty_duration_scaled,
4715 empty_size, chunk_offset, sync, TRUE, 0);
4716 } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4717 /* This assert is kept here to make sure implementors of new
4718 * sparse input format decide whether there needs to be special
4719 * gap handling or not */
4720 g_assert_not_reached ();
4721 GST_WARNING_OBJECT (qtmux,
4722 "no empty buffer creation function found for pad %s",
4723 GST_PAD_NAME (pad->collect.pad));
4734 gst_buffer_unref (last_buf);
4735 return GST_FLOW_ERROR;
4739 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4740 ("Audio buffer contains fragmented sample."));
4743 raw_audio_timestamp_drift:
4745 /* TODO: Could in theory be implemented with edit lists */
4746 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4747 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4748 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4749 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4750 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4752 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4757 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4762 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4763 ("format wasn't negotiated before buffer flow on pad %s",
4764 GST_PAD_NAME (pad->collect.pad)));
4766 gst_buffer_unref (buf);
4767 return GST_FLOW_NOT_NEGOTIATED;
4772 * DTS running time can be negative. There is no way to represent that in
4773 * MP4 however, thus we need to offset DTS so that it starts from 0.
4776 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4777 GstCollectData * cdata, GstBuffer ** buf)
4782 pts = GST_BUFFER_PTS (*buf);
4783 dts = GST_COLLECT_PADS_DTS (cdata);
4785 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4786 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4787 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4789 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4790 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4791 pad->dts_adjustment = -dts;
4793 pad->dts_adjustment = 0;
4796 if (pad->dts_adjustment > 0) {
4797 *buf = gst_buffer_make_writable (*buf);
4799 dts += pad->dts_adjustment;
4801 if (GST_CLOCK_TIME_IS_VALID (pts))
4802 pts += pad->dts_adjustment;
4804 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4805 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4810 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4814 GST_BUFFER_PTS (*buf) = pts;
4815 GST_BUFFER_DTS (*buf) = dts;
4817 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4818 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4823 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4826 GstQTPad *best_pad = NULL;
4828 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4829 guint64 smallest_offset = G_MAXUINT64;
4830 guint64 chunk_offset = 0;
4832 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4833 GstCollectData *cdata = (GstCollectData *) walk->data;
4834 GstQTPad *qtpad = (GstQTPad *) cdata;
4835 const TrakBufferEntryInfo *sample_entry;
4836 guint64 block_idx, current_block_idx;
4837 guint64 chunk_offset_offset = 0;
4838 GstBuffer *tmp_buf =
4839 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4841 /* Check for EOS pads and just skip them */
4842 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4843 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4846 gst_buffer_unref (tmp_buf);
4848 /* Find the exact offset where the next sample of this track is supposed
4849 * to be written at */
4850 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4852 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4853 while (block_idx > 0) {
4854 const TrakBufferEntryInfo *tmp =
4855 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4857 if (tmp->chunk_offset != sample_entry->chunk_offset)
4859 chunk_offset_offset += tmp->size * tmp->nsamples;
4863 /* Except for the previously selected pad being EOS we always have
4864 * qtmux->current_chunk_offset + qtmux->current_chunk_size
4866 * sample_entry->chunk_offset + chunk_offset_offset
4867 * for the best pad. Instead of checking that, we just return the
4868 * pad that has the smallest offset for the next to-be-written sample.
4870 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4871 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4873 chunk_offset = sample_entry->chunk_offset;
4877 if (chunk_offset != qtmux->current_chunk_offset) {
4878 qtmux->current_pad = NULL;
4884 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4885 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4886 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4887 && (qtmux->interleave_time == 0
4888 || qtmux->current_chunk_duration <= qtmux->interleave_time)
4889 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4890 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4891 GstBuffer *tmp_buf =
4892 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4894 if (tmp_buf || qtmux->current_pad->last_buf) {
4895 best_pad = qtmux->current_pad;
4897 gst_buffer_unref (tmp_buf);
4898 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4899 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4901 } else if (qtmux->collect->data->next) {
4902 /* Only switch pads if we have more than one, otherwise
4903 * we can just put everything into a single chunk and save
4904 * a few bytes of offsets
4906 if (qtmux->current_pad)
4907 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4908 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4909 best_pad = qtmux->current_pad = NULL;
4913 GstClockTime best_time = GST_CLOCK_TIME_NONE;
4915 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4916 GstCollectData *cdata = (GstCollectData *) walk->data;
4917 GstQTPad *qtpad = (GstQTPad *) cdata;
4919 GstClockTime timestamp;
4921 tmp_buf = gst_collect_pads_peek (pads, cdata);
4923 /* This one is newly EOS now, finish it for real */
4924 if (qtpad->last_buf) {
4925 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4930 if (qtpad->last_buf)
4931 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4933 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4936 if (best_pad == NULL ||
4937 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4939 best_time = timestamp;
4943 gst_buffer_unref (tmp_buf);
4947 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4948 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4950 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4957 static GstFlowReturn
4958 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4960 GstFlowReturn ret = GST_FLOW_OK;
4961 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4962 GstQTPad *best_pad = NULL;
4964 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4965 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4968 qtmux->state = GST_QT_MUX_STATE_DATA;
4971 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4972 return GST_FLOW_EOS;
4974 best_pad = find_best_pad (qtmux, pads);
4976 /* clipping already converted to running time */
4977 if (best_pad != NULL) {
4978 GstBuffer *buf = NULL;
4980 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4981 best_pad->raw_audio_adapter == NULL ||
4982 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4983 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4985 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4986 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4989 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
4990 (GstCollectData *) best_pad, &buf);
4992 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
4994 qtmux->state = GST_QT_MUX_STATE_EOS;
4995 ret = gst_qt_mux_stop_file (qtmux);
4996 if (ret == GST_FLOW_OK) {
4997 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
4998 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5001 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5002 gst_flow_get_name (ret));
5010 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5012 GstStructure *structure = (GstStructure *) user_data;
5013 const GValue *other = gst_structure_id_get_value (structure, field_id);
5016 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5020 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5023 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5024 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5026 return gst_structure_foreach (sub_s, check_field, sup_s);
5029 /* will unref @qtmux */
5031 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5033 GstCaps *current_caps;
5035 /* does not go well to renegotiate stream mid-way, unless
5036 * the old caps are a subset of the new one (this means upstream
5037 * added more info to the caps, as both should be 'fixed' caps) */
5038 current_caps = gst_pad_get_current_caps (pad);
5039 g_assert (caps != NULL);
5041 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5042 gst_caps_unref (current_caps);
5043 GST_WARNING_OBJECT (qtmux,
5044 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5045 GST_PAD_NAME (pad), caps);
5046 gst_object_unref (qtmux);
5050 GST_DEBUG_OBJECT (qtmux,
5051 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5052 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5053 gst_object_unref (qtmux);
5054 gst_caps_unref (current_caps);
5060 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5062 GstPad *pad = qtpad->collect.pad;
5063 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5064 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5065 GstStructure *structure;
5066 const gchar *mimetype;
5067 gint rate, channels;
5068 const GValue *value = NULL;
5069 const GstBuffer *codec_data = NULL;
5070 GstQTMuxFormat format;
5071 AudioSampleEntry entry = { 0, };
5072 AtomInfo *ext_atom = NULL;
5073 gint constant_size = 0;
5074 const gchar *stream_format;
5078 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5080 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5081 GST_DEBUG_PAD_NAME (pad), caps);
5083 qtpad->prepare_buf_func = NULL;
5085 format = qtmux_klass->format;
5086 structure = gst_caps_get_structure (caps, 0);
5087 mimetype = gst_structure_get_name (structure);
5090 if (!gst_structure_get_int (structure, "channels", &channels) ||
5091 !gst_structure_get_int (structure, "rate", &rate)) {
5096 value = gst_structure_get_value (structure, "codec_data");
5098 codec_data = gst_value_get_buffer (value);
5100 qtpad->is_out_of_order = FALSE;
5102 /* set common properties */
5103 entry.sample_rate = rate;
5104 entry.channels = channels;
5106 entry.sample_size = 16;
5107 /* this is the typical compressed case */
5108 if (format == GST_QT_MUX_FORMAT_QT) {
5110 entry.compression_id = -2;
5113 /* now map onto a fourcc, and some extra properties */
5114 if (strcmp (mimetype, "audio/mpeg") == 0) {
5115 gint mpegversion = 0, mpegaudioversion = 0;
5118 gst_structure_get_int (structure, "mpegversion", &mpegversion);
5119 switch (mpegversion) {
5121 gst_structure_get_int (structure, "layer", &layer);
5122 gst_structure_get_int (structure, "mpegaudioversion",
5126 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5127 if (format == GST_QT_MUX_FORMAT_QT)
5128 entry.fourcc = FOURCC__mp3;
5130 entry.fourcc = FOURCC_mp4a;
5132 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5133 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5134 qtpad->max_bitrate);
5137 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5138 || format == GST_QT_MUX_FORMAT_QT);
5139 entry.samples_per_packet = 384;
5140 } else if (layer == 2) {
5141 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5142 || format == GST_QT_MUX_FORMAT_QT);
5143 entry.samples_per_packet = 1152;
5145 g_warn_if_fail (layer == 3);
5146 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5148 entry.bytes_per_sample = 2;
5152 /* check stream-format */
5153 stream_format = gst_structure_get_string (structure, "stream-format");
5154 if (stream_format) {
5155 if (strcmp (stream_format, "raw") != 0) {
5156 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5157 "please use 'raw'", stream_format);
5161 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5165 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5166 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5171 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5172 /* warn if not Low Complexity profile */
5175 GST_WARNING_OBJECT (qtmux,
5176 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5180 entry.fourcc = FOURCC_mp4a;
5182 if (format == GST_QT_MUX_FORMAT_QT)
5183 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5184 qtpad->avg_bitrate, qtpad->max_bitrate);
5187 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5188 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5189 qtpad->max_bitrate);
5194 } else if (strcmp (mimetype, "audio/AMR") == 0) {
5195 entry.fourcc = FOURCC_samr;
5196 entry.sample_size = 16;
5197 entry.samples_per_packet = 160;
5198 entry.bytes_per_sample = 2;
5199 ext_atom = build_amr_extension ();
5200 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5201 entry.fourcc = FOURCC_sawb;
5202 entry.sample_size = 16;
5203 entry.samples_per_packet = 320;
5204 entry.bytes_per_sample = 2;
5205 ext_atom = build_amr_extension ();
5206 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5209 gst_audio_info_init (&info);
5210 if (!gst_audio_info_from_caps (&info, caps))
5213 /* spec has no place for a distinction in these */
5214 if (info.finfo->width != info.finfo->depth) {
5215 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5219 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5220 if (info.finfo->endianness == G_LITTLE_ENDIAN)
5221 entry.fourcc = FOURCC_sowt;
5222 else if (info.finfo->endianness == G_BIG_ENDIAN)
5223 entry.fourcc = FOURCC_twos;
5225 entry.fourcc = FOURCC_sowt;
5226 /* maximum backward compatibility; only new version for > 16 bit */
5227 if (info.finfo->depth <= 16)
5229 /* not compressed in any case */
5230 entry.compression_id = 0;
5231 /* QT spec says: max at 16 bit even if sample size were actually larger,
5232 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5233 entry.sample_size = info.finfo->depth;
5234 entry.bytes_per_sample = info.finfo->depth / 8;
5235 entry.samples_per_packet = 1;
5236 entry.bytes_per_packet = info.finfo->depth / 8;
5237 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5239 if (info.finfo->width == 8 && info.finfo->depth == 8) {
5240 /* fall back to old 8-bit version */
5241 entry.fourcc = FOURCC_raw_;
5243 entry.compression_id = 0;
5244 entry.sample_size = 8;
5246 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5250 constant_size = (info.finfo->depth / 8) * info.channels;
5251 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5252 entry.fourcc = FOURCC_alaw;
5253 entry.samples_per_packet = 1023;
5254 entry.bytes_per_sample = 2;
5255 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5256 entry.fourcc = FOURCC_ulaw;
5257 entry.samples_per_packet = 1023;
5258 entry.bytes_per_sample = 2;
5259 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5261 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5262 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5265 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5267 entry.fourcc = MS_WAVE_FOURCC (0x11);
5268 /* 4 byte header per channel (including one sample). 2 samples per byte
5269 remaining. Simplifying gives the following (samples per block per
5271 entry.samples_per_packet = 2 * blocksize / channels - 7;
5272 entry.bytes_per_sample = 2;
5274 entry.bytes_per_frame = blocksize;
5275 entry.bytes_per_packet = blocksize / channels;
5276 /* ADPCM has constant size packets */
5278 /* TODO: I don't really understand why this helps, but it does! Constant
5279 * size and compression_id of -2 seem to be incompatible, and other files
5280 * in the wild use this too. */
5281 entry.compression_id = -1;
5283 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5284 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5285 GstBuffer *codec_config;
5289 entry.fourcc = FOURCC_alac;
5290 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5291 /* let's check if codec data already comes with 'alac' atom prefix */
5292 if (!codec_data || (len = map.size) < 28) {
5293 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5294 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5297 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5300 gst_buffer_copy_region ((GstBuffer *) codec_data,
5301 GST_BUFFER_COPY_MEMORY, 8, len);
5303 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5305 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5307 /* does not look good, but perhaps some trailing unneeded stuff */
5308 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5310 if (format == GST_QT_MUX_FORMAT_QT)
5311 ext_atom = build_mov_alac_extension (codec_config);
5313 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5314 /* set some more info */
5315 gst_buffer_map (codec_config, &map, GST_MAP_READ);
5316 entry.bytes_per_sample = 2;
5317 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5318 gst_buffer_unmap (codec_config, &map);
5319 gst_buffer_unref (codec_config);
5320 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5321 entry.fourcc = FOURCC_ac_3;
5323 /* Fixed values according to TS 102 366 but it also mentions that
5324 * they should be ignored */
5326 entry.sample_size = 16;
5328 /* AC-3 needs an extension atom but its data can only be obtained from
5329 * the stream itself. Abuse the prepare_buf_func so we parse a frame
5330 * and get the needed data */
5331 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5332 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5333 /* Based on the specification defined in:
5334 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5335 guint8 channels, mapping_family, stream_count, coupled_count;
5339 guint8 channel_mapping[256];
5340 const GValue *streamheader;
5341 const GValue *first_element;
5344 entry.fourcc = FOURCC_opus;
5345 entry.sample_size = 16;
5347 streamheader = gst_structure_get_value (structure, "streamheader");
5348 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5349 gst_value_array_get_size (streamheader) != 0) {
5350 first_element = gst_value_array_get_value (streamheader, 0);
5351 header = gst_value_get_buffer (first_element);
5352 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5353 &mapping_family, &stream_count, &coupled_count, channel_mapping,
5354 &pre_skip, &output_gain)) {
5355 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5359 GST_WARNING_OBJECT (qtmux,
5360 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5362 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5363 &mapping_family, &stream_count, &coupled_count,
5365 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5372 entry.channels = channels;
5373 ext_atom = build_opus_extension (rate, channels, mapping_family,
5374 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5380 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5381 if (!timescale && qtmux->trak_timescale)
5382 timescale = qtmux->trak_timescale;
5383 else if (!timescale)
5384 timescale = entry.sample_rate;
5386 /* ok, set the pad info accordingly */
5387 qtpad->fourcc = entry.fourcc;
5388 qtpad->sample_size = constant_size;
5390 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5391 qtmux->context, &entry, timescale, ext_atom, constant_size);
5393 gst_object_unref (qtmux);
5399 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5400 GST_PAD_NAME (pad), caps);
5401 gst_object_unref (qtmux);
5407 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5409 GstPad *pad = qtpad->collect.pad;
5410 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5411 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5412 GstStructure *structure;
5413 const gchar *mimetype;
5414 gint width, height, depth = -1;
5415 gint framerate_num, framerate_den;
5417 const GValue *value = NULL;
5418 const GstBuffer *codec_data = NULL;
5419 VisualSampleEntry entry = { 0, };
5420 GstQTMuxFormat format;
5421 AtomInfo *ext_atom = NULL;
5422 GList *ext_atom_list = NULL;
5423 gboolean sync = FALSE;
5424 int par_num, par_den;
5425 const gchar *multiview_mode;
5428 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5430 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5431 GST_DEBUG_PAD_NAME (pad), caps);
5433 qtpad->prepare_buf_func = NULL;
5435 format = qtmux_klass->format;
5436 structure = gst_caps_get_structure (caps, 0);
5437 mimetype = gst_structure_get_name (structure);
5439 /* required parts */
5440 if (!gst_structure_get_int (structure, "width", &width) ||
5441 !gst_structure_get_int (structure, "height", &height))
5446 /* works as a default timebase */
5447 framerate_num = 10000;
5449 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5451 gst_structure_get_int (structure, "depth", &depth);
5452 value = gst_structure_get_value (structure, "codec_data");
5454 codec_data = gst_value_get_buffer (value);
5458 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5461 qtpad->is_out_of_order = FALSE;
5463 /* bring frame numerator into a range that ensures both reasonable resolution
5464 * as well as a fair duration */
5465 qtpad->expected_sample_duration_n = framerate_num;
5466 qtpad->expected_sample_duration_d = framerate_den;
5468 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5469 if (!rate && qtmux->trak_timescale)
5470 rate = qtmux->trak_timescale;
5472 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5474 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5477 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5478 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5479 GstVideoMultiviewMode mode;
5480 GstVideoMultiviewFlags flags = 0;
5482 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5483 gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5485 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5486 qtpad->trak->mdia.minf.stbl.svmi =
5488 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5490 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5491 qtpad->trak->mdia.minf.stbl.svmi =
5493 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5495 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5496 qtpad->trak->mdia.minf.stbl.svmi =
5498 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5501 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5507 /* set common properties */
5508 entry.width = width;
5509 entry.height = height;
5510 entry.par_n = par_num;
5511 entry.par_d = par_den;
5512 /* should be OK according to qt and iso spec, override if really needed */
5513 entry.color_table_id = -1;
5514 entry.frame_count = 1;
5517 /* sync entries by default */
5520 /* now map onto a fourcc, and some extra properties */
5521 if (strcmp (mimetype, "video/x-raw") == 0) {
5522 const gchar *format;
5524 const GstVideoFormatInfo *vinfo;
5526 format = gst_structure_get_string (structure, "format");
5527 fmt = gst_video_format_from_string (format);
5528 vinfo = gst_video_format_get_info (fmt);
5531 case GST_VIDEO_FORMAT_UYVY:
5534 entry.fourcc = FOURCC_2vuy;
5535 entry.depth = depth;
5538 case GST_VIDEO_FORMAT_v210:
5541 entry.fourcc = FOURCC_v210;
5542 entry.depth = depth;
5546 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5547 entry.fourcc = FOURCC_raw_;
5548 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5553 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5555 if (format == GST_QT_MUX_FORMAT_QT)
5556 entry.fourcc = FOURCC_h263;
5558 entry.fourcc = FOURCC_s263;
5559 ext_atom = build_h263_extension ();
5560 if (ext_atom != NULL)
5561 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5562 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5563 strcmp (mimetype, "video/mpeg") == 0) {
5566 if (strcmp (mimetype, "video/x-divx") == 0) {
5567 gst_structure_get_int (structure, "divxversion", &version);
5568 version = version == 5 ? 1 : 0;
5570 gst_structure_get_int (structure, "mpegversion", &version);
5571 version = version == 4 ? 1 : 0;
5574 entry.fourcc = FOURCC_mp4v;
5576 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5577 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5578 qtpad->max_bitrate);
5579 if (ext_atom != NULL)
5580 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5582 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5583 "output might not play in Apple QuickTime (try global-headers?)");
5585 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5587 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5591 entry.fourcc = FOURCC_avc1;
5593 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5594 if (ext_atom != NULL)
5595 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5596 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5597 if (ext_atom != NULL)
5598 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5599 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5600 const gchar *format;
5603 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5607 format = gst_structure_get_string (structure, "stream-format");
5608 if (strcmp (format, "hvc1") == 0)
5609 entry.fourcc = FOURCC_hvc1;
5610 else if (strcmp (format, "hev1") == 0)
5611 entry.fourcc = FOURCC_hev1;
5613 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5614 if (ext_atom != NULL)
5615 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5617 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5618 if (ext_atom != NULL)
5619 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5621 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5623 const GstBuffer *seqh = NULL;
5624 const GValue *seqh_value;
5627 gst_structure_get_int (structure, "svqversion", &version);
5629 entry.fourcc = FOURCC_SVQ3;
5633 seqh_value = gst_structure_get_value (structure, "seqh");
5635 seqh = gst_value_get_buffer (seqh_value);
5636 ext_atom = build_SMI_atom (seqh);
5638 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5641 /* we need to add the gamma anyway because quicktime might crash
5642 * when it doesn't find it */
5643 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5644 /* it seems that using 0 here makes it ignored */
5647 ext_atom = build_gama_atom (gamma);
5649 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5651 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5652 "a bug at http://bugzilla.gnome.org", version);
5654 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5656 gboolean pal = TRUE;
5659 if (framerate_num != 25 || framerate_den != 1)
5661 gst_structure_get_int (structure, "dvversion", &version);
5662 /* fall back to typical one */
5668 entry.fourcc = FOURCC_dvcp;
5670 entry.fourcc = FOURCC_dvc_;
5674 entry.fourcc = FOURCC_dv5p;
5676 entry.fourcc = FOURCC_dv5n;
5679 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5682 } else if (strcmp (mimetype, "image/jpeg") == 0) {
5683 entry.fourcc = FOURCC_jpeg;
5685 } else if (strcmp (mimetype, "image/png") == 0) {
5686 entry.fourcc = FOURCC_png;
5688 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5689 strcmp (mimetype, "image/x-jpc") == 0) {
5690 const gchar *colorspace;
5691 const GValue *cmap_array;
5692 const GValue *cdef_array;
5695 if (strcmp (mimetype, "image/x-jpc") == 0) {
5696 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5699 gst_structure_get_int (structure, "num-components", &ncomp);
5700 cmap_array = gst_structure_get_value (structure, "component-map");
5701 cdef_array = gst_structure_get_value (structure, "channel-definitions");
5704 entry.fourcc = FOURCC_mjp2;
5707 colorspace = gst_structure_get_string (structure, "colorspace");
5710 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5711 cdef_array)) != NULL) {
5712 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5714 ext_atom = build_jp2x_extension (codec_data);
5716 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5718 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5721 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5722 entry.fourcc = FOURCC_vp08;
5723 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5724 entry.fourcc = FOURCC_vp09;
5725 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5726 entry.fourcc = FOURCC_drac;
5727 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5730 gst_structure_get_uint (structure, "format", &fourcc);
5731 entry.fourcc = fourcc;
5732 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5735 gst_structure_get_uint (structure, "format", &fourcc);
5736 entry.fourcc = fourcc;
5737 } else if (strcmp (mimetype, "video/x-prores") == 0) {
5738 const gchar *variant;
5740 variant = gst_structure_get_string (structure, "variant");
5741 if (!variant || !g_strcmp0 (variant, "standard"))
5742 entry.fourcc = FOURCC_apcn;
5743 else if (!g_strcmp0 (variant, "lt"))
5744 entry.fourcc = FOURCC_apcs;
5745 else if (!g_strcmp0 (variant, "hq"))
5746 entry.fourcc = FOURCC_apch;
5747 else if (!g_strcmp0 (variant, "proxy"))
5748 entry.fourcc = FOURCC_apco;
5749 else if (!g_strcmp0 (variant, "4444"))
5750 entry.fourcc = FOURCC_ap4h;
5751 else if (!g_strcmp0 (variant, "4444xq"))
5752 entry.fourcc = FOURCC_ap4x;
5756 if (!qtmux->interleave_time_set)
5757 qtmux->interleave_time = 500 * GST_MSECOND;
5758 if (!qtmux->interleave_bytes_set)
5759 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5760 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5761 entry.fourcc = FOURCC_cfhd;
5768 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5769 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5771 GstVideoColorimetry colorimetry;
5773 s = gst_structure_get_string (structure, "colorimetry");
5774 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5776 build_colr_extension (&colorimetry,
5777 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5779 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5783 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5784 || strcmp (mimetype, "image/x-j2c") == 0
5785 || strcmp (mimetype, "image/x-jpc") == 0) {
5787 GstVideoInterlaceMode interlace_mode;
5788 GstVideoFieldOrder field_order;
5791 if (strcmp (mimetype, "image/x-j2c") == 0 ||
5792 strcmp (mimetype, "image/x-jpc") == 0) {
5795 gst_structure_get_int (structure, "fields", &fields);
5798 s = gst_structure_get_string (structure, "interlace-mode");
5800 interlace_mode = gst_video_interlace_mode_from_string (s);
5804 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5805 GST_VIDEO_INTERLACE_MODE_MIXED;
5807 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5808 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5809 s = gst_structure_get_string (structure, "field-order");
5811 field_order = gst_video_field_order_from_string (s);
5814 ext_atom = build_fiel_extension (interlace_mode, field_order);
5816 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5820 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5821 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5822 /* The 'clap' extension is also defined for MP4 but inventing values in
5823 * general seems a bit tricky for this one. We only write it for
5824 * SD resolution in MOV, where it is a requirement.
5825 * The same goes for the 'tapt' extension, just that it is not defined for
5826 * MP4 and only for MOV
5828 gint dar_num, dar_den;
5829 gint clef_width, clef_height, prof_width;
5830 gint clap_width_n, clap_width_d, clap_height;
5834 /* First, guess display aspect ratio based on pixel aspect ratio,
5835 * width and height. We assume that display aspect ratio is either
5838 approx_dar = (gdouble) (width * par_num) / (height * par_den);
5839 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5842 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5846 dar_num = width * par_num;
5847 dar_den = height * par_den;
5848 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5853 /* Then, calculate clean-aperture values (clap and clef)
5854 * using the guessed DAR.
5856 clef_height = clap_height = (height == 486 ? 480 : height);
5857 clef_width = gst_util_uint64_scale (clef_height,
5858 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5859 prof_width = gst_util_uint64_scale (width,
5860 par_num * G_GUINT64_CONSTANT (65536), par_den);
5861 clap_width_n = clap_height * dar_num * par_den;
5862 clap_width_d = dar_den * par_num;
5863 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5864 clap_width_n /= cdiv;
5865 clap_width_d /= cdiv;
5867 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5868 height << 16, width << 16, height << 16);
5869 qtpad->trak->tapt = ext_atom;
5871 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5872 clap_height, 1, 0, 1, 0, 1);
5874 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5877 /* ok, set the pad info accordingly */
5878 qtpad->fourcc = entry.fourcc;
5881 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5882 qtmux->context, &entry, rate, ext_atom_list);
5883 if (strcmp (mimetype, "video/x-prores") == 0) {
5884 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5885 const gchar *compressor = NULL;
5886 mp4v->spatial_quality = 0x3FF;
5887 mp4v->temporal_quality = 0;
5888 mp4v->vendor = FOURCC_appl;
5889 mp4v->horizontal_resolution = 72 << 16;
5890 mp4v->vertical_resolution = 72 << 16;
5891 mp4v->depth = (entry.fourcc == FOURCC_ap4h
5892 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5894 /* Set compressor name, required by some software */
5895 switch (entry.fourcc) {
5897 compressor = "Apple ProRes 422";
5900 compressor = "Apple ProRes 422 LT";
5903 compressor = "Apple ProRes 422 HQ";
5906 compressor = "Apple ProRes 422 Proxy";
5909 compressor = "Apple ProRes 4444";
5912 compressor = "Apple ProRes 4444 XQ";
5916 strcpy ((gchar *) mp4v->compressor + 1, compressor);
5917 mp4v->compressor[0] = strlen (compressor);
5921 gst_object_unref (qtmux);
5927 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5928 GST_PAD_NAME (pad), caps);
5929 gst_object_unref (qtmux);
5935 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5937 GstPad *pad = qtpad->collect.pad;
5938 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5939 GstStructure *structure;
5940 SubtitleSampleEntry entry = { 0, };
5943 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5945 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5946 GST_DEBUG_PAD_NAME (pad), caps);
5948 /* subtitles default */
5949 subtitle_sample_entry_init (&entry);
5950 qtpad->is_out_of_order = FALSE;
5951 qtpad->sync = FALSE;
5952 qtpad->sparse = TRUE;
5953 qtpad->prepare_buf_func = NULL;
5955 structure = gst_caps_get_structure (caps, 0);
5957 if (gst_structure_has_name (structure, "text/x-raw")) {
5958 const gchar *format = gst_structure_get_string (structure, "format");
5959 if (format && strcmp (format, "utf8") == 0) {
5960 entry.fourcc = FOURCC_tx3g;
5961 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
5962 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
5969 qtpad->fourcc = entry.fourcc;
5971 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
5972 qtmux->context, &entry);
5974 gst_object_unref (qtmux);
5980 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5981 GST_PAD_NAME (pad), caps);
5982 gst_object_unref (qtmux);
5988 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5990 GstPad *pad = qtpad->collect.pad;
5991 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5992 GstStructure *structure;
5993 guint32 fourcc_entry;
5997 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5999 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6000 GST_DEBUG_PAD_NAME (pad), caps);
6002 /* captions default */
6003 qtpad->is_out_of_order = FALSE;
6004 qtpad->sync = FALSE;
6005 qtpad->sparse = TRUE;
6006 /* Closed caption data are within atoms */
6007 qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6009 structure = gst_caps_get_structure (caps, 0);
6011 /* We know we only handle 608,format=cc_data and 708,format=cdp */
6012 if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6013 fourcc_entry = FOURCC_c608;
6014 } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6015 fourcc_entry = FOURCC_c708;
6019 /* FIXME: Get the timescale from the video track ? */
6020 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6021 if (!timescale && qtmux->trak_timescale)
6022 timescale = qtmux->trak_timescale;
6023 else if (!timescale)
6026 qtpad->fourcc = fourcc_entry;
6028 (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6029 qtmux->context, timescale, fourcc_entry);
6031 gst_object_unref (qtmux);
6037 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6038 GST_PAD_NAME (pad), caps);
6039 gst_object_unref (qtmux);
6045 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6046 GstEvent * event, gpointer user_data)
6049 guint32 avg_bitrate = 0, max_bitrate = 0;
6050 GstPad *pad = data->pad;
6051 gboolean ret = TRUE;
6053 qtmux = GST_QT_MUX_CAST (user_data);
6054 switch (GST_EVENT_TYPE (event)) {
6055 case GST_EVENT_CAPS:
6058 GstQTPad *collect_pad;
6060 gst_event_parse_caps (event, &caps);
6062 /* find stream data */
6063 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6064 g_assert (collect_pad);
6065 g_assert (collect_pad->set_caps);
6067 ret = collect_pad->set_caps (collect_pad, caps);
6068 gst_event_unref (event);
6072 case GST_EVENT_TAG:{
6074 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6075 GstTagMergeMode mode;
6077 GstQTPad *collect_pad;
6079 GST_OBJECT_LOCK (qtmux);
6080 mode = gst_tag_setter_get_tag_merge_mode (setter);
6081 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6083 gst_event_parse_tag (event, &list);
6084 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6085 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6087 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6088 gst_tag_setter_merge_tags (setter, list, mode);
6089 qtmux->tags_changed = TRUE;
6091 if (!collect_pad->tags)
6092 collect_pad->tags = gst_tag_list_new_empty ();
6093 gst_tag_list_insert (collect_pad->tags, list, mode);
6094 collect_pad->tags_changed = TRUE;
6096 GST_OBJECT_UNLOCK (qtmux);
6098 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6099 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6100 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6103 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6104 qtpad->avg_bitrate = avg_bitrate;
6105 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6106 qtpad->max_bitrate = max_bitrate;
6109 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6110 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6112 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6115 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6116 qtpad->trak->mdia.mdhd.language_code =
6117 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
6118 (iso_code[2] - 0x60);
6124 gst_event_unref (event);
6134 return gst_collect_pads_event_default (pads, data, event, FALSE);
6140 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6142 GstQTMux *mux = GST_QT_MUX_CAST (element);
6145 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6147 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6148 GstQTPad *qtpad = (GstQTPad *) walk->data;
6149 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6150 if (qtpad->collect.pad == pad) {
6151 /* this is it, remove */
6152 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6153 gst_element_remove_pad (element, pad);
6158 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6159 mux->current_pad = NULL;
6160 mux->current_chunk_size = 0;
6161 mux->current_chunk_duration = 0;
6164 gst_collect_pads_remove_pad (mux->collect, pad);
6166 if (mux->sinkpads == NULL) {
6167 /* No more outstanding request pads, reset our counters */
6168 mux->video_pads = 0;
6169 mux->audio_pads = 0;
6170 mux->subtitle_pads = 0;
6175 gst_qt_mux_request_new_pad (GstElement * element,
6176 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6178 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6179 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6180 GstQTPad *collect_pad;
6182 GstQTPadSetCapsFunc setcaps_func;
6185 gboolean lock = TRUE;
6187 if (templ->direction != GST_PAD_SINK)
6188 goto wrong_direction;
6190 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6193 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6194 setcaps_func = gst_qt_mux_audio_sink_set_caps;
6195 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6196 name = g_strdup (req_name);
6198 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6200 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6201 setcaps_func = gst_qt_mux_video_sink_set_caps;
6202 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6203 name = g_strdup (req_name);
6205 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6207 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6208 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6209 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6210 name = g_strdup (req_name);
6212 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6215 } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6216 setcaps_func = gst_qt_mux_caption_sink_set_caps;
6217 if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6218 name = g_strdup (req_name);
6220 name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6224 goto wrong_template;
6226 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6228 /* create pad and add to collections */
6230 g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6231 templ->direction, "template", templ, NULL);
6233 collect_pad = (GstQTPad *)
6234 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6235 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6237 gst_qt_mux_pad_reset (collect_pad);
6238 collect_pad->trak = atom_trak_new (qtmux->context);
6239 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6241 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6243 /* set up pad functions */
6244 collect_pad->set_caps = setcaps_func;
6246 gst_pad_set_active (newpad, TRUE);
6247 gst_element_add_pad (element, newpad);
6254 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6259 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6264 GST_WARNING_OBJECT (qtmux, "This is not our template!");
6270 gst_qt_mux_get_property (GObject * object,
6271 guint prop_id, GValue * value, GParamSpec * pspec)
6273 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6275 GST_OBJECT_LOCK (qtmux);
6277 case PROP_MOVIE_TIMESCALE:
6278 g_value_set_uint (value, qtmux->timescale);
6280 case PROP_TRAK_TIMESCALE:
6281 g_value_set_uint (value, qtmux->trak_timescale);
6284 g_value_set_boolean (value, qtmux->guess_pts);
6286 #ifndef GST_REMOVE_DEPRECATED
6287 case PROP_DTS_METHOD:
6288 g_value_set_enum (value, qtmux->dts_method);
6291 case PROP_FAST_START:
6292 g_value_set_boolean (value, qtmux->fast_start);
6294 case PROP_FAST_START_TEMP_FILE:
6295 g_value_set_string (value, qtmux->fast_start_file_path);
6297 case PROP_MOOV_RECOV_FILE:
6298 g_value_set_string (value, qtmux->moov_recov_file_path);
6300 case PROP_FRAGMENT_DURATION:
6301 g_value_set_uint (value, qtmux->fragment_duration);
6303 case PROP_STREAMABLE:
6304 g_value_set_boolean (value, qtmux->streamable);
6306 case PROP_RESERVED_MAX_DURATION:
6307 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6309 case PROP_RESERVED_DURATION_REMAINING:
6310 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6311 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6313 GstClockTime remaining = qtmux->reserved_duration_remaining;
6315 /* Report the remaining space as the calculated remaining, minus
6316 * however much we've muxed since the last update */
6317 if (remaining > qtmux->muxed_since_last_update)
6318 remaining -= qtmux->muxed_since_last_update;
6321 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6322 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6323 remaining, qtmux->reserved_duration_remaining,
6324 qtmux->muxed_since_last_update);
6325 g_value_set_uint64 (value, remaining);
6328 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6329 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6331 case PROP_RESERVED_BYTES_PER_SEC:
6332 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6334 case PROP_RESERVED_PREFILL:
6335 g_value_set_boolean (value, qtmux->reserved_prefill);
6337 case PROP_INTERLEAVE_BYTES:
6338 g_value_set_uint64 (value, qtmux->interleave_bytes);
6340 case PROP_INTERLEAVE_TIME:
6341 g_value_set_uint64 (value, qtmux->interleave_time);
6343 case PROP_MAX_RAW_AUDIO_DRIFT:
6344 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6347 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6350 GST_OBJECT_UNLOCK (qtmux);
6354 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6358 g_free (qtmux->fast_start_file_path);
6359 qtmux->fast_start_file_path = NULL;
6361 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6362 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6367 gst_qt_mux_set_property (GObject * object,
6368 guint prop_id, const GValue * value, GParamSpec * pspec)
6370 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6372 GST_OBJECT_LOCK (qtmux);
6374 case PROP_MOVIE_TIMESCALE:
6375 qtmux->timescale = g_value_get_uint (value);
6377 case PROP_TRAK_TIMESCALE:
6378 qtmux->trak_timescale = g_value_get_uint (value);
6381 qtmux->guess_pts = g_value_get_boolean (value);
6383 #ifndef GST_REMOVE_DEPRECATED
6384 case PROP_DTS_METHOD:
6385 qtmux->dts_method = g_value_get_enum (value);
6388 case PROP_FAST_START:
6389 qtmux->fast_start = g_value_get_boolean (value);
6391 case PROP_FAST_START_TEMP_FILE:
6392 g_free (qtmux->fast_start_file_path);
6393 qtmux->fast_start_file_path = g_value_dup_string (value);
6394 /* NULL means to generate a random one */
6395 if (!qtmux->fast_start_file_path) {
6396 gst_qt_mux_generate_fast_start_file_path (qtmux);
6399 case PROP_MOOV_RECOV_FILE:
6400 g_free (qtmux->moov_recov_file_path);
6401 qtmux->moov_recov_file_path = g_value_dup_string (value);
6403 case PROP_FRAGMENT_DURATION:
6404 qtmux->fragment_duration = g_value_get_uint (value);
6406 case PROP_STREAMABLE:{
6407 GstQTMuxClass *qtmux_klass =
6408 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6409 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6410 qtmux->streamable = g_value_get_boolean (value);
6414 case PROP_RESERVED_MAX_DURATION:
6415 qtmux->reserved_max_duration = g_value_get_uint64 (value);
6417 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6418 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6420 case PROP_RESERVED_BYTES_PER_SEC:
6421 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6423 case PROP_RESERVED_PREFILL:
6424 qtmux->reserved_prefill = g_value_get_boolean (value);
6426 case PROP_INTERLEAVE_BYTES:
6427 qtmux->interleave_bytes = g_value_get_uint64 (value);
6428 qtmux->interleave_bytes_set = TRUE;
6430 case PROP_INTERLEAVE_TIME:
6431 qtmux->interleave_time = g_value_get_uint64 (value);
6432 qtmux->interleave_time_set = TRUE;
6434 case PROP_MAX_RAW_AUDIO_DRIFT:
6435 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6438 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6441 GST_OBJECT_UNLOCK (qtmux);
6444 static GstStateChangeReturn
6445 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6447 GstStateChangeReturn ret;
6448 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6450 switch (transition) {
6451 case GST_STATE_CHANGE_NULL_TO_READY:
6453 case GST_STATE_CHANGE_READY_TO_PAUSED:
6454 gst_collect_pads_start (qtmux->collect);
6455 qtmux->state = GST_QT_MUX_STATE_STARTED;
6457 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6459 case GST_STATE_CHANGE_PAUSED_TO_READY:
6460 gst_collect_pads_stop (qtmux->collect);
6466 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6468 switch (transition) {
6469 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6471 case GST_STATE_CHANGE_PAUSED_TO_READY:
6472 gst_qt_mux_reset (qtmux, TRUE);
6474 case GST_STATE_CHANGE_READY_TO_NULL:
6484 gst_qt_mux_register (GstPlugin * plugin)
6486 GTypeInfo typeinfo = {
6487 sizeof (GstQTMuxClass),
6488 (GBaseInitFunc) gst_qt_mux_base_init,
6490 (GClassInitFunc) gst_qt_mux_class_init,
6495 (GInstanceInitFunc) gst_qt_mux_init,
6497 static const GInterfaceInfo tag_setter_info = {
6500 static const GInterfaceInfo tag_xmp_writer_info = {
6503 static const GInterfaceInfo preset_info = {
6507 GstQTMuxFormat format;
6508 GstQTMuxClassParams *params;
6511 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6513 GST_LOG ("Registering muxers");
6516 GstQTMuxFormatProp *prop;
6517 GstCaps *subtitle_caps, *caption_caps;
6519 prop = &gst_qt_mux_format_list[i];
6520 format = prop->format;
6521 if (format == GST_QT_MUX_FORMAT_NONE)
6524 /* create a cache for these properties */
6525 params = g_new0 (GstQTMuxClassParams, 1);
6526 params->prop = prop;
6527 params->src_caps = gst_static_caps_get (&prop->src_caps);
6528 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6529 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6530 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6531 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6532 params->subtitle_sink_caps = subtitle_caps;
6534 gst_caps_unref (subtitle_caps);
6536 caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6537 if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6538 params->caption_sink_caps = caption_caps;
6540 gst_caps_unref (caption_caps);
6543 /* create the type now */
6544 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6546 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6547 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6548 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6549 &tag_xmp_writer_info);
6550 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6552 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6558 GST_LOG ("Finished registering muxers");
6560 /* FIXME: ideally classification tag should be added and
6561 registered in gstreamer core gsttaglist
6564 GST_LOG ("Registering tags");
6566 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6567 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6568 gst_tag_merge_use_first);
6570 GST_LOG ("Finished registering tags");