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,
400 PROP_START_GAP_THRESHOLD,
403 /* some spare for header size as well */
404 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
406 #define DEFAULT_MOVIE_TIMESCALE 0
407 #define DEFAULT_TRAK_TIMESCALE 0
408 #define DEFAULT_DO_CTTS TRUE
409 #define DEFAULT_FAST_START FALSE
410 #define DEFAULT_FAST_START_TEMP_FILE NULL
411 #define DEFAULT_MOOV_RECOV_FILE NULL
412 #define DEFAULT_FRAGMENT_DURATION 0
413 #define DEFAULT_STREAMABLE TRUE
414 #ifndef GST_REMOVE_DEPRECATED
415 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
417 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
418 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
419 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
420 #define DEFAULT_RESERVED_PREFILL FALSE
421 #define DEFAULT_INTERLEAVE_BYTES 0
422 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
423 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
424 #define DEFAULT_START_GAP_THRESHOLD 0
426 static void gst_qt_mux_finalize (GObject * object);
428 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
429 GstStateChange transition);
431 /* property functions */
432 static void gst_qt_mux_set_property (GObject * object,
433 guint prop_id, const GValue * value, GParamSpec * pspec);
434 static void gst_qt_mux_get_property (GObject * object,
435 guint prop_id, GValue * value, GParamSpec * pspec);
438 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
439 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
440 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
443 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
444 GstCollectData * data, GstEvent * event, gpointer user_data);
446 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
448 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
452 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
454 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
455 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
457 static GstElementClass *parent_class = NULL;
460 gst_qt_mux_base_init (gpointer g_class)
462 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
463 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
464 GstQTMuxClassParams *params;
465 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
467 GstPadTemplate *srctempl;
468 gchar *longname, *description;
471 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
472 GST_QT_MUX_PARAMS_QDATA);
473 g_assert (params != NULL);
475 /* construct the element details struct */
476 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
477 description = g_strdup_printf ("Multiplex audio and video into a %s file",
478 params->prop->long_name);
479 gst_element_class_set_static_metadata (element_class, longname,
480 "Codec/Muxer", description,
481 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
483 g_free (description);
486 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
487 GST_PAD_ALWAYS, params->src_caps);
488 gst_element_class_add_pad_template (element_class, srctempl);
490 if (params->audio_sink_caps) {
491 audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
492 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
493 GST_TYPE_QT_MUX_PAD);
494 gst_element_class_add_pad_template (element_class, audiosinktempl);
497 if (params->video_sink_caps) {
498 videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
499 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
500 GST_TYPE_QT_MUX_PAD);
501 gst_element_class_add_pad_template (element_class, videosinktempl);
504 if (params->subtitle_sink_caps) {
505 subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
506 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
507 GST_TYPE_QT_MUX_PAD);
508 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
511 if (params->caption_sink_caps) {
512 captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
513 GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
514 GST_TYPE_QT_MUX_PAD);
515 gst_element_class_add_pad_template (element_class, captionsinktempl);
518 klass->format = params->prop->format;
522 gst_qt_mux_class_init (GstQTMuxClass * klass)
524 GObjectClass *gobject_class;
525 GstElementClass *gstelement_class;
526 GParamFlags streamable_flags;
527 const gchar *streamable_desc;
529 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
530 "be streamed and hence no indexes written or duration written."
532 gobject_class = (GObjectClass *) klass;
533 gstelement_class = (GstElementClass *) klass;
535 parent_class = g_type_class_peek_parent (klass);
537 gobject_class->finalize = gst_qt_mux_finalize;
538 gobject_class->get_property = gst_qt_mux_get_property;
539 gobject_class->set_property = gst_qt_mux_set_property;
541 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
542 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
543 streamable_desc = STREAMABLE_DESC;
544 streamable = DEFAULT_STREAMABLE;
547 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
548 streamable_flags |= G_PARAM_DEPRECATED;
552 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
553 g_param_spec_uint ("movie-timescale", "Movie timescale",
554 "Timescale to use in the movie (units per second, 0 == default)",
555 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
556 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
557 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
558 g_param_spec_uint ("trak-timescale", "Track timescale",
559 "Timescale to use for the tracks (units per second, 0 is automatic)",
560 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
561 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
562 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
563 g_param_spec_boolean ("presentation-time",
564 "Include presentation-time info",
565 "Calculate and include presentation/composition time "
566 "(in addition to decoding time)", DEFAULT_DO_CTTS,
567 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
568 #ifndef GST_REMOVE_DEPRECATED
569 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
570 g_param_spec_enum ("dts-method", "dts-method",
571 "Method to determine DTS time (DEPRECATED)",
572 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
573 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
574 G_PARAM_STATIC_STRINGS));
576 g_object_class_install_property (gobject_class, PROP_FAST_START,
577 g_param_spec_boolean ("faststart", "Format file to faststart",
578 "If the file should be formatted for faststart (headers first)",
579 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
580 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
581 g_param_spec_string ("faststart-file", "File to use for storing buffers",
582 "File that will be used temporarily to store data from the stream "
583 "when creating a faststart file. If null a filepath will be "
584 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
585 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
586 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
587 g_param_spec_string ("moov-recovery-file",
588 "File to store data for posterior moov atom recovery",
589 "File to be used to store "
590 "data for moov atom making movie file recovery possible in case "
591 "of a crash during muxing. Null for disabled. (Experimental)",
592 DEFAULT_MOOV_RECOV_FILE,
593 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
594 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
595 g_param_spec_uint ("fragment-duration", "Fragment duration",
596 "Fragment durations in ms (produce a fragmented file if > 0)",
597 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
598 2000 : DEFAULT_FRAGMENT_DURATION,
599 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
600 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
601 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
602 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
603 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
604 g_param_spec_uint64 ("reserved-max-duration",
605 "Reserved maximum file duration (ns)",
606 "When set to a value > 0, reserves space for index tables at the "
607 "beginning of the file.",
608 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
609 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
610 g_object_class_install_property (gobject_class,
611 PROP_RESERVED_DURATION_REMAINING,
612 g_param_spec_uint64 ("reserved-duration-remaining",
613 "Report the approximate amount of remaining recording space (ns)",
614 "Reports the approximate amount of remaining moov header space "
615 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
616 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
617 g_object_class_install_property (gobject_class,
618 PROP_RESERVED_MOOV_UPDATE_PERIOD,
619 g_param_spec_uint64 ("reserved-moov-update-period",
620 "Interval at which to update index tables (ns)",
621 "When used with reserved-max-duration, periodically updates the "
622 "index tables with information muxed so far.", 0, G_MAXUINT64,
623 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
624 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
625 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
626 g_param_spec_uint ("reserved-bytes-per-sec",
627 "Reserved MOOV bytes per second, per track",
628 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
629 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
630 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
631 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
632 g_param_spec_boolean ("reserved-prefill",
633 "Reserved Prefill Samples Table",
634 "Prefill samples table of reserved duration",
635 DEFAULT_RESERVED_PREFILL,
636 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
637 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
638 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
639 "Interleave between streams in bytes",
640 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
641 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
642 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
643 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
644 "Interleave between streams in nanoseconds",
645 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
646 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
647 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
648 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
649 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
650 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
651 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
652 g_object_class_install_property (gobject_class, PROP_START_GAP_THRESHOLD,
653 g_param_spec_uint64 ("start-gap-threshold", "Start Gap Threshold",
654 "Threshold for creating an edit list for gaps at the start in nanoseconds",
655 0, G_MAXUINT64, DEFAULT_START_GAP_THRESHOLD,
656 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
658 gstelement_class->request_new_pad =
659 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
660 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
661 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
665 gst_qt_mux_pad_reset (GstQTPad * qtpad)
668 qtpad->is_out_of_order = FALSE;
669 qtpad->sample_size = 0;
672 qtpad->sample_offset = 0;
673 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
674 qtpad->first_ts = GST_CLOCK_TIME_NONE;
675 qtpad->first_dts = GST_CLOCK_TIME_NONE;
676 qtpad->prepare_buf_func = NULL;
677 qtpad->create_empty_buffer = NULL;
678 qtpad->avg_bitrate = 0;
679 qtpad->max_bitrate = 0;
680 qtpad->total_duration = 0;
681 qtpad->total_bytes = 0;
682 qtpad->sparse = FALSE;
684 gst_buffer_replace (&qtpad->last_buf, NULL);
687 gst_tag_list_unref (qtpad->tags);
691 /* reference owned elsewhere */
693 qtpad->tc_trak = NULL;
696 atom_traf_free (qtpad->traf);
699 atom_array_clear (&qtpad->fragment_buffers);
701 g_array_unref (qtpad->samples);
702 qtpad->samples = NULL;
704 /* reference owned elsewhere */
707 qtpad->first_pts = GST_CLOCK_TIME_NONE;
710 gst_video_time_code_free (qtpad->first_tc);
711 qtpad->first_tc = NULL;
713 if (qtpad->raw_audio_adapter)
714 gst_object_unref (qtpad->raw_audio_adapter);
715 qtpad->raw_audio_adapter = NULL;
719 * Takes GstQTMux back to its initial state
722 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
726 qtmux->state = GST_QT_MUX_STATE_NONE;
727 qtmux->header_size = 0;
728 qtmux->mdat_size = 0;
731 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
732 qtmux->fragment_sequence = 0;
735 atom_ftyp_free (qtmux->ftyp);
739 atom_moov_free (qtmux->moov);
743 atom_mfra_free (qtmux->mfra);
746 if (qtmux->fast_start_file) {
747 fclose (qtmux->fast_start_file);
748 g_remove (qtmux->fast_start_file_path);
749 qtmux->fast_start_file = NULL;
751 if (qtmux->moov_recov_file) {
752 fclose (qtmux->moov_recov_file);
753 qtmux->moov_recov_file = NULL;
755 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
756 AtomInfo *ainfo = (AtomInfo *) walk->data;
757 ainfo->free_func (ainfo->atom);
760 g_slist_free (qtmux->extra_atoms);
761 qtmux->extra_atoms = NULL;
763 GST_OBJECT_LOCK (qtmux);
764 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
765 GST_OBJECT_UNLOCK (qtmux);
768 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
769 GstQTPad *qtpad = (GstQTPad *) walk->data;
770 gst_qt_mux_pad_reset (qtpad);
772 /* hm, moov_free above yanked the traks away from us,
773 * so do not free, but do clear */
778 qtmux->moov = atom_moov_new (qtmux->context);
779 /* ensure all is as nice and fresh as request_new_pad would provide it */
780 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
781 GstQTPad *qtpad = (GstQTPad *) walk->data;
783 qtpad->trak = atom_trak_new (qtmux->context);
784 atom_moov_add_trak (qtmux->moov, qtpad->trak);
788 qtmux->current_pad = NULL;
789 qtmux->current_chunk_size = 0;
790 qtmux->current_chunk_duration = 0;
791 qtmux->current_chunk_offset = -1;
793 qtmux->reserved_moov_size = 0;
794 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
795 qtmux->muxed_since_last_update = 0;
796 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
800 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
802 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
803 GstPadTemplate *templ;
805 templ = gst_element_class_get_pad_template (klass, "src");
806 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
807 gst_pad_use_fixed_caps (qtmux->srcpad);
808 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
810 qtmux->sinkpads = NULL;
811 qtmux->collect = gst_collect_pads_new ();
812 gst_collect_pads_set_event_function (qtmux->collect,
813 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
814 gst_collect_pads_set_clip_function (qtmux->collect,
815 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
816 gst_collect_pads_set_function (qtmux->collect,
817 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
819 /* properties set to default upon construction */
821 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
822 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
823 qtmux->reserved_bytes_per_sec_per_trak =
824 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
825 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
826 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
827 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
828 qtmux->start_gap_threshold = DEFAULT_START_GAP_THRESHOLD;
830 /* always need this */
832 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
834 /* internals to initial state */
835 gst_qt_mux_reset (qtmux, TRUE);
840 gst_qt_mux_finalize (GObject * object)
842 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
844 gst_qt_mux_reset (qtmux, FALSE);
846 g_free (qtmux->fast_start_file_path);
847 g_free (qtmux->moov_recov_file_path);
849 atoms_context_free (qtmux->context);
850 gst_object_unref (qtmux->collect);
852 g_slist_free (qtmux->sinkpads);
854 G_OBJECT_CLASS (parent_class)->finalize (object);
858 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
865 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
870 size = gst_buffer_get_size (buf);
871 newbuf = gst_buffer_new_and_alloc (size + 8);
872 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
874 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
875 GST_WRITE_UINT32_BE (map.data, map.size);
876 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
878 gst_buffer_unmap (buf, &map);
879 gst_buffer_unref (buf);
885 extract_608_field_from_s334_1a (const guint8 * ccdata, gsize ccdata_size,
886 guint field, guint8 ** res)
889 gsize storage_size = 128;
890 gsize i, res_size = 0;
892 storage = g_malloc0 (storage_size);
894 /* Iterate over the ccdata and put the corresponding tuples for the given field
896 for (i = 0; i < ccdata_size; i += 3) {
897 if ((field == 1 && (ccdata[i * 3] & 0x80)) ||
898 (field == 2 && !(ccdata[i * 3] & 0x80))) {
899 GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
900 ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
901 if (res_size >= storage_size) {
903 storage = g_realloc (storage, storage_size);
905 storage[res_size] = ccdata[i * 3 + 1];
906 storage[res_size + 1] = ccdata[i * 3 + 2];
923 gst_qt_mux_prepare_caption_buffer (GstQTPad * qtpad, GstBuffer * buf,
926 GstBuffer *newbuf = NULL;
927 GstMapInfo map, inmap;
934 in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
936 size = gst_buffer_get_size (buf);
937 gst_buffer_map (buf, &inmap, GST_MAP_READ);
939 GST_LOG_OBJECT (qtmux,
940 "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
941 GST_FOURCC_ARGS (qtpad->fourcc), size);
943 switch (qtpad->fourcc) {
947 gsize cdat_size, cdt2_size, total_size = 0;
948 gsize write_offs = 0;
951 extract_608_field_from_s334_1a (inmap.data, inmap.size, 1, &cdat);
953 extract_608_field_from_s334_1a (inmap.data, inmap.size, 2, &cdt2);
956 total_size += cdat_size + 8;
958 total_size += cdt2_size + 8;
959 if (total_size == 0) {
960 GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
961 /* FIXME : We might want to *always* store something, even if
962 * it's "empty" CC (i.e. 0x80 0x80) */
966 newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
967 /* Let's copy over all metadata and not the memory */
968 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
970 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
971 if (cdat_size || in_prefill) {
972 GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
973 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
975 memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
977 /* Write 'empty' CC */
981 write_offs = in_prefill ? 10 : cdat_size + 8;
986 if (cdt2_size || in_prefill) {
987 GST_WRITE_UINT32_BE (map.data + write_offs,
988 in_prefill ? 10 : cdt2_size + 8);
989 GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
991 memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
993 /* Write 'empty' CC */
994 map.data[write_offs + 8] = 0x80;
995 map.data[write_offs + 9] = 0x80;
1000 gst_buffer_unmap (newbuf, &map);
1006 /* Take the whole CDP */
1007 if (in_prefill && size > 256) {
1008 GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1011 newbuf = gst_buffer_new_and_alloc (in_prefill ? 256 + 8 : size + 8);
1013 /* Let's copy over all metadata and not the memory */
1014 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1016 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1018 GST_WRITE_UINT32_BE (map.data, size + 8);
1019 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1020 memcpy (map.data + 8, inmap.data, inmap.size);
1022 gst_buffer_unmap (newbuf, &map);
1026 /* theoretically this should never happen, but let's keep this here in case */
1027 GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1031 gst_buffer_unmap (buf, &inmap);
1032 gst_buffer_unref (buf);
1038 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1045 const guint8 *dataend;
1047 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1052 gst_buffer_map (buf, &frommap, GST_MAP_READ);
1054 dataend = memchr (frommap.data, 0, frommap.size);
1055 size = dataend ? dataend - frommap.data : frommap.size;
1056 newbuf = gst_buffer_new_and_alloc (size + 2);
1058 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1060 GST_WRITE_UINT16_BE (tomap.data, size);
1061 memcpy (tomap.data + 2, frommap.data, size);
1063 gst_buffer_unmap (newbuf, &tomap);
1064 gst_buffer_unmap (buf, &frommap);
1066 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1068 /* gst_buffer_copy_into is trying to be too clever and
1069 * won't copy duration when size is different */
1070 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1072 gst_buffer_unref (buf);
1078 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1079 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1084 g_return_if_fail (qtpad->trak_ste);
1086 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
1088 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1092 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1096 GstByteReader reader;
1099 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1100 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1104 if (G_UNLIKELY (map.size < 8))
1107 gst_byte_reader_init (&reader, map.data, map.size);
1108 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1113 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1115 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1118 gst_bit_reader_init (&bits, map.data, map.size);
1120 /* off + sync + crc */
1121 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1123 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1124 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1125 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1126 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1127 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1129 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1130 gst_bit_reader_skip_unchecked (&bits, 2);
1131 if ((acmod & 0x4)) /* if a surround channel exists */
1132 gst_bit_reader_skip_unchecked (&bits, 2);
1133 if (acmod == 0x2) /* if in 2/0 mode */
1134 gst_bit_reader_skip_unchecked (&bits, 2);
1136 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1138 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1139 bsmod, acmod, lfe_on);
1141 /* AC-3 spec says that those values should be constant for the
1142 * whole stream when muxed in mp4. We trust the input follows it */
1143 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1144 "prepare buffer function");
1145 qtpad->prepare_buf_func = NULL;
1149 gst_buffer_unmap (buf, &map);
1154 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1158 data = g_malloc (2);
1159 GST_WRITE_UINT16_BE (data, 0);
1161 return gst_buffer_new_wrapped (data, 2);
1165 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1166 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1168 switch (gst_tag_get_type (tag)) {
1174 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1176 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1177 GST_FOURCC_ARGS (fourcc), str);
1178 atom_udta_add_str_tag (udta, fourcc, str);
1187 if (!gst_tag_list_get_double (list, tag, &value))
1189 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1190 GST_FOURCC_ARGS (fourcc), (gint) value);
1191 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1198 /* paired unsigned integers */
1202 got_tag = gst_tag_list_get_uint (list, tag, &value);
1203 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1206 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1207 GST_FOURCC_ARGS (fourcc), value, count);
1208 atom_udta_add_uint_tag (udta, fourcc, 0,
1209 value << 16 | (count & 0xFFFF));
1211 /* unpaired unsigned integers */
1212 if (!gst_tag_list_get_uint (list, tag, &value))
1214 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1215 GST_FOURCC_ARGS (fourcc), value);
1216 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1221 g_assert_not_reached ();
1227 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1228 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1236 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1238 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1241 year = g_date_get_year (date);
1242 month = g_date_get_month (date);
1243 day = g_date_get_day (date);
1247 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1248 day == G_DATE_BAD_DAY) {
1249 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1253 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1254 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1255 GST_FOURCC_ARGS (fourcc), str);
1256 atom_udta_add_str_tag (udta, fourcc, str);
1261 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1262 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1264 GValue value = { 0, };
1268 GstStructure *structure;
1272 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1274 if (!gst_tag_list_copy_value (&value, list, tag))
1277 sample = gst_value_get_sample (&value);
1282 buf = gst_sample_get_buffer (sample);
1286 caps = gst_sample_get_caps (sample);
1288 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1292 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1294 structure = gst_caps_get_structure (caps, 0);
1295 if (gst_structure_has_name (structure, "image/jpeg"))
1297 else if (gst_structure_has_name (structure, "image/png"))
1301 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1305 gst_buffer_map (buf, &map, GST_MAP_READ);
1306 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1307 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1308 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1309 gst_buffer_unmap (buf, &map);
1311 g_value_unset (&value);
1315 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1316 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1321 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1322 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1324 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1328 if (!gst_tag_list_get_uint (list, tag2, &number))
1332 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1333 GST_FOURCC_ARGS (fourcc), str);
1334 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1336 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1337 GST_FOURCC_ARGS (fourcc), str, number);
1338 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1345 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1346 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1351 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1353 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1356 year = g_date_get_year (date);
1359 if (year == G_DATE_BAD_YEAR) {
1360 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1364 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1365 GST_FOURCC_ARGS (fourcc), year);
1366 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1370 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1371 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1373 gdouble latitude = -360, longitude = -360, altitude = 0;
1374 gchar *location = NULL;
1375 guint8 *data, *ddata;
1376 gint size = 0, len = 0;
1377 gboolean ret = FALSE;
1379 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1381 ret = gst_tag_list_get_string (list, tag, &location);
1382 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1384 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1386 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1393 len = strlen (location);
1394 size += len + 1 + 2;
1396 /* role + (long, lat, alt) + body + notes */
1397 size += 1 + 3 * 4 + 1 + 1;
1399 data = ddata = g_malloc (size);
1402 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1405 memcpy (data + 2, location, len);
1406 GST_WRITE_UINT8 (data + 2 + len, 0);
1407 data += len + 1 + 2;
1409 GST_WRITE_UINT8 (data, 0);
1410 /* long, lat, alt */
1411 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1412 QT_WRITE_SFP32 (data + 1, longitude);
1413 QT_WRITE_SFP32 (data + 5, latitude);
1414 QT_WRITE_SFP32 (data + 9, altitude);
1415 /* neither astronomical body nor notes */
1416 GST_WRITE_UINT16_BE (data + 13, 0);
1418 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1419 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1424 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1425 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1427 gchar *keywords = NULL;
1428 guint8 *data, *ddata;
1432 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1434 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1437 kwds = g_strsplit (keywords, ",", 0);
1441 for (i = 0; kwds[i]; i++) {
1442 /* size byte + null-terminator */
1443 size += strlen (kwds[i]) + 1 + 1;
1446 /* language tag + count + keywords */
1449 data = ddata = g_malloc (size);
1452 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1454 GST_WRITE_UINT8 (data + 2, i);
1457 for (i = 0; kwds[i]; ++i) {
1458 gint len = strlen (kwds[i]);
1460 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1461 GST_FOURCC_ARGS (fourcc), kwds[i]);
1463 GST_WRITE_UINT8 (data, len + 1);
1464 memcpy (data + 1, kwds[i], len + 1);
1470 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1475 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1476 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1484 size = strlen (input);
1486 if (size < 4 + 3 + 1 + 1 + 1) {
1487 /* at least the minimum xxxx://y/z */
1488 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1493 /* read the fourcc */
1494 memcpy (&fourcc, data, 4);
1498 if (strncmp (data, "://", 3) != 0) {
1504 /* read the table number */
1505 if (sscanf (data, "%d", &table) != 1) {
1509 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1510 ", table numbers should be positive, ignoring tag", table);
1514 /* find the next / */
1515 while (size > 0 && data[0] != '/') {
1522 g_assert (data[0] == '/');
1531 /* read up the rest of the string */
1532 *p_content = g_strdup (data);
1533 *p_table = (guint16) table;
1539 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1540 "input (%s) didn't match the expected entitycode://table/content",
1547 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1548 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1550 gchar *clsf_data = NULL;
1554 gchar *content = NULL;
1557 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1559 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1562 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1563 GST_FOURCC_ARGS (fourcc), clsf_data);
1565 /* parse the string, format is:
1566 * entityfourcc://table/content
1568 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1572 size = strlen (content) + 1;
1574 /* now we have everything, build the atom
1575 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1576 data = g_malloc (4 + 2 + 2 + size);
1577 GST_WRITE_UINT32_LE (data, entity);
1578 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1579 GST_WRITE_UINT16_BE (data + 6, 0);
1580 memcpy (data + 8, content, size);
1583 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1587 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1588 const GstTagList * list, AtomUDTA * udta, const char *tag,
1589 const char *tag2, guint32 fourcc);
1592 * Struct to record mappings from gstreamer tags to fourcc codes
1594 typedef struct _GstTagToFourcc
1597 const gchar *gsttag;
1598 const gchar *gsttag2;
1599 const GstQTMuxAddUdtaTagFunc func;
1602 /* tag list tags to fourcc matching */
1603 static const GstTagToFourcc tag_matches_mp4[] = {
1604 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1605 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1606 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1607 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1608 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1609 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1610 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1611 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1612 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1613 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1614 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1615 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1616 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1617 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1618 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1619 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1620 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1621 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1622 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1623 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1624 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1625 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1626 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1627 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1628 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1629 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1630 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1631 gst_qt_mux_add_mp4_tag},
1632 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1633 gst_qt_mux_add_mp4_tag},
1634 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1635 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1639 static const GstTagToFourcc tag_matches_3gp[] = {
1640 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1641 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1642 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1643 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1644 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1645 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1646 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1647 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1648 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1649 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1650 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1651 gst_qt_mux_add_3gp_classification},
1655 /* qtdemux produces these for atoms it cannot parse */
1656 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1659 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1661 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1662 GstBuffer *xmp = NULL;
1664 /* adobe specs only have 'quicktime' and 'mp4',
1665 * but I guess we can extrapolate to gpp.
1666 * Keep mj2 out for now as we don't add any tags for it yet.
1667 * If you have further info about xmp on these formats, please share */
1668 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1671 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1673 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1674 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1677 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1680 /* for isom/mp4, it is a top level uuid atom */
1681 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1684 ainfo = build_uuid_xmp_atom (xmp);
1686 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1691 gst_buffer_unref (xmp);
1695 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1698 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1701 const gchar *tag, *tag2;
1702 const GstTagToFourcc *tag_matches;
1704 switch (qtmux_klass->format) {
1705 case GST_QT_MUX_FORMAT_3GP:
1706 tag_matches = tag_matches_3gp;
1708 case GST_QT_MUX_FORMAT_MJ2:
1712 /* sort of iTunes style for mp4 and QT (?) */
1713 tag_matches = tag_matches_mp4;
1720 /* Clear existing tags so we don't add them over and over */
1721 atom_udta_clear_tags (udta);
1723 for (i = 0; tag_matches[i].fourcc; i++) {
1724 fourcc = tag_matches[i].fourcc;
1725 tag = tag_matches[i].gsttag;
1726 tag2 = tag_matches[i].gsttag2;
1728 g_assert (tag_matches[i].func);
1729 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1732 /* add unparsed blobs if present */
1733 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1736 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1737 for (i = 0; i < num_tags; ++i) {
1738 GstSample *sample = NULL;
1740 const GstStructure *s;
1742 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1745 buf = gst_sample_get_buffer (sample);
1747 if (buf && (s = gst_sample_get_info (sample))) {
1748 const gchar *style = NULL;
1751 gst_buffer_map (buf, &map, GST_MAP_READ);
1752 GST_DEBUG_OBJECT (qtmux,
1753 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1754 GST_PTR_FORMAT, i, num_tags, map.size, s);
1755 if (s && (style = gst_structure_get_string (s, "style"))) {
1756 /* try to prevent some style tag ending up into another variant
1757 * (todo: make into a list if more cases) */
1758 if ((strcmp (style, "itunes") == 0 &&
1759 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1760 (strcmp (style, "iso") == 0 &&
1761 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1762 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1763 atom_udta_add_blob_tag (udta, map.data, map.size);
1766 gst_buffer_unmap (buf, &map);
1768 gst_sample_unref (sample);
1776 * Gets the tagsetter iface taglist and puts the known tags
1777 * into the output stream
1780 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1782 const GstTagList *tags = NULL;
1785 GST_OBJECT_LOCK (qtmux);
1786 if (qtmux->tags_changed) {
1787 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1788 qtmux->tags_changed = FALSE;
1790 GST_OBJECT_UNLOCK (qtmux);
1792 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1794 if (tags && !gst_tag_list_is_empty (tags)) {
1795 GstTagList *copy = gst_tag_list_copy (tags);
1797 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1798 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1799 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1800 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1802 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1803 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1804 gst_qt_mux_add_xmp_tags (qtmux, copy);
1805 gst_tag_list_unref (copy);
1807 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1810 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1811 GstCollectData *cdata = (GstCollectData *) walk->data;
1812 GstQTPad *qpad = (GstQTPad *) cdata;
1813 GstPad *pad = qpad->collect.pad;
1815 if (qpad->tags_changed && qpad->tags) {
1816 GST_DEBUG_OBJECT (pad, "Adding tags");
1817 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1818 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1819 qpad->tags_changed = FALSE;
1820 GST_DEBUG_OBJECT (pad, "Tags added");
1822 GST_DEBUG_OBJECT (pad, "No new tags received");
1827 static inline GstBuffer *
1828 _gst_buffer_new_take_data (guint8 * data, guint size)
1832 buf = gst_buffer_new ();
1833 gst_buffer_append_memory (buf,
1834 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1839 static GstFlowReturn
1840 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1846 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1848 size = gst_buffer_get_size (buf);
1849 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1851 if (mind_fast && qtmux->fast_start_file) {
1855 GST_LOG_OBJECT (qtmux, "to temporary file");
1856 gst_buffer_map (buf, &map, GST_MAP_READ);
1857 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1858 gst_buffer_unmap (buf, &map);
1859 gst_buffer_unref (buf);
1865 GST_LOG_OBJECT (qtmux, "downstream");
1866 res = gst_pad_push (qtmux->srcpad, buf);
1869 if (G_LIKELY (offset))
1877 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1878 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1879 return GST_FLOW_ERROR;
1884 gst_qt_mux_seek_to_beginning (FILE * f)
1887 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1889 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1890 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1893 if (fseek (f, (long) 0, SEEK_SET) != 0)
1899 static GstFlowReturn
1900 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1902 GstFlowReturn ret = GST_FLOW_OK;
1903 GstBuffer *buf = NULL;
1905 if (fflush (qtmux->fast_start_file))
1908 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1911 /* hm, this could all take a really really long time,
1912 * but there may not be another way to get moov atom first
1913 * (somehow optimize copy?) */
1914 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1915 while (ret == GST_FLOW_OK) {
1916 const int bufsize = 4096;
1920 buf = gst_buffer_new_and_alloc (bufsize);
1921 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1922 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1924 gst_buffer_unmap (buf, &map);
1927 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1928 gst_buffer_unmap (buf, &map);
1929 if (size != bufsize)
1930 gst_buffer_set_size (buf, size);
1931 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1935 gst_buffer_unref (buf);
1937 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1939 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1947 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1948 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1949 ret = GST_FLOW_ERROR;
1954 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1955 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1956 ret = GST_FLOW_ERROR;
1961 /* clear descriptor so we don't remove temp file later on,
1962 * might be possible to recover */
1963 fclose (qtmux->fast_start_file);
1964 qtmux->fast_start_file = NULL;
1970 * Sends the initial mdat atom fields (size fields and fourcc type),
1971 * the subsequent buffers are considered part of it's data.
1972 * As we can't predict the amount of data that we are going to place in mdat
1973 * we need to record the position of the size field in the stream so we can
1974 * seek back to it later and update when the streams have finished.
1976 static GstFlowReturn
1977 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1978 gboolean extended, gboolean fsync_after)
1983 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1984 "size %" G_GUINT64_FORMAT, size);
1986 /* if the qtmux state is EOS, really write the mdat, otherwise
1987 * allow size == 0 for a placeholder atom */
1988 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1992 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1993 /* Always write 16-bytes, but put a free atom first
1994 * if the size is < 4GB. */
1995 buf = gst_buffer_new_and_alloc (16);
1996 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1999 /* Write extended mdat header and large_size field */
2000 GST_WRITE_UINT32_BE (map.data, 1);
2001 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2002 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
2004 /* Write an empty free atom, then standard 32-bit mdat */
2005 GST_WRITE_UINT32_BE (map.data, 8);
2006 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
2007 GST_WRITE_UINT32_BE (map.data + 8, size);
2008 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2010 gst_buffer_unmap (buf, &map);
2012 buf = gst_buffer_new_and_alloc (8);
2013 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2015 /* Vanilla 32-bit mdat */
2016 GST_WRITE_UINT32_BE (map.data, size);
2017 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2018 gst_buffer_unmap (buf, &map);
2021 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2023 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2025 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2030 * We get the position of the mdat size field, seek back to it
2031 * and overwrite with the real value
2033 static GstFlowReturn
2034 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2035 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2039 /* We must have recorded the mdat position for this to work */
2040 g_assert (mdat_pos != 0);
2042 /* seek and rewrite the header */
2043 gst_segment_init (&segment, GST_FORMAT_BYTES);
2044 segment.start = mdat_pos;
2045 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2047 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2051 static GstFlowReturn
2052 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2055 guint64 size = 0, offset = 0;
2056 guint8 *data = NULL;
2058 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2060 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2061 goto serialize_error;
2063 buf = _gst_buffer_new_take_data (data, offset);
2065 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2066 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2071 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2072 ("Failed to serialize ftyp"));
2073 return GST_FLOW_ERROR;
2078 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2079 GstBuffer ** p_prefix)
2081 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2082 guint32 major, version;
2084 GstBuffer *prefix = NULL;
2085 AtomFTYP *ftyp = NULL;
2087 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2089 /* init and send context and ftyp based on current property state */
2090 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2091 &version, &comp, qtmux->moov, qtmux->longest_chunk,
2092 qtmux->fast_start_file != NULL);
2093 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2100 gst_buffer_unref (prefix);
2105 static GstFlowReturn
2106 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2108 GstFlowReturn ret = GST_FLOW_OK;
2109 GstBuffer *prefix = NULL;
2111 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2113 /* init and send context and ftyp based on current property state */
2115 atom_ftyp_free (qtmux->ftyp);
2118 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2120 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2121 if (ret != GST_FLOW_OK)
2124 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2128 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2130 GstStructure *structure;
2131 GValue array = { 0 };
2132 GValue value = { 0 };
2133 GstCaps *caps, *tcaps;
2135 tcaps = gst_pad_get_current_caps (mux->srcpad);
2136 caps = gst_caps_copy (tcaps);
2137 gst_caps_unref (tcaps);
2139 structure = gst_caps_get_structure (caps, 0);
2141 g_value_init (&array, GST_TYPE_ARRAY);
2143 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2144 g_value_init (&value, GST_TYPE_BUFFER);
2145 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2146 gst_value_array_append_value (&array, &value);
2147 g_value_unset (&value);
2149 gst_structure_set_value (structure, "streamheader", &array);
2150 g_value_unset (&array);
2151 gst_pad_set_caps (mux->srcpad, caps);
2152 gst_caps_unref (caps);
2156 * Write out a free space atom. The offset is adjusted by the full
2157 * size, but a smaller buffer is sent
2159 static GstFlowReturn
2160 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2161 gboolean fsync_after)
2165 guint8 *data = NULL;
2166 guint64 offset = 0, bsize = 0;
2169 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2171 /* We can't make a free space atom smaller than the header */
2175 node_header = g_malloc0 (sizeof (Atom));
2176 node_header->type = FOURCC_free;
2177 node_header->size = size;
2180 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2181 goto serialize_error;
2183 buf = _gst_buffer_new_take_data (data, offset);
2184 g_free (node_header);
2187 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2189 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2190 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2197 /* Make sure downstream position ends up at the end of this free box */
2198 gst_segment_init (&segment, GST_FORMAT_BYTES);
2199 segment.start = *off;
2200 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2208 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2209 ("Not enough free reserved space"));
2210 return GST_FLOW_ERROR;
2214 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2215 ("Failed to serialize mdat"));
2216 g_free (node_header);
2217 return GST_FLOW_ERROR;
2222 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2224 gboolean fragmented = FALSE;
2227 GST_OBJECT_LOCK (qtmux);
2228 timescale = qtmux->timescale;
2229 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2230 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2232 GST_OBJECT_UNLOCK (qtmux);
2234 /* inform lower layers of our property wishes, and determine duration.
2235 * Let moov take care of this using its list of traks;
2236 * so that released pads are also included */
2237 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2239 atom_moov_update_timescale (qtmux->moov, timescale);
2240 atom_moov_set_fragmented (qtmux->moov, fragmented);
2242 atom_moov_update_duration (qtmux->moov);
2245 static GstFlowReturn
2246 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2247 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2249 guint64 offset = 0, size = 0;
2252 GstFlowReturn ret = GST_FLOW_OK;
2254 guint64 current_time = atoms_get_current_qt_time ();
2256 /* update modification times */
2257 qtmux->moov->mvhd.time_info.modification_time = current_time;
2258 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2259 GstCollectData *cdata = (GstCollectData *) walk->data;
2260 GstQTPad *qtpad = (GstQTPad *) cdata;
2262 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2263 qtpad->trak->tkhd.modification_time = current_time;
2266 /* serialize moov */
2269 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2270 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2271 goto serialize_error;
2272 qtmux->last_moov_size = offset;
2274 /* Check we have enough reserved space for this and a Free atom */
2275 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2276 goto too_small_reserved;
2277 buf = _gst_buffer_new_take_data (data, offset);
2278 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2280 /* If at EOS, this is the final moov, put in the streamheader
2281 * (apparently used by a flumotion util) */
2282 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2283 gst_qt_mux_set_header_on_caps (qtmux, buf);
2286 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2287 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2289 /* Write out a free atom if needed */
2290 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2291 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2292 (guint32) (padded_moov_size - offset));
2294 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2301 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2302 ("Not enough free reserved header space"),
2303 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2304 offset, padded_moov_size));
2305 return GST_FLOW_ERROR;
2310 return GST_FLOW_ERROR;
2314 /* either calculates size of extra atoms or pushes them */
2315 static GstFlowReturn
2316 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2320 guint64 loffset = 0, size = 0;
2322 GstFlowReturn ret = GST_FLOW_OK;
2324 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2325 AtomInfo *ainfo = (AtomInfo *) walk->data;
2329 if (!ainfo->copy_data_func (ainfo->atom,
2330 send ? &data : NULL, &size, &loffset))
2331 goto serialize_error;
2336 GST_DEBUG_OBJECT (qtmux,
2337 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2338 GST_FOURCC_ARGS (ainfo->atom->type));
2339 buf = _gst_buffer_new_take_data (data, loffset);
2340 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2341 if (ret != GST_FLOW_OK)
2354 return GST_FLOW_ERROR;
2359 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2361 gboolean seekable = FALSE;
2362 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2364 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2365 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2366 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2368 /* have to assume seeking is not supported if query not handled downstream */
2369 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2372 gst_query_unref (query);
2378 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2381 gboolean fail = FALSE;
2382 AtomFTYP *ftyp = NULL;
2383 GstBuffer *prefix = NULL;
2385 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2386 qtmux->moov_recov_file_path);
2388 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2389 if (qtmux->moov_recov_file == NULL) {
2390 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2391 qtmux->moov_recov_file_path);
2395 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2397 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2398 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2399 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2403 atom_ftyp_free (ftyp);
2405 gst_buffer_unref (prefix);
2407 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2408 GstCollectData *cdata = (GstCollectData *) walk->data;
2409 GstQTPad *qpad = (GstQTPad *) cdata;
2410 /* write info for each stream */
2411 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2413 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2423 fclose (qtmux->moov_recov_file);
2424 qtmux->moov_recov_file = NULL;
2428 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2430 switch (qpad->fourcc) {
2439 return qpad->sample_offset;
2442 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2443 qpad->expected_sample_duration_n,
2444 qpad->expected_sample_duration_d *
2445 atom_trak_get_timescale (qpad->trak));
2452 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2454 switch (qpad->fourcc) {
2456 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2458 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2460 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2462 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2469 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2471 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2473 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2475 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2482 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2484 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2486 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2488 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2495 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2497 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2499 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2501 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2508 /* We always write both cdat and cdt2 atom in prefill mode */
2511 /* We're cheating a bit by always allocating 256 bytes plus 8 bytes for the atom header
2512 * even if we use less */
2517 guint64 next_sample_offset;
2519 block_idx = prefill_get_block_index (qtmux, qpad);
2520 next_sample_offset =
2521 gst_util_uint64_scale (block_idx + 1,
2522 qpad->expected_sample_duration_d *
2523 atom_trak_get_timescale (qpad->trak),
2524 qpad->expected_sample_duration_n);
2526 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2531 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2539 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2541 switch (qpad->fourcc) {
2550 return gst_util_uint64_scale (qpad->sample_offset + 1,
2551 qpad->expected_sample_duration_d * GST_SECOND,
2552 qpad->expected_sample_duration_n);
2556 guint64 next_sample_offset;
2558 block_idx = prefill_get_block_index (qtmux, qpad);
2559 next_sample_offset =
2560 gst_util_uint64_scale (block_idx + 1,
2561 qpad->expected_sample_duration_d *
2562 atom_trak_get_timescale (qpad->trak),
2563 qpad->expected_sample_duration_n);
2565 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2566 atom_trak_get_timescale (qpad->trak));
2569 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2577 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2582 GstClockTime input_timestamp;
2583 guint64 input_timestamp_distance;
2586 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2588 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2589 qtpad->expected_sample_duration_n,
2590 qtpad->expected_sample_duration_d *
2591 atom_trak_get_timescale (qtpad->trak));
2593 gst_util_uint64_scale (block_idx + 1,
2594 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2595 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2597 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2598 GST_COLLECT_PADS_STATE_EOS)
2599 && gst_adapter_available (qtpad->raw_audio_adapter) <
2600 nsamples * qtpad->sample_size)
2601 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2606 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2607 &input_timestamp_distance);
2608 if (input_timestamp != GST_CLOCK_TIME_NONE)
2610 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2611 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2614 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2615 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2616 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2617 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2618 GST_BUFFER_PTS (buf) = input_timestamp;
2619 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2620 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2622 qtpad->raw_audio_adapter_offset += nsamples;
2624 /* Check if we have yet another block of raw audio in the adapter */
2626 gst_util_uint64_scale (block_idx + 2,
2627 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2628 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2629 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2630 nsamples * qtpad->sample_size) {
2632 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2633 &input_timestamp_distance);
2634 if (input_timestamp != GST_CLOCK_TIME_NONE)
2636 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2637 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2638 qtpad->raw_audio_adapter_pts = input_timestamp;
2640 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2647 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2651 /* Find the (first) video track and assume that we have to output
2653 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2654 GstCollectData *cdata = (GstCollectData *) walk->data;
2655 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2657 if (tmp_qpad->trak->is_video) {
2658 *dur_n = tmp_qpad->expected_sample_duration_n;
2659 *dur_d = tmp_qpad->expected_sample_duration_d;
2665 GST_INFO_OBJECT (qtmux,
2666 "Found no video framerate, using 40ms audio buffers");
2672 /* Called when all pads are prerolled to adjust and */
2674 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2676 switch (qpad->fourcc) {
2684 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2685 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2691 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2692 /* We need a "valid" duration */
2693 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2694 &qpad->expected_sample_duration_d);
2695 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2700 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2701 &qpad->expected_sample_duration_d);
2702 /* Set a prepare_buf_func that ensures this */
2703 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2704 qpad->raw_audio_adapter = gst_adapter_new ();
2705 qpad->raw_audio_adapter_offset = 0;
2706 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2715 /* Only called at startup when doing the "fake" iteration of all tracks in order
2716 * to prefill the sample tables in the header. */
2718 find_best_pad_prefill_start (GstQTMux * qtmux)
2721 GstQTPad *best_pad = NULL;
2723 /* If interleave limits have been specified and the current pad is within
2724 * those interleave limits, pick that one, otherwise let's try to figure out
2725 * the next best one. */
2726 if (qtmux->current_pad &&
2727 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2728 (qtmux->interleave_bytes == 0
2729 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2730 && (qtmux->interleave_time == 0
2731 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2732 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2733 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2735 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2736 best_pad = qtmux->current_pad;
2738 } else if (qtmux->collect->data->next) {
2739 /* Attempt to try another pad if we have one. Otherwise use the only pad
2741 best_pad = qtmux->current_pad = NULL;
2744 /* The next best pad is the one which has the lowest timestamp and hasn't
2745 * exceeded the reserved max duration */
2747 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2749 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2750 GstCollectData *cdata = (GstCollectData *) walk->data;
2751 GstQTPad *qtpad = (GstQTPad *) cdata;
2752 GstClockTime timestamp;
2754 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2757 timestamp = qtpad->total_duration;
2759 if (best_pad == NULL ||
2760 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2762 best_time = timestamp;
2770 /* Called when starting the file in prefill_mode to figure out all the entries
2771 * of the header based on the input stream and reserved maximum duration.
2773 * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2774 * will be updated and written on EOS. */
2776 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2780 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2782 /* Update expected sample sizes/durations as needed, this is for raw
2783 * audio where samples are actual audio samples. */
2784 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2785 GstCollectData *cdata = (GstCollectData *) walk->data;
2786 GstQTPad *qpad = (GstQTPad *) cdata;
2788 if (!prefill_update_sample_size (qtmux, qpad))
2792 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2793 /* For the first sample check/update timecode as needed. We do that before
2794 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2795 * initial buffer directly, not with last_buf */
2796 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2797 GstCollectData *cdata = (GstCollectData *) walk->data;
2798 GstQTPad *qpad = (GstQTPad *) cdata;
2800 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2801 GstVideoTimeCodeMeta *tc_meta;
2803 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))
2804 && qpad->trak->is_video) {
2805 GstVideoTimeCode *tc = &tc_meta->tc;
2807 qpad->tc_trak = atom_trak_new (qtmux->context);
2808 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2810 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2811 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2813 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2814 qpad->trak->mdia.mdhd.time_info.timescale, tc);
2816 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2817 qtmux->mdat_size, FALSE, 0);
2819 qpad->tc_pos = qtmux->mdat_size;
2820 qpad->first_tc = gst_video_time_code_copy (tc);
2821 qpad->first_pts = GST_BUFFER_PTS (buffer);
2823 qtmux->current_chunk_offset = -1;
2824 qtmux->current_chunk_size = 0;
2825 qtmux->current_chunk_duration = 0;
2826 qtmux->mdat_size += 4;
2829 gst_buffer_unref (buffer);
2833 while ((qpad = find_best_pad_prefill_start (qtmux))) {
2834 GstClockTime timestamp, next_timestamp, duration;
2835 guint nsamples, sample_size;
2836 guint64 chunk_offset;
2837 gint64 scaled_duration;
2838 gint64 pts_offset = 0;
2839 gboolean sync = FALSE;
2840 TrakBufferEntryInfo sample_entry;
2842 sample_size = prefill_get_sample_size (qtmux, qpad);
2844 if (sample_size == -1) {
2849 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2851 timestamp = qpad->total_duration;
2852 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2853 duration = next_timestamp - timestamp;
2855 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2856 qpad->first_ts = timestamp;
2857 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2858 qpad->first_dts = timestamp;
2860 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2861 qtmux->current_pad = qpad;
2862 if (qtmux->current_chunk_offset == -1)
2863 qtmux->current_chunk_offset = qtmux->mdat_size;
2865 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2866 qtmux->current_chunk_size = 0;
2867 qtmux->current_chunk_duration = 0;
2869 if (qpad->sample_size)
2870 nsamples = sample_size / qpad->sample_size;
2873 qpad->last_dts = timestamp;
2874 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2875 atom_trak_get_timescale (qpad->trak),
2876 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2877 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2879 qtmux->current_chunk_size += sample_size;
2880 qtmux->current_chunk_duration += duration;
2881 qpad->total_bytes += sample_size;
2883 chunk_offset = qtmux->current_chunk_offset;
2885 /* I-frame only, no frame reordering */
2889 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2890 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2891 qtmux->longest_chunk = qtmux->current_chunk_duration;
2894 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2895 sample_entry.nsamples = nsamples;
2896 sample_entry.delta = scaled_duration / nsamples;
2897 sample_entry.size = sample_size / nsamples;
2898 sample_entry.chunk_offset = chunk_offset;
2899 sample_entry.pts_offset = pts_offset;
2900 sample_entry.sync = sync;
2901 sample_entry.do_pts = TRUE;
2902 g_array_append_val (qpad->samples, sample_entry);
2903 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2904 sample_size / nsamples, chunk_offset, sync, pts_offset);
2906 qpad->total_duration = next_timestamp;
2907 qtmux->mdat_size += sample_size;
2908 qpad->sample_offset += nsamples;
2914 static GstFlowReturn
2915 gst_qt_mux_start_file (GstQTMux * qtmux)
2917 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2918 GstFlowReturn ret = GST_FLOW_OK;
2922 GstClockTime reserved_max_duration;
2923 guint reserved_bytes_per_sec_per_trak;
2926 GST_DEBUG_OBJECT (qtmux, "starting file");
2928 GST_OBJECT_LOCK (qtmux);
2929 reserved_max_duration = qtmux->reserved_max_duration;
2930 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2931 GST_OBJECT_UNLOCK (qtmux);
2933 /* stream-start (FIXME: create id based on input ids) */
2934 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2935 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2937 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2938 /* qtmux has structure with and without variant, remove all but the first */
2939 while (gst_caps_get_size (caps) > 1)
2940 gst_caps_remove_structure (caps, 1);
2941 gst_pad_set_caps (qtmux->srcpad, caps);
2942 gst_caps_unref (caps);
2944 /* Default is 'normal' mode */
2945 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2947 /* Require a sensible fragment duration when muxing
2948 * using the ISML muxer */
2949 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2950 qtmux->fragment_duration == 0)
2953 if (qtmux->fragment_duration > 0) {
2954 if (qtmux->streamable)
2955 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2957 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2958 } else if (qtmux->fast_start) {
2959 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2960 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2961 if (qtmux->reserved_prefill)
2962 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2964 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2967 switch (qtmux->mux_mode) {
2968 case GST_QT_MUX_MODE_MOOV_AT_END:
2969 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2970 /* We have to be able to seek to rewrite the mdat header, or any
2971 * moov atom we write will not be visible in the file, because an
2972 * MDAT with 0 as the size covers the rest of the file. A file
2973 * with no moov is not playable, so error out now. */
2974 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2975 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2976 ("Downstream is not seekable - will not be able to create a playable file"),
2978 return GST_FLOW_ERROR;
2980 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
2981 GST_WARNING_OBJECT (qtmux,
2982 "Robust muxing requires reserved-moov-update-period to be set");
2985 case GST_QT_MUX_MODE_FAST_START:
2986 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2987 break; /* Don't need seekability, ignore */
2988 case GST_QT_MUX_MODE_FRAGMENTED:
2989 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2990 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2991 "streamable=false. Will ignore that and create streamable output "
2993 qtmux->streamable = TRUE;
2994 g_object_notify (G_OBJECT (qtmux), "streamable");
2997 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2998 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2999 GST_WARNING_OBJECT (qtmux,
3000 "downstream is not seekable, will not be able "
3001 "to trim samples table at the end if less than reserved-duration is "
3007 /* let downstream know we think in BYTES and expect to do seeking later on */
3008 gst_segment_init (&segment, GST_FORMAT_BYTES);
3009 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3011 GST_OBJECT_LOCK (qtmux);
3013 if (qtmux->timescale == 0) {
3014 guint32 suggested_timescale = 0;
3017 /* Calculate a reasonable timescale for the moov:
3018 * If there is video, it is the biggest video track timescale or an even
3019 * multiple of it if it's smaller than 1800.
3020 * Otherwise it is 1800 */
3021 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3022 GstCollectData *cdata = (GstCollectData *) walk->data;
3023 GstQTPad *qpad = (GstQTPad *) cdata;
3029 if (!qpad->trak->mdia.minf.vmhd)
3032 suggested_timescale =
3033 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3036 if (suggested_timescale == 0)
3037 suggested_timescale = 1800;
3039 while (suggested_timescale < 1800)
3040 suggested_timescale *= 2;
3042 qtmux->timescale = suggested_timescale;
3045 /* Set width/height/timescale of any closed caption tracks to that of the
3046 * first video track */
3048 guint video_width = 0, video_height = 0;
3049 guint32 video_timescale = 0;
3052 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3053 GstCollectData *cdata = (GstCollectData *) walk->data;
3054 GstQTPad *qpad = (GstQTPad *) cdata;
3059 /* Not closed caption */
3060 if (qpad->trak->mdia.hdlr.handler_type != FOURCC_clcp)
3063 if (video_width == 0 || video_height == 0 || video_timescale == 0) {
3066 for (walk2 = qtmux->sinkpads; walk2; walk2 = g_slist_next (walk2)) {
3067 GstCollectData *cdata2 = (GstCollectData *) walk2->data;
3068 GstQTPad *qpad2 = (GstQTPad *) cdata2;
3074 if (!qpad2->trak->mdia.minf.vmhd)
3077 video_width = qpad2->trak->tkhd.width;
3078 video_height = qpad2->trak->tkhd.height;
3079 video_timescale = qpad2->trak->mdia.mdhd.time_info.timescale;
3083 qpad->trak->tkhd.width = video_width << 16;
3084 qpad->trak->tkhd.height = video_height << 16;
3085 qpad->trak->mdia.mdhd.time_info.timescale = video_timescale;
3089 /* initialize our moov recovery file */
3090 if (qtmux->moov_recov_file_path) {
3091 gst_qt_mux_prepare_moov_recovery (qtmux);
3094 /* Make sure the first time we update the moov, we'll
3095 * include any tagsetter tags */
3096 qtmux->tags_changed = TRUE;
3098 GST_OBJECT_UNLOCK (qtmux);
3101 * send mdat header if already needed, and mark position for later update.
3102 * We don't send ftyp now if we are on fast start mode, because we can
3103 * better fine tune using the information we gather to create the whole moov
3106 switch (qtmux->mux_mode) {
3107 case GST_QT_MUX_MODE_MOOV_AT_END:
3108 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3109 if (ret != GST_FLOW_OK)
3112 /* Store this as the mdat offset for later updating
3113 * when we write the moov */
3114 qtmux->mdat_pos = qtmux->header_size;
3115 /* extended atom in case we go over 4GB while writing and need
3116 * the full 64-bit atom */
3118 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3121 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3122 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3123 if (ret != GST_FLOW_OK)
3126 /* Pad ftyp out to an 8-byte boundary before starting the moov
3127 * ping pong region. It should be well less than 1 disk sector,
3128 * unless there's a bajillion compatible types listed,
3129 * but let's be sure the free atom doesn't cross a sector
3130 * boundary anyway */
3131 if (qtmux->header_size % 8) {
3132 /* Extra 8 bytes for the padding free atom header */
3133 guint padding = (guint) (16 - (qtmux->header_size % 8));
3134 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3136 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3138 if (ret != GST_FLOW_OK)
3142 /* Store this as the moov offset for later updating.
3143 * We record mdat position below */
3144 qtmux->moov_pos = qtmux->header_size;
3146 /* Set up the initial 'ping' state of the ping-pong buffers */
3147 qtmux->reserved_moov_first_active = TRUE;
3149 gst_qt_mux_configure_moov (qtmux);
3150 gst_qt_mux_setup_metadata (qtmux);
3151 /* Empty free atom to begin, starting on an 8-byte boundary */
3152 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3153 if (ret != GST_FLOW_OK)
3155 /* Moov header, not padded yet */
3156 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3157 if (ret != GST_FLOW_OK)
3159 /* The moov we just sent contains the 'base' size of the moov, before
3160 * we put in any time-dependent per-trak data. Use that to make
3161 * a good estimate of how much extra to reserve */
3162 /* Calculate how much space to reserve for our MOOV atom.
3163 * We actually reserve twice that, for ping-pong buffers */
3164 qtmux->base_moov_size = qtmux->last_moov_size;
3165 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3166 qtmux->base_moov_size);
3167 qtmux->reserved_moov_size = qtmux->base_moov_size +
3168 gst_util_uint64_scale (reserved_max_duration,
3169 reserved_bytes_per_sec_per_trak *
3170 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3172 /* Need space for at least 4 atom headers. More really, but
3173 * this as an absolute minimum */
3174 if (qtmux->reserved_moov_size < 4 * 8)
3175 goto reserved_moov_too_small;
3177 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3178 2 * qtmux->reserved_moov_size + 16);
3180 GST_OBJECT_LOCK (qtmux);
3181 qtmux->reserved_duration_remaining =
3182 gst_util_uint64_scale (qtmux->reserved_moov_size -
3183 qtmux->base_moov_size, GST_SECOND,
3184 reserved_bytes_per_sec_per_trak *
3185 atom_moov_get_trak_count (qtmux->moov));
3186 GST_OBJECT_UNLOCK (qtmux);
3188 /* Now that we know how much reserved space is targetted,
3189 * output a free atom to fill the extra reserved */
3190 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3191 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3192 if (ret != GST_FLOW_OK)
3195 /* Then a free atom containing 'pong' buffer, with an
3196 * extra 8 bytes to account for the free atom header itself */
3197 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3198 qtmux->reserved_moov_size + 8, FALSE);
3199 if (ret != GST_FLOW_OK)
3202 /* extra atoms go after the free/moov(s), before the mdat */
3204 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3205 if (ret != GST_FLOW_OK)
3208 qtmux->mdat_pos = qtmux->header_size;
3209 /* extended atom in case we go over 4GB while writing and need
3210 * the full 64-bit atom */
3212 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3215 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3216 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3217 if (ret != GST_FLOW_OK)
3220 /* Store this as the moov offset for later updating.
3221 * We record mdat position below */
3222 qtmux->moov_pos = qtmux->header_size;
3224 if (!gst_qt_mux_prefill_samples (qtmux)) {
3225 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3226 ("Unsupported codecs or configuration for prefill mode"), (NULL));
3228 return GST_FLOW_ERROR;
3231 gst_qt_mux_update_global_statistics (qtmux);
3232 gst_qt_mux_configure_moov (qtmux);
3233 gst_qt_mux_update_edit_lists (qtmux);
3234 gst_qt_mux_setup_metadata (qtmux);
3236 /* Moov header with pre-filled samples */
3237 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3238 if (ret != GST_FLOW_OK)
3241 /* last_moov_size now contains the full size of the moov, moov_pos the
3242 * position. This allows us to rewrite it in the very end as needed */
3243 qtmux->reserved_moov_size =
3244 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3246 /* Send an additional free atom at the end so we definitely have space
3247 * to rewrite the moov header at the end and remove the samples that
3248 * were not actually written */
3250 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3251 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3252 if (ret != GST_FLOW_OK)
3255 /* extra atoms go after the free/moov(s), before the mdat */
3257 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3258 if (ret != GST_FLOW_OK)
3261 qtmux->mdat_pos = qtmux->header_size;
3263 /* And now send the mdat header */
3265 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3266 qtmux->mdat_size, TRUE, FALSE);
3268 /* chunks position is set relative to the first byte of the
3269 * MDAT atom payload. Set the overall offset into the file */
3270 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3275 gst_segment_init (&segment, GST_FORMAT_BYTES);
3276 segment.start = qtmux->moov_pos;
3277 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3279 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3280 if (ret != GST_FLOW_OK)
3283 segment.start = qtmux->header_size;
3284 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3287 qtmux->current_chunk_size = 0;
3288 qtmux->current_chunk_duration = 0;
3289 qtmux->current_chunk_offset = -1;
3290 qtmux->mdat_size = 0;
3291 qtmux->current_pad = NULL;
3292 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3294 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3295 GstCollectData *cdata = (GstCollectData *) walk->data;
3296 GstQTPad *qtpad = (GstQTPad *) cdata;
3298 qtpad->total_bytes = 0;
3299 qtpad->total_duration = 0;
3300 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3301 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3302 qtpad->sample_offset = 0;
3306 case GST_QT_MUX_MODE_FAST_START:
3307 GST_OBJECT_LOCK (qtmux);
3308 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3309 if (!qtmux->fast_start_file)
3311 GST_OBJECT_UNLOCK (qtmux);
3312 /* send a dummy buffer for preroll */
3313 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3315 case GST_QT_MUX_MODE_FRAGMENTED:
3316 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3317 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3318 if (ret != GST_FLOW_OK)
3320 /* store the moov pos so we can update the duration later
3321 * in non-streamable mode */
3322 qtmux->moov_pos = qtmux->header_size;
3324 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3325 qtmux->fragment_duration);
3326 /* also used as snapshot marker to indicate fragmented file */
3327 qtmux->fragment_sequence = 1;
3328 /* prepare moov and/or tags */
3329 gst_qt_mux_configure_moov (qtmux);
3330 gst_qt_mux_setup_metadata (qtmux);
3331 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3332 if (ret != GST_FLOW_OK)
3336 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3337 if (ret != GST_FLOW_OK)
3339 /* prepare index if not streamable */
3340 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3341 qtmux->mfra = atom_mfra_new (qtmux->context);
3349 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3350 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3351 return GST_FLOW_ERROR;
3353 reserved_moov_too_small:
3355 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3356 ("Not enough reserved space for creating headers"), (NULL));
3357 return GST_FLOW_ERROR;
3361 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3362 (("Could not open temporary file \"%s\""),
3363 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3364 GST_OBJECT_UNLOCK (qtmux);
3365 return GST_FLOW_ERROR;
3369 static GstFlowReturn
3370 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3372 GstFlowReturn ret = GST_FLOW_OK;
3375 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3376 GstCollectData *cdata = (GstCollectData *) walk->data;
3377 GstQTPad *qtpad = (GstQTPad *) cdata;
3379 /* avoid add_buffer complaining if not negotiated
3380 * in which case no buffers either, so skipping */
3381 if (!qtpad->fourcc) {
3382 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3383 GST_PAD_NAME (qtpad->collect.pad));
3387 /* send last buffer; also flushes possibly queued buffers/ts */
3388 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3389 GST_PAD_NAME (qtpad->collect.pad));
3390 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3391 if (ret != GST_FLOW_OK) {
3392 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3393 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3394 gst_flow_get_name (ret));
3402 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3406 /* for setting some subtitles fields */
3407 guint max_width = 0;
3408 guint max_height = 0;
3410 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3412 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3413 GstCollectData *cdata = (GstCollectData *) walk->data;
3414 GstQTPad *qtpad = (GstQTPad *) cdata;
3416 if (!qtpad->fourcc) {
3417 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3418 GST_PAD_NAME (qtpad->collect.pad));
3422 /* having flushed above, can check for buffers now */
3423 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3424 GstClockTime first_pts_in = qtpad->first_ts;
3425 /* it should be, since we got first_ts by adding adjustment
3426 * to a positive incoming PTS */
3427 if (qtpad->dts_adjustment <= first_pts_in)
3428 first_pts_in -= qtpad->dts_adjustment;
3429 /* determine max stream duration */
3430 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3431 || qtpad->last_dts > qtmux->last_dts) {
3432 qtmux->last_dts = qtpad->last_dts;
3434 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3435 || first_pts_in < qtmux->first_ts) {
3436 /* we need the original incoming PTS here, as this first_ts
3437 * is used in update_edit_lists to construct the edit list that arrange
3438 * for sync'ed streams. The first_ts is most likely obtained from
3439 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3440 * so it makes no difference, though it matters in other cases */
3441 qtmux->first_ts = first_pts_in;
3445 /* subtitles need to know the video width/height,
3446 * it is stored shifted 16 bits to the left according to the
3448 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3449 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3451 /* update average bitrate of streams if needed */
3453 guint32 avgbitrate = 0;
3454 guint32 maxbitrate = qtpad->max_bitrate;
3456 if (qtpad->avg_bitrate)
3457 avgbitrate = qtpad->avg_bitrate;
3458 else if (qtpad->total_duration > 0)
3459 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3460 8 * GST_SECOND, qtpad->total_duration);
3462 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3466 /* need to update values on subtitle traks now that we know the
3467 * max width and height */
3468 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3469 GstCollectData *cdata = (GstCollectData *) walk->data;
3470 GstQTPad *qtpad = (GstQTPad *) cdata;
3472 if (!qtpad->fourcc) {
3473 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3474 GST_PAD_NAME (qtpad->collect.pad));
3478 if (qtpad->fourcc == FOURCC_tx3g) {
3479 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3484 /* Called after gst_qt_mux_update_global_statistics() updates the
3485 * first_ts tracking, to create/set edit lists for delayed streams */
3487 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3491 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3492 GST_TIME_ARGS (qtmux->first_ts));
3493 /* add/update EDTSs for late streams. configure_moov will have
3494 * set the trak durations above by summing the sample tables,
3495 * here we extend that if needing to insert an empty segment */
3496 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3497 GstCollectData *cdata = (GstCollectData *) walk->data;
3498 GstQTPad *qtpad = (GstQTPad *) cdata;
3500 atom_trak_edts_clear (qtpad->trak);
3502 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3503 guint32 lateness = 0;
3504 guint32 duration = qtpad->trak->tkhd.duration;
3507 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3510 GstClockTime diff, trak_lateness;
3512 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3513 lateness = gst_util_uint64_scale_round (diff,
3514 qtmux->timescale, GST_SECOND);
3516 /* Allow up to 1 trak timescale unit of lateness, Such a small
3517 * timestamp/duration can't be represented by the trak-specific parts
3518 * of the headers anyway, so it's irrelevantly small */
3519 trak_lateness = gst_util_uint64_scale (diff,
3520 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3522 if (trak_lateness > 0 && diff > qtmux->start_gap_threshold) {
3523 GST_DEBUG_OBJECT (qtmux,
3524 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3525 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3527 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3528 (guint32) (1 * 65536.0));
3532 /* Always write an edit list for the whole track. In general this is not
3533 * necessary except for the case of having a gap or DTS adjustment but
3534 * it allows to give the whole track's duration in the usually more
3535 * accurate media timescale
3538 GstClockTime ctts = 0;
3539 guint32 media_start;
3541 if (qtpad->first_ts > qtpad->first_dts)
3542 ctts = qtpad->first_ts - qtpad->first_dts;
3544 media_start = gst_util_uint64_scale_round (ctts,
3545 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3547 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3548 * is empty because there's no gap added above, this call
3549 * will not replace index 1, it will create the entry at index 0.
3550 * Luckily, that's exactly what we want here */
3551 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3552 (guint32) (1 * 65536.0));
3555 /* need to add the empty time to the trak duration */
3556 duration += lateness;
3557 qtpad->trak->tkhd.duration = duration;
3558 if (qtpad->tc_trak) {
3559 qtpad->tc_trak->tkhd.duration = duration;
3560 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3563 /* And possibly grow the moov duration */
3564 if (duration > qtmux->moov->mvhd.time_info.duration) {
3565 qtmux->moov->mvhd.time_info.duration = duration;
3566 qtmux->moov->mvex.mehd.fragment_duration = duration;
3572 static GstFlowReturn
3573 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3578 guint64 offset = qtpad->tc_pos;
3579 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3581 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3584 g_assert (qtpad->tc_pos != -1);
3586 gst_segment_init (&segment, GST_FORMAT_BYTES);
3587 segment.start = offset;
3588 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3590 buf = gst_buffer_new_and_alloc (4);
3591 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3593 GST_WRITE_UINT32_BE (map.data,
3594 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3595 gst_buffer_unmap (buf, &map);
3597 /* Reset this value, so the timecode won't be re-rewritten */
3600 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3603 static GstFlowReturn
3604 gst_qt_mux_stop_file (GstQTMux * qtmux)
3606 gboolean ret = GST_FLOW_OK;
3607 guint64 offset = 0, size = 0;
3608 gboolean large_file;
3611 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3613 /* pushing last buffers for each pad */
3614 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3617 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3618 /* Streamable mode; no need to write duration or MFRA */
3619 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3623 gst_qt_mux_update_global_statistics (qtmux);
3624 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3625 GstQTPad *qtpad = (GstQTPad *) walk->data;
3627 if (qtpad->tc_pos != -1) {
3628 /* File is being stopped and timecode hasn't been updated. Update it now
3629 * with whatever we have */
3630 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3631 if (ret != GST_FLOW_OK)
3636 switch (qtmux->mux_mode) {
3637 case GST_QT_MUX_MODE_FRAGMENTED:{
3639 guint8 *data = NULL;
3643 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3644 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3645 goto serialize_error;
3646 buf = _gst_buffer_new_take_data (data, offset);
3647 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3648 if (ret != GST_FLOW_OK)
3651 /* only mvex duration is updated,
3652 * mvhd should be consistent with empty moov
3653 * (but TODO maybe some clients do not handle that well ?) */
3654 qtmux->moov->mvex.mehd.fragment_duration =
3655 gst_util_uint64_scale_round (qtmux->last_dts, qtmux->timescale,
3657 GST_DEBUG_OBJECT (qtmux,
3658 "rewriting moov with mvex duration %" GST_TIME_FORMAT,
3659 GST_TIME_ARGS (qtmux->last_dts));
3660 /* seek and rewrite the header */
3661 gst_segment_init (&segment, GST_FORMAT_BYTES);
3662 segment.start = qtmux->moov_pos;
3663 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3664 /* no need to seek back */
3665 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3667 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3668 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3669 if (G_UNLIKELY (ret != GST_FLOW_OK))
3671 /* Finalise by writing the final size into the mdat. Up until now
3672 * it's been 0, which means 'rest of the file'
3673 * No need to seek back after this, we won't write any more */
3674 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3675 qtmux->mdat_size, NULL, TRUE);
3677 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3679 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3681 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3682 GstCollectData *cdata = (GstCollectData *) walk->data;
3683 GstQTPad *qpad = (GstQTPad *) cdata;
3685 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3687 /* Get the block index of the last sample we wrote, not of the next
3688 * sample we would write */
3689 block_idx = prefill_get_block_index (qtmux, qpad);
3692 if (block_idx > 0) {
3694 guint64 nsamples = 0;
3697 n = atom_array_get_len (&stbl->stts.entries);
3698 for (i = 0; i < n; i++) {
3699 entry = &atom_array_index (&stbl->stts.entries, i);
3700 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3701 entry->sample_count = qpad->sample_offset - nsamples;
3702 stbl->stts.entries.len = i + 1;
3705 nsamples += entry->sample_count;
3709 stbl->stts.entries.len = 0;
3714 g_assert (stbl->stsz.entries.len == 0);
3715 stbl->stsz.table_size = qpad->sample_offset;
3721 guint64 nsamples = 0;
3722 gint chunk_index = 0;
3723 const TrakBufferEntryInfo *sample_entry;
3725 if (block_idx > 0) {
3727 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3730 n = stbl->stco64.entries.len;
3731 for (i = 0; i < n; i++) {
3732 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3734 if (*entry == sample_entry->chunk_offset) {
3735 stbl->stco64.entries.len = i + 1;
3736 chunk_index = i + 1;
3741 g_assert (chunk_index > 0);
3743 n = stbl->stsc.entries.len;
3744 for (i = 0; i < n; i++) {
3745 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3747 if (entry->first_chunk >= chunk_index)
3752 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3754 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3755 i - 1).samples_per_chunk;
3761 STSCEntry *prev_entry =
3762 &atom_array_index (&stbl->stsc.entries, i - 1);
3765 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3766 if (qpad->sample_offset - nsamples > 0) {
3767 stbl->stsc.entries.len = i;
3768 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3769 qpad->sample_offset - nsamples);
3771 stbl->stsc.entries.len = i;
3772 stbl->stco64.entries.len--;
3775 /* Everything in a single chunk */
3776 stbl->stsc.entries.len = 0;
3777 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3778 qpad->sample_offset);
3781 stbl->stco64.entries.len = 0;
3782 stbl->stsc.entries.len = 0;
3789 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3790 AtomTREX *trex = walk2->data;
3792 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3793 trex->track_ID = next_track_id;
3798 qpad->trak->tkhd.track_ID = next_track_id++;
3801 qtmux->moov->mvhd.next_track_id = next_track_id;
3803 gst_qt_mux_update_global_statistics (qtmux);
3804 gst_qt_mux_configure_moov (qtmux);
3806 gst_qt_mux_update_edit_lists (qtmux);
3808 /* Check if any gap edit lists were added. We don't have any space
3809 * reserved for this in the moov and the pre-finalized moov would have
3810 * broken A/V synchronization. Error out here now
3812 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3813 GstCollectData *cdata = (GstCollectData *) walk->data;
3814 GstQTPad *qpad = (GstQTPad *) cdata;
3816 if (qpad->trak->edts
3817 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3818 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3819 ("Can't support gaps in prefill mode"));
3821 return GST_FLOW_ERROR;
3825 gst_qt_mux_setup_metadata (qtmux);
3826 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3831 gst_segment_init (&segment, GST_FORMAT_BYTES);
3832 segment.start = qtmux->moov_pos;
3833 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3836 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3838 if (ret != GST_FLOW_OK)
3841 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3843 gst_qt_mux_send_free_atom (qtmux, NULL,
3844 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3847 if (ret != GST_FLOW_OK)
3851 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3852 qtmux->mdat_size, NULL, FALSE);
3859 /* Moov-at-end or fast-start mode from here down */
3860 gst_qt_mux_configure_moov (qtmux);
3862 gst_qt_mux_update_edit_lists (qtmux);
3864 /* tags into file metadata */
3865 gst_qt_mux_setup_metadata (qtmux);
3867 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3869 switch (qtmux->mux_mode) {
3870 case GST_QT_MUX_MODE_FAST_START:{
3871 /* if faststart, update the offset of the atoms in the movie with the offset
3872 * that the movie headers before mdat will cause.
3873 * Also, send the ftyp */
3876 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3877 if (ret != GST_FLOW_OK) {
3880 /* copy into NULL to obtain size */
3881 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3882 goto serialize_error;
3883 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3885 offset += qtmux->header_size + (large_file ? 16 : 8);
3887 /* sum up with the extra atoms size */
3888 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3889 if (ret != GST_FLOW_OK)
3894 offset = qtmux->header_size;
3898 /* Now that we know the size of moov + extra atoms, we can adjust
3899 * the chunk offsets stored into the moov */
3900 atom_moov_chunks_set_offset (qtmux->moov, offset);
3902 /* write out moov and extra atoms */
3903 /* note: as of this point, we no longer care about tracking written data size,
3904 * since there is no more use for it anyway */
3905 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3906 if (ret != GST_FLOW_OK)
3910 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3911 if (ret != GST_FLOW_OK)
3914 switch (qtmux->mux_mode) {
3915 case GST_QT_MUX_MODE_MOOV_AT_END:
3917 /* mdat needs update iff not using faststart */
3918 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3919 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3920 qtmux->mdat_size, NULL, FALSE);
3921 /* note; no seeking back to the end of file is done,
3922 * since we no longer write anything anyway */
3925 case GST_QT_MUX_MODE_FAST_START:
3927 /* send mdat atom and move buffered data into it */
3928 /* mdat_size = accumulated (buffered data) */
3929 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3931 if (ret != GST_FLOW_OK)
3933 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3934 if (ret != GST_FLOW_OK)
3939 g_assert_not_reached ();
3947 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3948 ("Failed to serialize moov"));
3949 return GST_FLOW_ERROR;
3953 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3954 return GST_FLOW_ERROR;
3958 static GstFlowReturn
3959 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3960 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3961 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3963 GstFlowReturn ret = GST_FLOW_OK;
3965 /* setup if needed */
3966 if (G_UNLIKELY (!pad->traf || force))
3970 /* flush pad fragment if threshold reached,
3971 * or at new keyframe if we should be minding those in the first place */
3972 if (G_UNLIKELY (force || (sync && pad->sync) ||
3973 pad->fragment_duration < (gint64) delta)) {
3975 guint64 size = 0, offset = 0;
3976 guint8 *data = NULL;
3978 guint i, total_size;
3980 /* now we know where moof ends up, update offset in tfra */
3982 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3984 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3985 /* takes ownership */
3986 atom_moof_add_traf (moof, pad->traf);
3988 atom_moof_copy_data (moof, &data, &size, &offset);
3989 buffer = _gst_buffer_new_take_data (data, offset);
3990 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3991 gst_buffer_get_size (buffer));
3992 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3994 /* and actual data */
3996 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3998 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
4001 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
4002 atom_array_get_len (&pad->fragment_buffers), total_size);
4003 if (ret == GST_FLOW_OK)
4004 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
4006 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4007 if (G_LIKELY (ret == GST_FLOW_OK))
4008 ret = gst_qt_mux_send_buffer (qtmux,
4009 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
4012 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4015 atom_array_clear (&pad->fragment_buffers);
4016 atom_moof_free (moof);
4017 qtmux->fragment_sequence++;
4022 if (G_UNLIKELY (!pad->traf)) {
4023 GST_LOG_OBJECT (qtmux, "setting up new fragment");
4024 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4025 atom_array_init (&pad->fragment_buffers, 512);
4026 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4027 atom_trak_get_timescale (pad->trak), 1000);
4029 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
4030 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
4031 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
4033 atom_traf_set_base_decode_time (pad->traf, dts);
4036 /* add buffer and metadata */
4037 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
4039 atom_array_append (&pad->fragment_buffers, buf, 256);
4040 pad->fragment_duration -= delta;
4043 guint32 sn = atom_traf_get_sample_num (pad->traf);
4045 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
4046 atom_tfra_add_entry (pad->tfra, dts, sn);
4049 if (G_UNLIKELY (force))
4055 /* Here's the clever bit of robust recording: Updating the moov
4056 * header is done using a ping-pong scheme inside 2 blocks of size
4057 * 'reserved_moov_size' at the start of the file, in such a way that the
4058 * file on-disk is always valid if interrupted.
4059 * Inside the reserved space, we have 2 pairs of free + moov atoms
4060 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4061 * at offset "reserved_moov_size".
4063 * 1. Free-A has 0 size payload, moov-A immediately after is
4064 * active/current, and is padded with an internal Free atom to
4065 * end at reserved_space/2. Free-B is at reserved_space/2, sized
4066 * to cover the remaining free space (including moov-B).
4067 * 2. We write moov-B (which is invisible inside free-B), and pad it to
4068 * end at the end of free space. Then, we update free-A to size
4069 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
4070 * free-B header, and makes moov-B active.
4071 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4072 * Change the size of free-A to make moov-A active again.
4073 * 4. Rinse and repeat.
4076 static GstFlowReturn
4077 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4081 guint64 freeA_offset;
4082 guint32 new_freeA_size;
4083 guint64 new_moov_offset;
4085 /* Update moov info, then seek and rewrite the MOOV atom */
4086 gst_qt_mux_update_global_statistics (qtmux);
4087 gst_qt_mux_configure_moov (qtmux);
4089 gst_qt_mux_update_edit_lists (qtmux);
4091 /* tags into file metadata */
4092 gst_qt_mux_setup_metadata (qtmux);
4094 /* chunks position is set relative to the first byte of the
4095 * MDAT atom payload. Set the overall offset into the file */
4096 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4098 /* Calculate which moov to rewrite. qtmux->moov_pos points to
4099 * the start of the free-A header */
4100 freeA_offset = qtmux->moov_pos;
4101 if (qtmux->reserved_moov_first_active) {
4102 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4103 /* After this, freeA will include itself, moovA, plus the freeB
4105 new_freeA_size = qtmux->reserved_moov_size + 16;
4107 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4110 /* the moov we update is after free-A, calculate its offset */
4111 new_moov_offset = freeA_offset + new_freeA_size;
4113 /* Swap ping-pong cadence marker */
4114 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4116 /* seek and rewrite the MOOV atom */
4117 gst_segment_init (&segment, GST_FORMAT_BYTES);
4118 segment.start = new_moov_offset;
4119 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4122 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4124 if (ret != GST_FLOW_OK)
4127 /* Update the estimated recording space remaining, based on amount used so
4128 * far and duration muxed so far */
4129 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4130 GstClockTime remain;
4131 GstClockTime time_muxed = qtmux->last_dts;
4134 gst_util_uint64_scale (qtmux->reserved_moov_size -
4135 qtmux->last_moov_size, time_muxed,
4136 qtmux->last_moov_size - qtmux->base_moov_size);
4137 /* Always under-estimate slightly, so users
4138 * have time to stop muxing before we run out */
4139 if (remain < GST_SECOND / 2)
4142 remain -= GST_SECOND / 2;
4144 GST_INFO_OBJECT (qtmux,
4145 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4146 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4147 qtmux->reserved_moov_size, qtmux->last_moov_size,
4148 GST_TIME_ARGS (qtmux->last_dts),
4149 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4151 GST_OBJECT_LOCK (qtmux);
4152 qtmux->reserved_duration_remaining = remain;
4153 qtmux->muxed_since_last_update = 0;
4154 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4155 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4156 GST_OBJECT_UNLOCK (qtmux);
4160 /* Now update the moov-A size. Don't pass offset, since we don't need
4161 * send_free_atom() to seek for us - all our callers seek back to
4162 * where they need after this, or they don't need it */
4163 gst_segment_init (&segment, GST_FORMAT_BYTES);
4164 segment.start = freeA_offset;
4165 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4167 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4172 static GstFlowReturn
4173 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4176 GstFlowReturn flow_ret;
4178 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4180 GST_OBJECT_LOCK (qtmux);
4182 /* Update the offset of how much we've muxed, so the
4183 * report of remaining space keeps counting down */
4184 if (position > qtmux->last_moov_update &&
4185 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4186 GST_LOG_OBJECT (qtmux,
4187 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4188 qtmux->muxed_since_last_update);
4189 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4192 /* Next, check if we're supposed to send periodic moov updates downstream */
4193 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4194 GST_OBJECT_UNLOCK (qtmux);
4198 /* Update if position is > the threshold or there's been no update yet */
4199 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4200 (position <= qtmux->last_moov_update ||
4201 (position - qtmux->last_moov_update) <
4202 qtmux->reserved_moov_update_period)) {
4203 GST_OBJECT_UNLOCK (qtmux);
4204 return GST_FLOW_OK; /* No update needed yet */
4207 qtmux->last_moov_update = position;
4208 GST_OBJECT_UNLOCK (qtmux);
4210 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4211 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4212 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4214 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4215 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4218 /* Seek back to previous position */
4219 gst_segment_init (&segment, GST_FORMAT_BYTES);
4220 segment.start = mdat_offset;
4221 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4226 static GstFlowReturn
4227 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4228 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4229 gint64 last_dts, gint64 scaled_duration, guint sample_size,
4230 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4232 GstFlowReturn ret = GST_FLOW_OK;
4234 /* note that a new chunk is started each time (not fancy but works) */
4235 if (qtmux->moov_recov_file) {
4236 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4237 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4238 do_pts, pts_offset)) {
4239 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4240 "recovery file, disabling recovery");
4241 fclose (qtmux->moov_recov_file);
4242 qtmux->moov_recov_file = NULL;
4246 switch (qtmux->mux_mode) {
4247 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4248 const TrakBufferEntryInfo *sample_entry;
4249 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4251 if (block_idx >= pad->samples->len) {
4252 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4253 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4254 block_idx, pad->samples->len));
4255 gst_buffer_unref (buffer);
4256 return GST_FLOW_ERROR;
4259 /* Check if all values are as expected */
4261 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4263 /* Allow +/- 1 difference for the scaled_duration to allow
4264 * for some rounding errors
4266 if (sample_entry->nsamples != nsamples
4267 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4268 || sample_entry->size != sample_size
4269 || sample_entry->chunk_offset != chunk_offset
4270 || sample_entry->pts_offset != pts_offset
4271 || sample_entry->sync != sync) {
4272 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4273 ("Unexpected values in sample %" G_GUINT64_FORMAT,
4274 pad->sample_offset + 1));
4275 GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4276 "chunk offset %" G_GUINT64_FORMAT ", "
4277 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4278 sample_entry->nsamples,
4279 sample_entry->delta,
4281 sample_entry->chunk_offset,
4282 sample_entry->pts_offset, sample_entry->sync);
4283 GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4284 "chunk offset %" G_GUINT64_FORMAT ", "
4285 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4287 (guint) scaled_duration,
4288 sample_size, chunk_offset, pts_offset, sync);
4290 gst_buffer_unref (buffer);
4291 return GST_FLOW_ERROR;
4294 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4297 case GST_QT_MUX_MODE_MOOV_AT_END:
4298 case GST_QT_MUX_MODE_FAST_START:
4299 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4300 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4301 sample_size, chunk_offset, sync, pts_offset);
4302 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4303 /* Check if it's time to re-write the headers in robust-recording mode */
4304 if (ret == GST_FLOW_OK
4305 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4306 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4308 case GST_QT_MUX_MODE_FRAGMENTED:
4309 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4310 /* ensure that always sync samples are marked as such */
4311 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4312 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4313 sample_size, !pad->sync || sync, pts_offset);
4321 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4322 guint buffer_size, GstClockTime duration)
4324 /* not that much happens here,
4325 * but updating any of this very likely needs to happen all in sync,
4326 * unless there is a very good reason not to */
4328 /* for computing the avg bitrate */
4329 pad->total_bytes += buffer_size;
4330 pad->total_duration += duration;
4331 /* for keeping track of where we are in chunk;
4332 * ensures that data really is located as recorded in atoms */
4333 qtmux->current_chunk_size += buffer_size;
4334 qtmux->current_chunk_duration += duration;
4337 static GstFlowReturn
4338 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4339 GstBuffer * buf, GstFlowReturn ret)
4341 GstVideoTimeCodeMeta *tc_meta;
4342 GstVideoTimeCode *tc;
4345 guint32 frames_since_daily_jam;
4346 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4348 if (!pad->trak->is_video)
4351 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4354 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4357 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4363 /* This means we never got a timecode before */
4364 if (pad->first_tc == NULL) {
4365 #ifndef GST_DISABLE_GST_DEBUG
4366 gchar *tc_str = gst_video_time_code_to_string (tc);
4367 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4370 g_assert (pad->tc_trak == NULL);
4371 pad->first_tc = gst_video_time_code_copy (tc);
4372 /* If frames are out of order, the frame we're currently getting might
4373 * not be the first one. Just write a 0 timecode for now and wait
4374 * until we receive a timecode that's lower than the current one */
4375 if (pad->is_out_of_order) {
4376 pad->first_pts = GST_BUFFER_PTS (buf);
4377 frames_since_daily_jam = 0;
4378 /* Position to rewrite */
4379 pad->tc_pos = qtmux->mdat_size;
4381 frames_since_daily_jam =
4382 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4383 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4385 /* Write the timecode trak now */
4386 pad->tc_trak = atom_trak_new (qtmux->context);
4387 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4389 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4390 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4392 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4393 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4395 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4396 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4397 g_assert (szret == 4);
4399 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4400 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4402 /* Need to reset the current chunk (of the previous pad) here because
4403 * some other data was written now above, and the pad has to start a
4405 qtmux->current_chunk_offset = -1;
4406 qtmux->current_chunk_size = 0;
4407 qtmux->current_chunk_duration = 0;
4408 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4409 frames_since_daily_jam =
4410 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4411 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4413 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4414 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4415 g_assert (szret == 4);
4417 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4420 qtmux->current_chunk_offset = -1;
4421 qtmux->current_chunk_size = 0;
4422 qtmux->current_chunk_duration = 0;
4423 } else if (pad->is_out_of_order) {
4424 /* Check for a lower timecode than the one stored */
4425 g_assert (pad->tc_trak != NULL);
4426 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4427 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4428 gst_video_time_code_free (pad->first_tc);
4429 pad->first_tc = gst_video_time_code_copy (tc);
4432 guint64 bk_size = qtmux->mdat_size;
4434 /* If this frame's DTS is after the first PTS received, it means
4435 * we've already received the first frame to be presented. Otherwise
4436 * the decoder would need to go back in time */
4437 gst_qt_mux_update_timecode (qtmux, pad);
4439 /* Reset writing position */
4440 gst_segment_init (&segment, GST_FORMAT_BYTES);
4441 segment.start = bk_size;
4442 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4450 * Here we push the buffer and update the tables in the track atoms
4452 static GstFlowReturn
4453 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4455 GstBuffer *last_buf = NULL;
4456 GstClockTime duration;
4457 guint nsamples, sample_size;
4458 guint64 chunk_offset;
4459 gint64 last_dts, scaled_duration;
4460 gint64 pts_offset = 0;
4461 gboolean sync = FALSE;
4462 GstFlowReturn ret = GST_FLOW_OK;
4466 goto not_negotiated;
4468 /* if this pad has a prepare function, call it */
4469 if (pad->prepare_buf_func != NULL) {
4472 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4473 if (buf && !new_buf)
4478 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4479 if (ret != GST_FLOW_OK) {
4481 gst_buffer_unref (buf);
4485 last_buf = pad->last_buf;
4486 pad->last_buf = buf;
4488 if (last_buf == NULL) {
4489 #ifndef GST_DISABLE_GST_DEBUG
4491 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4492 "received NULL buffer, doing nothing",
4493 GST_PAD_NAME (pad->collect.pad));
4495 GST_LOG_OBJECT (qtmux,
4496 "Pad %s has no previous buffer stored, storing now",
4497 GST_PAD_NAME (pad->collect.pad));
4503 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4506 /* if this is the first buffer, store the timestamp */
4507 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4508 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4509 pad->first_ts = GST_BUFFER_PTS (last_buf);
4510 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4511 pad->first_ts = GST_BUFFER_DTS (last_buf);
4514 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4515 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4516 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4517 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4520 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4521 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4523 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4524 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4525 pad->first_ts = pad->first_dts = 0;
4527 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4528 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4529 GST_TIME_ARGS (pad->first_ts));
4532 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4533 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4534 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4535 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4536 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4537 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4538 pad->last_buf = buf = gst_buffer_make_writable (buf);
4539 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4542 buffer_size = gst_buffer_get_size (last_buf);
4544 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4545 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4546 guint fill_size = required_buffer_size - buffer_size;
4550 if (required_buffer_size < buffer_size) {
4551 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4552 ("Sample size %u bigger than expected maximum %u", buffer_size,
4553 required_buffer_size));
4557 if (fill_size > 0) {
4558 GST_DEBUG_OBJECT (qtmux,
4559 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4560 required_buffer_size);
4561 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4562 gst_memory_map (mem, &map, GST_MAP_WRITE);
4563 memset (map.data, 0, map.size);
4564 gst_memory_unmap (mem, &map);
4565 last_buf = gst_buffer_make_writable (last_buf);
4566 gst_buffer_append_memory (last_buf, mem);
4567 buffer_size = required_buffer_size;
4571 /* duration actually means time delta between samples, so we calculate
4572 * the duration based on the difference in DTS or PTS, falling back
4573 * to DURATION if the other two don't exist, such as with the last
4574 * sample before EOS. Or use 0 if nothing else is available */
4575 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4576 duration = GST_BUFFER_DURATION (last_buf);
4580 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4581 && GST_BUFFER_DTS_IS_VALID (last_buf))
4582 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4583 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4584 && GST_BUFFER_PTS_IS_VALID (last_buf))
4585 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4588 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4589 GST_DEBUG_OBJECT (qtmux,
4590 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4591 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4592 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4593 qtmux->current_chunk_size,
4594 GST_TIME_ARGS (qtmux->current_chunk_duration));
4595 qtmux->current_pad = pad;
4596 if (qtmux->current_chunk_offset == -1)
4597 qtmux->current_chunk_offset = qtmux->mdat_size;
4599 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4600 qtmux->current_chunk_size = 0;
4601 qtmux->current_chunk_duration = 0;
4604 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4605 atom_trak_get_timescale (pad->trak), GST_SECOND);
4607 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4608 if (pad->sample_size && !qtmux->fragment_sequence) {
4609 GstClockTime expected_timestamp;
4611 /* Constant size packets: usually raw audio (with many samples per
4612 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4614 sample_size = pad->sample_size;
4615 if (buffer_size % sample_size != 0)
4616 goto fragmented_sample;
4618 /* note: qt raw audio storage warps it implicitly into a timewise
4619 * perfect stream, discarding buffer times.
4620 * If the difference between the current PTS and the expected one
4621 * becomes too big, we error out: there was a gap and we have no way to
4622 * represent that, causing A/V sync to be off */
4623 expected_timestamp =
4624 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4625 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4626 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4627 expected_timestamp) > qtmux->max_raw_audio_drift)
4628 goto raw_audio_timestamp_drift;
4630 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4631 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4632 atom_trak_get_timescale (pad->trak), GST_SECOND);
4633 duration = GST_BUFFER_DURATION (last_buf);
4635 nsamples = buffer_size / sample_size;
4637 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4638 atom_trak_get_timescale (pad->trak));
4641 /* timescale = samplerate */
4642 scaled_duration = 1;
4644 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4645 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4648 sample_size = buffer_size;
4649 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4650 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4652 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4653 pad->last_dts = GST_BUFFER_DTS (buf);
4655 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4657 if ((gint64) (pad->last_dts) < 0) {
4658 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4659 atom_trak_get_timescale (pad->trak), GST_SECOND);
4661 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4662 atom_trak_get_timescale (pad->trak), GST_SECOND);
4664 scaled_duration = scaled_dts - last_dts;
4665 last_dts = scaled_dts;
4667 /* first convert intended timestamp (in GstClockTime resolution) to
4668 * trak timescale, then derive delta;
4669 * this ensures sums of (scale)delta add up to converted timestamp,
4670 * which only deviates at most 1/scale from timestamp itself */
4671 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4672 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4673 pad->last_dts += duration;
4677 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4679 chunk_offset = qtmux->current_chunk_offset;
4681 GST_LOG_OBJECT (qtmux,
4682 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4683 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4684 GST_LOG_OBJECT (qtmux,
4685 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4686 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4687 nsamples, scaled_duration, sample_size, chunk_offset);
4689 /* might be a sync sample */
4691 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4692 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4693 GST_PAD_NAME (pad->collect.pad));
4697 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4698 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4699 atom_trak_get_timescale (pad->trak), GST_SECOND);
4701 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4702 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4705 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4706 atom_trak_get_timescale (pad->trak), GST_SECOND);
4708 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4709 " timebase_dts: %d pts_offset: %d",
4710 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4711 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4712 (int) (last_dts), (int) (pts_offset));
4714 if (GST_CLOCK_TIME_IS_VALID (duration)
4715 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4716 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4717 GST_DEBUG_OBJECT (qtmux,
4718 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4719 GST_TIME_ARGS (qtmux->current_chunk_duration),
4720 GST_PAD_NAME (pad->collect.pad));
4721 qtmux->longest_chunk = qtmux->current_chunk_duration;
4724 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4725 const TrakBufferEntryInfo *sample_entry;
4726 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4728 if (block_idx >= pad->samples->len) {
4729 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4730 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4731 block_idx, pad->samples->len));
4735 /* Check if all values are as expected */
4737 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4739 if (chunk_offset < sample_entry->chunk_offset) {
4740 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4741 GstBuffer *fill_buf;
4743 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4744 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4746 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4747 if (ret != GST_FLOW_OK)
4749 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4750 qtmux->current_chunk_size = buffer_size;
4751 qtmux->current_chunk_duration = duration;
4752 } else if (chunk_offset != sample_entry->chunk_offset) {
4753 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4754 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4755 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4760 /* now we go and register this buffer/sample all over */
4761 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4762 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4763 chunk_offset, sync, TRUE, pts_offset);
4764 pad->sample_offset += nsamples;
4766 /* if this is sparse and we have a next buffer, check if there is any gap
4767 * between them to insert an empty sample */
4768 if (pad->sparse && buf) {
4769 if (pad->create_empty_buffer) {
4770 GstBuffer *empty_buf;
4771 gint64 empty_duration =
4772 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4773 gint64 empty_duration_scaled;
4776 empty_buf = pad->create_empty_buffer (pad, empty_duration);
4778 pad->last_dts = GST_BUFFER_PTS (buf);
4779 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4780 atom_trak_get_timescale (pad->trak), GST_SECOND)
4781 - (last_dts + scaled_duration);
4782 empty_size = gst_buffer_get_size (empty_buf);
4784 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4788 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4789 last_dts + scaled_duration, empty_duration_scaled,
4790 empty_size, chunk_offset, sync, TRUE, 0);
4791 } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4792 /* This assert is kept here to make sure implementors of new
4793 * sparse input format decide whether there needs to be special
4794 * gap handling or not */
4795 g_assert_not_reached ();
4796 GST_WARNING_OBJECT (qtmux,
4797 "no empty buffer creation function found for pad %s",
4798 GST_PAD_NAME (pad->collect.pad));
4809 gst_buffer_unref (last_buf);
4810 return GST_FLOW_ERROR;
4814 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4815 ("Audio buffer contains fragmented sample."));
4818 raw_audio_timestamp_drift:
4820 /* TODO: Could in theory be implemented with edit lists */
4821 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4822 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4823 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4824 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4825 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4827 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4832 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4837 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4838 ("format wasn't negotiated before buffer flow on pad %s",
4839 GST_PAD_NAME (pad->collect.pad)));
4841 gst_buffer_unref (buf);
4842 return GST_FLOW_NOT_NEGOTIATED;
4847 * DTS running time can be negative. There is no way to represent that in
4848 * MP4 however, thus we need to offset DTS so that it starts from 0.
4851 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4852 GstCollectData * cdata, GstBuffer ** buf)
4857 pts = GST_BUFFER_PTS (*buf);
4858 dts = GST_COLLECT_PADS_DTS (cdata);
4860 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4861 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4862 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4864 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4865 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4866 pad->dts_adjustment = -dts;
4868 pad->dts_adjustment = 0;
4871 if (pad->dts_adjustment > 0) {
4872 *buf = gst_buffer_make_writable (*buf);
4874 dts += pad->dts_adjustment;
4876 if (GST_CLOCK_TIME_IS_VALID (pts))
4877 pts += pad->dts_adjustment;
4879 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4880 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4885 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4889 GST_BUFFER_PTS (*buf) = pts;
4890 GST_BUFFER_DTS (*buf) = dts;
4892 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4893 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4898 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4901 GstQTPad *best_pad = NULL;
4903 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4904 guint64 smallest_offset = G_MAXUINT64;
4905 guint64 chunk_offset = 0;
4907 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4908 GstCollectData *cdata = (GstCollectData *) walk->data;
4909 GstQTPad *qtpad = (GstQTPad *) cdata;
4910 const TrakBufferEntryInfo *sample_entry;
4911 guint64 block_idx, current_block_idx;
4912 guint64 chunk_offset_offset = 0;
4913 GstBuffer *tmp_buf =
4914 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4916 /* Check for EOS pads and just skip them */
4917 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4918 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4921 gst_buffer_unref (tmp_buf);
4923 /* Find the exact offset where the next sample of this track is supposed
4924 * to be written at */
4925 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4927 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4928 while (block_idx > 0) {
4929 const TrakBufferEntryInfo *tmp =
4930 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4932 if (tmp->chunk_offset != sample_entry->chunk_offset)
4934 chunk_offset_offset += tmp->size * tmp->nsamples;
4938 /* Except for the previously selected pad being EOS we always have
4939 * qtmux->current_chunk_offset + qtmux->current_chunk_size
4941 * sample_entry->chunk_offset + chunk_offset_offset
4942 * for the best pad. Instead of checking that, we just return the
4943 * pad that has the smallest offset for the next to-be-written sample.
4945 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4946 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4948 chunk_offset = sample_entry->chunk_offset;
4952 if (chunk_offset != qtmux->current_chunk_offset) {
4953 qtmux->current_pad = NULL;
4959 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4960 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4961 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4962 && (qtmux->interleave_time == 0
4963 || qtmux->current_chunk_duration <= qtmux->interleave_time)
4964 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4965 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4966 GstBuffer *tmp_buf =
4967 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4969 if (tmp_buf || qtmux->current_pad->last_buf) {
4970 best_pad = qtmux->current_pad;
4972 gst_buffer_unref (tmp_buf);
4973 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4974 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4976 } else if (qtmux->collect->data->next) {
4977 /* Only switch pads if we have more than one, otherwise
4978 * we can just put everything into a single chunk and save
4979 * a few bytes of offsets
4981 if (qtmux->current_pad)
4982 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4983 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4984 best_pad = qtmux->current_pad = NULL;
4988 GstClockTime best_time = GST_CLOCK_TIME_NONE;
4990 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4991 GstCollectData *cdata = (GstCollectData *) walk->data;
4992 GstQTPad *qtpad = (GstQTPad *) cdata;
4994 GstClockTime timestamp;
4996 tmp_buf = gst_collect_pads_peek (pads, cdata);
4998 /* This one is newly EOS now, finish it for real */
4999 if (qtpad->last_buf) {
5000 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5005 if (qtpad->last_buf)
5006 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5008 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
5011 if (best_pad == NULL ||
5012 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
5014 best_time = timestamp;
5018 gst_buffer_unref (tmp_buf);
5022 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
5023 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
5025 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
5032 static GstFlowReturn
5033 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
5035 GstFlowReturn ret = GST_FLOW_OK;
5036 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
5037 GstQTPad *best_pad = NULL;
5039 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
5040 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
5043 qtmux->state = GST_QT_MUX_STATE_DATA;
5046 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
5047 return GST_FLOW_EOS;
5049 best_pad = find_best_pad (qtmux, pads);
5051 /* clipping already converted to running time */
5052 if (best_pad != NULL) {
5053 GstBuffer *buf = NULL;
5055 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
5056 best_pad->raw_audio_adapter == NULL ||
5057 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
5058 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
5060 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
5061 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
5064 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
5065 (GstCollectData *) best_pad, &buf);
5067 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5069 qtmux->state = GST_QT_MUX_STATE_EOS;
5070 ret = gst_qt_mux_stop_file (qtmux);
5071 if (ret == GST_FLOW_OK) {
5072 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
5073 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5076 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5077 gst_flow_get_name (ret));
5085 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5087 GstStructure *structure = (GstStructure *) user_data;
5088 const GValue *other = gst_structure_id_get_value (structure, field_id);
5091 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5095 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5098 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5099 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5101 return gst_structure_foreach (sub_s, check_field, sup_s);
5104 /* will unref @qtmux */
5106 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5108 GstCaps *current_caps;
5110 /* does not go well to renegotiate stream mid-way, unless
5111 * the old caps are a subset of the new one (this means upstream
5112 * added more info to the caps, as both should be 'fixed' caps) */
5113 current_caps = gst_pad_get_current_caps (pad);
5114 g_assert (caps != NULL);
5116 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5117 gst_caps_unref (current_caps);
5118 GST_WARNING_OBJECT (qtmux,
5119 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5120 GST_PAD_NAME (pad), caps);
5121 gst_object_unref (qtmux);
5125 GST_DEBUG_OBJECT (qtmux,
5126 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5127 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5128 gst_object_unref (qtmux);
5129 gst_caps_unref (current_caps);
5135 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5137 GstPad *pad = qtpad->collect.pad;
5138 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5139 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5140 GstStructure *structure;
5141 const gchar *mimetype;
5142 gint rate, channels;
5143 const GValue *value = NULL;
5144 const GstBuffer *codec_data = NULL;
5145 GstQTMuxFormat format;
5146 AudioSampleEntry entry = { 0, };
5147 AtomInfo *ext_atom = NULL;
5148 gint constant_size = 0;
5149 const gchar *stream_format;
5153 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5155 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5156 GST_DEBUG_PAD_NAME (pad), caps);
5158 qtpad->prepare_buf_func = NULL;
5160 format = qtmux_klass->format;
5161 structure = gst_caps_get_structure (caps, 0);
5162 mimetype = gst_structure_get_name (structure);
5165 if (!gst_structure_get_int (structure, "channels", &channels) ||
5166 !gst_structure_get_int (structure, "rate", &rate)) {
5171 value = gst_structure_get_value (structure, "codec_data");
5173 codec_data = gst_value_get_buffer (value);
5175 qtpad->is_out_of_order = FALSE;
5177 /* set common properties */
5178 entry.sample_rate = rate;
5179 entry.channels = channels;
5181 entry.sample_size = 16;
5182 /* this is the typical compressed case */
5183 if (format == GST_QT_MUX_FORMAT_QT) {
5185 entry.compression_id = -2;
5188 /* now map onto a fourcc, and some extra properties */
5189 if (strcmp (mimetype, "audio/mpeg") == 0) {
5190 gint mpegversion = 0, mpegaudioversion = 0;
5193 gst_structure_get_int (structure, "mpegversion", &mpegversion);
5194 switch (mpegversion) {
5196 gst_structure_get_int (structure, "layer", &layer);
5197 gst_structure_get_int (structure, "mpegaudioversion",
5201 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5202 if (format == GST_QT_MUX_FORMAT_QT)
5203 entry.fourcc = FOURCC__mp3;
5205 entry.fourcc = FOURCC_mp4a;
5207 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5208 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5209 qtpad->max_bitrate);
5212 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5213 || format == GST_QT_MUX_FORMAT_QT);
5214 entry.samples_per_packet = 384;
5215 } else if (layer == 2) {
5216 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5217 || format == GST_QT_MUX_FORMAT_QT);
5218 entry.samples_per_packet = 1152;
5220 g_warn_if_fail (layer == 3);
5221 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5223 entry.bytes_per_sample = 2;
5227 /* check stream-format */
5228 stream_format = gst_structure_get_string (structure, "stream-format");
5229 if (stream_format) {
5230 if (strcmp (stream_format, "raw") != 0) {
5231 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5232 "please use 'raw'", stream_format);
5236 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5240 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5241 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5246 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5247 /* warn if not Low Complexity profile */
5250 GST_WARNING_OBJECT (qtmux,
5251 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5255 entry.fourcc = FOURCC_mp4a;
5257 if (format == GST_QT_MUX_FORMAT_QT)
5258 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5259 qtpad->avg_bitrate, qtpad->max_bitrate);
5262 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5263 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5264 qtpad->max_bitrate);
5269 } else if (strcmp (mimetype, "audio/AMR") == 0) {
5270 entry.fourcc = FOURCC_samr;
5271 entry.sample_size = 16;
5272 entry.samples_per_packet = 160;
5273 entry.bytes_per_sample = 2;
5274 ext_atom = build_amr_extension ();
5275 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5276 entry.fourcc = FOURCC_sawb;
5277 entry.sample_size = 16;
5278 entry.samples_per_packet = 320;
5279 entry.bytes_per_sample = 2;
5280 ext_atom = build_amr_extension ();
5281 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5284 gst_audio_info_init (&info);
5285 if (!gst_audio_info_from_caps (&info, caps))
5288 /* spec has no place for a distinction in these */
5289 if (info.finfo->width != info.finfo->depth) {
5290 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5294 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5295 if (info.finfo->endianness == G_LITTLE_ENDIAN)
5296 entry.fourcc = FOURCC_sowt;
5297 else if (info.finfo->endianness == G_BIG_ENDIAN)
5298 entry.fourcc = FOURCC_twos;
5300 entry.fourcc = FOURCC_sowt;
5301 /* maximum backward compatibility; only new version for > 16 bit */
5302 if (info.finfo->depth <= 16)
5304 /* not compressed in any case */
5305 entry.compression_id = 0;
5306 /* QT spec says: max at 16 bit even if sample size were actually larger,
5307 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5308 entry.sample_size = info.finfo->depth;
5309 entry.bytes_per_sample = info.finfo->depth / 8;
5310 entry.samples_per_packet = 1;
5311 entry.bytes_per_packet = info.finfo->depth / 8;
5312 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5314 if (info.finfo->width == 8 && info.finfo->depth == 8) {
5315 /* fall back to old 8-bit version */
5316 entry.fourcc = FOURCC_raw_;
5318 entry.compression_id = 0;
5319 entry.sample_size = 8;
5321 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5325 constant_size = (info.finfo->depth / 8) * info.channels;
5326 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5327 entry.fourcc = FOURCC_alaw;
5328 entry.samples_per_packet = 1023;
5329 entry.bytes_per_sample = 2;
5330 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5331 entry.fourcc = FOURCC_ulaw;
5332 entry.samples_per_packet = 1023;
5333 entry.bytes_per_sample = 2;
5334 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5336 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5337 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5340 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5342 entry.fourcc = MS_WAVE_FOURCC (0x11);
5343 /* 4 byte header per channel (including one sample). 2 samples per byte
5344 remaining. Simplifying gives the following (samples per block per
5346 entry.samples_per_packet = 2 * blocksize / channels - 7;
5347 entry.bytes_per_sample = 2;
5349 entry.bytes_per_frame = blocksize;
5350 entry.bytes_per_packet = blocksize / channels;
5351 /* ADPCM has constant size packets */
5353 /* TODO: I don't really understand why this helps, but it does! Constant
5354 * size and compression_id of -2 seem to be incompatible, and other files
5355 * in the wild use this too. */
5356 entry.compression_id = -1;
5358 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5359 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5360 GstBuffer *codec_config;
5364 entry.fourcc = FOURCC_alac;
5365 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5366 /* let's check if codec data already comes with 'alac' atom prefix */
5367 if (!codec_data || (len = map.size) < 28) {
5368 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5369 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5372 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5375 gst_buffer_copy_region ((GstBuffer *) codec_data,
5376 GST_BUFFER_COPY_MEMORY, 8, len);
5378 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5380 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5382 /* does not look good, but perhaps some trailing unneeded stuff */
5383 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5385 if (format == GST_QT_MUX_FORMAT_QT)
5386 ext_atom = build_mov_alac_extension (codec_config);
5388 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5389 /* set some more info */
5390 gst_buffer_map (codec_config, &map, GST_MAP_READ);
5391 entry.bytes_per_sample = 2;
5392 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5393 gst_buffer_unmap (codec_config, &map);
5394 gst_buffer_unref (codec_config);
5395 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5396 entry.fourcc = FOURCC_ac_3;
5398 /* Fixed values according to TS 102 366 but it also mentions that
5399 * they should be ignored */
5401 entry.sample_size = 16;
5403 /* AC-3 needs an extension atom but its data can only be obtained from
5404 * the stream itself. Abuse the prepare_buf_func so we parse a frame
5405 * and get the needed data */
5406 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5407 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5408 /* Based on the specification defined in:
5409 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5410 guint8 channels, mapping_family, stream_count, coupled_count;
5414 guint8 channel_mapping[256];
5415 const GValue *streamheader;
5416 const GValue *first_element;
5419 entry.fourcc = FOURCC_opus;
5420 entry.sample_size = 16;
5422 streamheader = gst_structure_get_value (structure, "streamheader");
5423 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5424 gst_value_array_get_size (streamheader) != 0) {
5425 first_element = gst_value_array_get_value (streamheader, 0);
5426 header = gst_value_get_buffer (first_element);
5427 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5428 &mapping_family, &stream_count, &coupled_count, channel_mapping,
5429 &pre_skip, &output_gain)) {
5430 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5434 GST_WARNING_OBJECT (qtmux,
5435 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5437 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5438 &mapping_family, &stream_count, &coupled_count,
5440 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5447 entry.channels = channels;
5448 ext_atom = build_opus_extension (rate, channels, mapping_family,
5449 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5455 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5456 if (!timescale && qtmux->trak_timescale)
5457 timescale = qtmux->trak_timescale;
5458 else if (!timescale)
5459 timescale = entry.sample_rate;
5461 /* ok, set the pad info accordingly */
5462 qtpad->fourcc = entry.fourcc;
5463 qtpad->sample_size = constant_size;
5465 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5466 qtmux->context, &entry, timescale, ext_atom, constant_size);
5468 gst_object_unref (qtmux);
5474 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5475 GST_PAD_NAME (pad), caps);
5476 gst_object_unref (qtmux);
5482 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5484 GstPad *pad = qtpad->collect.pad;
5485 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5486 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5487 GstStructure *structure;
5488 const gchar *mimetype;
5489 gint width, height, depth = -1;
5490 gint framerate_num, framerate_den;
5492 const GValue *value = NULL;
5493 const GstBuffer *codec_data = NULL;
5494 VisualSampleEntry entry = { 0, };
5495 GstQTMuxFormat format;
5496 AtomInfo *ext_atom = NULL;
5497 GList *ext_atom_list = NULL;
5498 gboolean sync = FALSE;
5499 int par_num, par_den;
5500 const gchar *multiview_mode;
5503 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5505 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5506 GST_DEBUG_PAD_NAME (pad), caps);
5508 qtpad->prepare_buf_func = NULL;
5510 format = qtmux_klass->format;
5511 structure = gst_caps_get_structure (caps, 0);
5512 mimetype = gst_structure_get_name (structure);
5514 /* required parts */
5515 if (!gst_structure_get_int (structure, "width", &width) ||
5516 !gst_structure_get_int (structure, "height", &height))
5521 /* works as a default timebase */
5522 framerate_num = 10000;
5524 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5526 gst_structure_get_int (structure, "depth", &depth);
5527 value = gst_structure_get_value (structure, "codec_data");
5529 codec_data = gst_value_get_buffer (value);
5533 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5536 qtpad->is_out_of_order = FALSE;
5538 /* bring frame numerator into a range that ensures both reasonable resolution
5539 * as well as a fair duration */
5540 qtpad->expected_sample_duration_n = framerate_num;
5541 qtpad->expected_sample_duration_d = framerate_den;
5543 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5544 if (!rate && qtmux->trak_timescale)
5545 rate = qtmux->trak_timescale;
5547 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5549 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5552 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5553 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5554 GstVideoMultiviewMode mode;
5555 GstVideoMultiviewFlags flags = 0;
5557 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5558 gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5560 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5561 qtpad->trak->mdia.minf.stbl.svmi =
5563 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5565 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5566 qtpad->trak->mdia.minf.stbl.svmi =
5568 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5570 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5571 qtpad->trak->mdia.minf.stbl.svmi =
5573 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5576 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5582 /* set common properties */
5583 entry.width = width;
5584 entry.height = height;
5585 entry.par_n = par_num;
5586 entry.par_d = par_den;
5587 /* should be OK according to qt and iso spec, override if really needed */
5588 entry.color_table_id = -1;
5589 entry.frame_count = 1;
5592 /* sync entries by default */
5595 /* now map onto a fourcc, and some extra properties */
5596 if (strcmp (mimetype, "video/x-raw") == 0) {
5597 const gchar *format;
5599 const GstVideoFormatInfo *vinfo;
5601 format = gst_structure_get_string (structure, "format");
5602 fmt = gst_video_format_from_string (format);
5603 vinfo = gst_video_format_get_info (fmt);
5606 case GST_VIDEO_FORMAT_UYVY:
5609 entry.fourcc = FOURCC_2vuy;
5610 entry.depth = depth;
5613 case GST_VIDEO_FORMAT_v210:
5616 entry.fourcc = FOURCC_v210;
5617 entry.depth = depth;
5621 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5622 entry.fourcc = FOURCC_raw_;
5623 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5628 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5630 if (format == GST_QT_MUX_FORMAT_QT)
5631 entry.fourcc = FOURCC_h263;
5633 entry.fourcc = FOURCC_s263;
5634 ext_atom = build_h263_extension ();
5635 if (ext_atom != NULL)
5636 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5637 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5638 strcmp (mimetype, "video/mpeg") == 0) {
5641 if (strcmp (mimetype, "video/x-divx") == 0) {
5642 gst_structure_get_int (structure, "divxversion", &version);
5643 version = version == 5 ? 1 : 0;
5645 gst_structure_get_int (structure, "mpegversion", &version);
5646 version = version == 4 ? 1 : 0;
5649 entry.fourcc = FOURCC_mp4v;
5651 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5652 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5653 qtpad->max_bitrate);
5654 if (ext_atom != NULL)
5655 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5657 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5658 "output might not play in Apple QuickTime (try global-headers?)");
5660 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5662 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5666 entry.fourcc = FOURCC_avc1;
5668 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5669 if (ext_atom != NULL)
5670 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5671 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5672 if (ext_atom != NULL)
5673 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5674 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5675 const gchar *format;
5678 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5682 format = gst_structure_get_string (structure, "stream-format");
5683 if (strcmp (format, "hvc1") == 0)
5684 entry.fourcc = FOURCC_hvc1;
5685 else if (strcmp (format, "hev1") == 0)
5686 entry.fourcc = FOURCC_hev1;
5688 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5689 if (ext_atom != NULL)
5690 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5692 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5693 if (ext_atom != NULL)
5694 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5696 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5698 const GstBuffer *seqh = NULL;
5699 const GValue *seqh_value;
5702 gst_structure_get_int (structure, "svqversion", &version);
5704 entry.fourcc = FOURCC_SVQ3;
5708 seqh_value = gst_structure_get_value (structure, "seqh");
5710 seqh = gst_value_get_buffer (seqh_value);
5711 ext_atom = build_SMI_atom (seqh);
5713 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5716 /* we need to add the gamma anyway because quicktime might crash
5717 * when it doesn't find it */
5718 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5719 /* it seems that using 0 here makes it ignored */
5722 ext_atom = build_gama_atom (gamma);
5724 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5726 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5727 "a bug at http://bugzilla.gnome.org", version);
5729 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5731 gboolean pal = TRUE;
5734 if (framerate_num != 25 || framerate_den != 1)
5736 gst_structure_get_int (structure, "dvversion", &version);
5737 /* fall back to typical one */
5743 entry.fourcc = FOURCC_dvcp;
5745 entry.fourcc = FOURCC_dvc_;
5749 entry.fourcc = FOURCC_dv5p;
5751 entry.fourcc = FOURCC_dv5n;
5754 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5757 } else if (strcmp (mimetype, "image/jpeg") == 0) {
5758 entry.fourcc = FOURCC_jpeg;
5760 } else if (strcmp (mimetype, "image/png") == 0) {
5761 entry.fourcc = FOURCC_png;
5763 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5764 strcmp (mimetype, "image/x-jpc") == 0) {
5765 const gchar *colorspace;
5766 const GValue *cmap_array;
5767 const GValue *cdef_array;
5770 if (strcmp (mimetype, "image/x-jpc") == 0) {
5771 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5774 gst_structure_get_int (structure, "num-components", &ncomp);
5775 cmap_array = gst_structure_get_value (structure, "component-map");
5776 cdef_array = gst_structure_get_value (structure, "channel-definitions");
5779 entry.fourcc = FOURCC_mjp2;
5782 colorspace = gst_structure_get_string (structure, "colorspace");
5785 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5786 cdef_array)) != NULL) {
5787 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5789 ext_atom = build_jp2x_extension (codec_data);
5791 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5793 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5796 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5797 entry.fourcc = FOURCC_vp08;
5798 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5799 entry.fourcc = FOURCC_vp09;
5800 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5801 entry.fourcc = FOURCC_drac;
5802 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5805 gst_structure_get_uint (structure, "format", &fourcc);
5806 entry.fourcc = fourcc;
5807 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5810 gst_structure_get_uint (structure, "format", &fourcc);
5811 entry.fourcc = fourcc;
5812 } else if (strcmp (mimetype, "video/x-prores") == 0) {
5813 const gchar *variant;
5815 variant = gst_structure_get_string (structure, "variant");
5816 if (!variant || !g_strcmp0 (variant, "standard"))
5817 entry.fourcc = FOURCC_apcn;
5818 else if (!g_strcmp0 (variant, "lt"))
5819 entry.fourcc = FOURCC_apcs;
5820 else if (!g_strcmp0 (variant, "hq"))
5821 entry.fourcc = FOURCC_apch;
5822 else if (!g_strcmp0 (variant, "proxy"))
5823 entry.fourcc = FOURCC_apco;
5824 else if (!g_strcmp0 (variant, "4444"))
5825 entry.fourcc = FOURCC_ap4h;
5826 else if (!g_strcmp0 (variant, "4444xq"))
5827 entry.fourcc = FOURCC_ap4x;
5831 if (!qtmux->interleave_time_set)
5832 qtmux->interleave_time = 500 * GST_MSECOND;
5833 if (!qtmux->interleave_bytes_set)
5834 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5835 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5836 entry.fourcc = FOURCC_cfhd;
5838 } else if (strcmp (mimetype, "video/x-av1") == 0) {
5839 gint presentation_delay;
5840 guint8 presentation_delay_byte = 0;
5841 GstBuffer *av1_codec_data;
5843 if (gst_structure_get_int (structure, "presentation-delay",
5844 &presentation_delay)) {
5845 presentation_delay_byte = 1 << 5;
5846 presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
5850 av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
5851 /* Fill version and 3 bytes of flags to 0 */
5852 gst_buffer_memset (av1_codec_data, 0, 0, 4);
5853 gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
5855 av1_codec_data = gst_buffer_append (av1_codec_data,
5856 gst_buffer_ref ((GstBuffer *) codec_data));
5858 entry.fourcc = FOURCC_av01;
5860 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5861 if (ext_atom != NULL)
5862 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5863 ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
5864 if (ext_atom != NULL)
5865 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5866 gst_buffer_unref (av1_codec_data);
5872 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5873 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5875 GstVideoColorimetry colorimetry;
5877 s = gst_structure_get_string (structure, "colorimetry");
5878 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5880 build_colr_extension (&colorimetry,
5881 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5883 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5887 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5888 || strcmp (mimetype, "image/x-j2c") == 0
5889 || strcmp (mimetype, "image/x-jpc") == 0) {
5891 GstVideoInterlaceMode interlace_mode;
5892 GstVideoFieldOrder field_order;
5895 if (strcmp (mimetype, "image/x-j2c") == 0 ||
5896 strcmp (mimetype, "image/x-jpc") == 0) {
5899 gst_structure_get_int (structure, "fields", &fields);
5902 s = gst_structure_get_string (structure, "interlace-mode");
5904 interlace_mode = gst_video_interlace_mode_from_string (s);
5908 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5909 GST_VIDEO_INTERLACE_MODE_MIXED;
5911 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5912 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5913 s = gst_structure_get_string (structure, "field-order");
5915 field_order = gst_video_field_order_from_string (s);
5918 ext_atom = build_fiel_extension (interlace_mode, field_order);
5920 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5924 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5925 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5926 /* The 'clap' extension is also defined for MP4 but inventing values in
5927 * general seems a bit tricky for this one. We only write it for
5928 * SD resolution in MOV, where it is a requirement.
5929 * The same goes for the 'tapt' extension, just that it is not defined for
5930 * MP4 and only for MOV
5932 gint dar_num, dar_den;
5933 gint clef_width, clef_height, prof_width;
5934 gint clap_width_n, clap_width_d, clap_height;
5938 /* First, guess display aspect ratio based on pixel aspect ratio,
5939 * width and height. We assume that display aspect ratio is either
5942 approx_dar = (gdouble) (width * par_num) / (height * par_den);
5943 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5946 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5950 dar_num = width * par_num;
5951 dar_den = height * par_den;
5952 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5957 /* Then, calculate clean-aperture values (clap and clef)
5958 * using the guessed DAR.
5960 clef_height = clap_height = (height == 486 ? 480 : height);
5961 clef_width = gst_util_uint64_scale (clef_height,
5962 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5963 prof_width = gst_util_uint64_scale (width,
5964 par_num * G_GUINT64_CONSTANT (65536), par_den);
5965 clap_width_n = clap_height * dar_num * par_den;
5966 clap_width_d = dar_den * par_num;
5967 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5968 clap_width_n /= cdiv;
5969 clap_width_d /= cdiv;
5971 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5972 height << 16, width << 16, height << 16);
5973 qtpad->trak->tapt = ext_atom;
5975 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5976 clap_height, 1, 0, 1, 0, 1);
5978 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5981 /* ok, set the pad info accordingly */
5982 qtpad->fourcc = entry.fourcc;
5985 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5986 qtmux->context, &entry, rate, ext_atom_list);
5987 if (strcmp (mimetype, "video/x-prores") == 0) {
5988 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5989 const gchar *compressor = NULL;
5990 mp4v->spatial_quality = 0x3FF;
5991 mp4v->temporal_quality = 0;
5992 mp4v->vendor = FOURCC_appl;
5993 mp4v->horizontal_resolution = 72 << 16;
5994 mp4v->vertical_resolution = 72 << 16;
5995 mp4v->depth = (entry.fourcc == FOURCC_ap4h
5996 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5998 /* Set compressor name, required by some software */
5999 switch (entry.fourcc) {
6001 compressor = "Apple ProRes 422";
6004 compressor = "Apple ProRes 422 LT";
6007 compressor = "Apple ProRes 422 HQ";
6010 compressor = "Apple ProRes 422 Proxy";
6013 compressor = "Apple ProRes 4444";
6016 compressor = "Apple ProRes 4444 XQ";
6020 strcpy ((gchar *) mp4v->compressor + 1, compressor);
6021 mp4v->compressor[0] = strlen (compressor);
6025 gst_object_unref (qtmux);
6031 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6032 GST_PAD_NAME (pad), caps);
6033 gst_object_unref (qtmux);
6039 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6041 GstPad *pad = qtpad->collect.pad;
6042 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6043 GstStructure *structure;
6044 SubtitleSampleEntry entry = { 0, };
6047 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6049 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6050 GST_DEBUG_PAD_NAME (pad), caps);
6052 /* subtitles default */
6053 subtitle_sample_entry_init (&entry);
6054 qtpad->is_out_of_order = FALSE;
6055 qtpad->sync = FALSE;
6056 qtpad->sparse = TRUE;
6057 qtpad->prepare_buf_func = NULL;
6059 structure = gst_caps_get_structure (caps, 0);
6061 if (gst_structure_has_name (structure, "text/x-raw")) {
6062 const gchar *format = gst_structure_get_string (structure, "format");
6063 if (format && strcmp (format, "utf8") == 0) {
6064 entry.fourcc = FOURCC_tx3g;
6065 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6066 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6073 qtpad->fourcc = entry.fourcc;
6075 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6076 qtmux->context, &entry);
6078 gst_object_unref (qtmux);
6084 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6085 GST_PAD_NAME (pad), caps);
6086 gst_object_unref (qtmux);
6092 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6094 GstPad *pad = qtpad->collect.pad;
6095 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6096 GstStructure *structure;
6097 guint32 fourcc_entry;
6101 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6103 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6104 GST_DEBUG_PAD_NAME (pad), caps);
6106 /* captions default */
6107 qtpad->is_out_of_order = FALSE;
6108 qtpad->sync = FALSE;
6109 qtpad->sparse = TRUE;
6110 /* Closed caption data are within atoms */
6111 qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6113 structure = gst_caps_get_structure (caps, 0);
6115 /* We know we only handle 608,format=s334-1a and 708,format=cdp */
6116 if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6117 fourcc_entry = FOURCC_c608;
6118 } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6119 fourcc_entry = FOURCC_c708;
6123 /* We set the real timescale later to the one from the video track when
6124 * writing the headers */
6125 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6126 if (!timescale && qtmux->trak_timescale)
6127 timescale = qtmux->trak_timescale;
6128 else if (!timescale)
6131 qtpad->fourcc = fourcc_entry;
6133 (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6134 qtmux->context, timescale, fourcc_entry);
6136 /* Initialize caption track language code to 0 unless something else is
6137 * specified. Without this, Final Cut considers it "non-standard"
6139 qtpad->trak->mdia.mdhd.language_code = 0;
6141 gst_object_unref (qtmux);
6147 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6148 GST_PAD_NAME (pad), caps);
6149 gst_object_unref (qtmux);
6155 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6156 GstEvent * event, gpointer user_data)
6159 guint32 avg_bitrate = 0, max_bitrate = 0;
6160 GstPad *pad = data->pad;
6161 gboolean ret = TRUE;
6163 qtmux = GST_QT_MUX_CAST (user_data);
6164 switch (GST_EVENT_TYPE (event)) {
6165 case GST_EVENT_CAPS:
6168 GstQTPad *collect_pad;
6170 gst_event_parse_caps (event, &caps);
6172 /* find stream data */
6173 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6174 g_assert (collect_pad);
6175 g_assert (collect_pad->set_caps);
6177 ret = collect_pad->set_caps (collect_pad, caps);
6178 gst_event_unref (event);
6182 case GST_EVENT_TAG:{
6184 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6185 GstTagMergeMode mode;
6187 GstQTPad *collect_pad;
6189 GST_OBJECT_LOCK (qtmux);
6190 mode = gst_tag_setter_get_tag_merge_mode (setter);
6191 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6193 gst_event_parse_tag (event, &list);
6194 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6195 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6197 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6198 gst_tag_setter_merge_tags (setter, list, mode);
6199 qtmux->tags_changed = TRUE;
6201 if (!collect_pad->tags)
6202 collect_pad->tags = gst_tag_list_new_empty ();
6203 gst_tag_list_insert (collect_pad->tags, list, mode);
6204 collect_pad->tags_changed = TRUE;
6206 GST_OBJECT_UNLOCK (qtmux);
6208 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6209 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6210 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6213 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6214 qtpad->avg_bitrate = avg_bitrate;
6215 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6216 qtpad->max_bitrate = max_bitrate;
6219 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6220 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6222 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6225 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6226 qtpad->trak->mdia.mdhd.language_code = language_code (iso_code);
6232 gst_event_unref (event);
6242 return gst_collect_pads_event_default (pads, data, event, FALSE);
6248 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6250 GstQTMux *mux = GST_QT_MUX_CAST (element);
6253 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6255 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6256 GstQTPad *qtpad = (GstQTPad *) walk->data;
6257 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6258 if (qtpad->collect.pad == pad) {
6259 /* this is it, remove */
6260 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6261 gst_element_remove_pad (element, pad);
6266 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6267 mux->current_pad = NULL;
6268 mux->current_chunk_size = 0;
6269 mux->current_chunk_duration = 0;
6272 gst_collect_pads_remove_pad (mux->collect, pad);
6274 if (mux->sinkpads == NULL) {
6275 /* No more outstanding request pads, reset our counters */
6276 mux->video_pads = 0;
6277 mux->audio_pads = 0;
6278 mux->subtitle_pads = 0;
6283 gst_qt_mux_request_new_pad (GstElement * element,
6284 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6286 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6287 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6288 GstQTPad *collect_pad;
6290 GstQTPadSetCapsFunc setcaps_func;
6293 gboolean lock = TRUE;
6295 if (templ->direction != GST_PAD_SINK)
6296 goto wrong_direction;
6298 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6301 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6302 setcaps_func = gst_qt_mux_audio_sink_set_caps;
6303 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6304 name = g_strdup (req_name);
6306 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6308 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6309 setcaps_func = gst_qt_mux_video_sink_set_caps;
6310 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6311 name = g_strdup (req_name);
6313 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6315 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6316 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6317 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6318 name = g_strdup (req_name);
6320 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6323 } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6324 setcaps_func = gst_qt_mux_caption_sink_set_caps;
6325 if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6326 name = g_strdup (req_name);
6328 name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6332 goto wrong_template;
6334 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6336 /* create pad and add to collections */
6338 g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6339 templ->direction, "template", templ, NULL);
6341 collect_pad = (GstQTPad *)
6342 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6343 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6345 gst_qt_mux_pad_reset (collect_pad);
6346 collect_pad->trak = atom_trak_new (qtmux->context);
6347 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6349 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6351 /* set up pad functions */
6352 collect_pad->set_caps = setcaps_func;
6354 gst_pad_set_active (newpad, TRUE);
6355 gst_element_add_pad (element, newpad);
6362 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6367 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6372 GST_WARNING_OBJECT (qtmux, "This is not our template!");
6378 gst_qt_mux_get_property (GObject * object,
6379 guint prop_id, GValue * value, GParamSpec * pspec)
6381 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6383 GST_OBJECT_LOCK (qtmux);
6385 case PROP_MOVIE_TIMESCALE:
6386 g_value_set_uint (value, qtmux->timescale);
6388 case PROP_TRAK_TIMESCALE:
6389 g_value_set_uint (value, qtmux->trak_timescale);
6392 g_value_set_boolean (value, qtmux->guess_pts);
6394 #ifndef GST_REMOVE_DEPRECATED
6395 case PROP_DTS_METHOD:
6396 g_value_set_enum (value, qtmux->dts_method);
6399 case PROP_FAST_START:
6400 g_value_set_boolean (value, qtmux->fast_start);
6402 case PROP_FAST_START_TEMP_FILE:
6403 g_value_set_string (value, qtmux->fast_start_file_path);
6405 case PROP_MOOV_RECOV_FILE:
6406 g_value_set_string (value, qtmux->moov_recov_file_path);
6408 case PROP_FRAGMENT_DURATION:
6409 g_value_set_uint (value, qtmux->fragment_duration);
6411 case PROP_STREAMABLE:
6412 g_value_set_boolean (value, qtmux->streamable);
6414 case PROP_RESERVED_MAX_DURATION:
6415 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6417 case PROP_RESERVED_DURATION_REMAINING:
6418 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6419 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6421 GstClockTime remaining = qtmux->reserved_duration_remaining;
6423 /* Report the remaining space as the calculated remaining, minus
6424 * however much we've muxed since the last update */
6425 if (remaining > qtmux->muxed_since_last_update)
6426 remaining -= qtmux->muxed_since_last_update;
6429 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6430 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6431 remaining, qtmux->reserved_duration_remaining,
6432 qtmux->muxed_since_last_update);
6433 g_value_set_uint64 (value, remaining);
6436 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6437 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6439 case PROP_RESERVED_BYTES_PER_SEC:
6440 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6442 case PROP_RESERVED_PREFILL:
6443 g_value_set_boolean (value, qtmux->reserved_prefill);
6445 case PROP_INTERLEAVE_BYTES:
6446 g_value_set_uint64 (value, qtmux->interleave_bytes);
6448 case PROP_INTERLEAVE_TIME:
6449 g_value_set_uint64 (value, qtmux->interleave_time);
6451 case PROP_MAX_RAW_AUDIO_DRIFT:
6452 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6454 case PROP_START_GAP_THRESHOLD:
6455 g_value_set_uint64 (value, qtmux->start_gap_threshold);
6458 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6461 GST_OBJECT_UNLOCK (qtmux);
6465 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6469 g_free (qtmux->fast_start_file_path);
6470 qtmux->fast_start_file_path = NULL;
6472 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6473 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6478 gst_qt_mux_set_property (GObject * object,
6479 guint prop_id, const GValue * value, GParamSpec * pspec)
6481 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6483 GST_OBJECT_LOCK (qtmux);
6485 case PROP_MOVIE_TIMESCALE:
6486 qtmux->timescale = g_value_get_uint (value);
6488 case PROP_TRAK_TIMESCALE:
6489 qtmux->trak_timescale = g_value_get_uint (value);
6492 qtmux->guess_pts = g_value_get_boolean (value);
6494 #ifndef GST_REMOVE_DEPRECATED
6495 case PROP_DTS_METHOD:
6496 qtmux->dts_method = g_value_get_enum (value);
6499 case PROP_FAST_START:
6500 qtmux->fast_start = g_value_get_boolean (value);
6502 case PROP_FAST_START_TEMP_FILE:
6503 g_free (qtmux->fast_start_file_path);
6504 qtmux->fast_start_file_path = g_value_dup_string (value);
6505 /* NULL means to generate a random one */
6506 if (!qtmux->fast_start_file_path) {
6507 gst_qt_mux_generate_fast_start_file_path (qtmux);
6510 case PROP_MOOV_RECOV_FILE:
6511 g_free (qtmux->moov_recov_file_path);
6512 qtmux->moov_recov_file_path = g_value_dup_string (value);
6514 case PROP_FRAGMENT_DURATION:
6515 qtmux->fragment_duration = g_value_get_uint (value);
6517 case PROP_STREAMABLE:{
6518 GstQTMuxClass *qtmux_klass =
6519 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6520 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6521 qtmux->streamable = g_value_get_boolean (value);
6525 case PROP_RESERVED_MAX_DURATION:
6526 qtmux->reserved_max_duration = g_value_get_uint64 (value);
6528 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6529 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6531 case PROP_RESERVED_BYTES_PER_SEC:
6532 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6534 case PROP_RESERVED_PREFILL:
6535 qtmux->reserved_prefill = g_value_get_boolean (value);
6537 case PROP_INTERLEAVE_BYTES:
6538 qtmux->interleave_bytes = g_value_get_uint64 (value);
6539 qtmux->interleave_bytes_set = TRUE;
6541 case PROP_INTERLEAVE_TIME:
6542 qtmux->interleave_time = g_value_get_uint64 (value);
6543 qtmux->interleave_time_set = TRUE;
6545 case PROP_MAX_RAW_AUDIO_DRIFT:
6546 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6548 case PROP_START_GAP_THRESHOLD:
6549 qtmux->start_gap_threshold = g_value_get_uint64 (value);
6552 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6555 GST_OBJECT_UNLOCK (qtmux);
6558 static GstStateChangeReturn
6559 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6561 GstStateChangeReturn ret;
6562 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6564 switch (transition) {
6565 case GST_STATE_CHANGE_NULL_TO_READY:
6567 case GST_STATE_CHANGE_READY_TO_PAUSED:
6568 gst_collect_pads_start (qtmux->collect);
6569 qtmux->state = GST_QT_MUX_STATE_STARTED;
6571 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6573 case GST_STATE_CHANGE_PAUSED_TO_READY:
6574 gst_collect_pads_stop (qtmux->collect);
6580 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6582 switch (transition) {
6583 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6585 case GST_STATE_CHANGE_PAUSED_TO_READY:
6586 gst_qt_mux_reset (qtmux, TRUE);
6588 case GST_STATE_CHANGE_READY_TO_NULL:
6598 gst_qt_mux_register (GstPlugin * plugin)
6600 GTypeInfo typeinfo = {
6601 sizeof (GstQTMuxClass),
6602 (GBaseInitFunc) gst_qt_mux_base_init,
6604 (GClassInitFunc) gst_qt_mux_class_init,
6609 (GInstanceInitFunc) gst_qt_mux_init,
6611 static const GInterfaceInfo tag_setter_info = {
6614 static const GInterfaceInfo tag_xmp_writer_info = {
6617 static const GInterfaceInfo preset_info = {
6621 GstQTMuxFormat format;
6622 GstQTMuxClassParams *params;
6625 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6627 GST_LOG ("Registering muxers");
6630 GstQTMuxFormatProp *prop;
6631 GstCaps *subtitle_caps, *caption_caps;
6633 prop = &gst_qt_mux_format_list[i];
6634 format = prop->format;
6635 if (format == GST_QT_MUX_FORMAT_NONE)
6638 /* create a cache for these properties */
6639 params = g_new0 (GstQTMuxClassParams, 1);
6640 params->prop = prop;
6641 params->src_caps = gst_static_caps_get (&prop->src_caps);
6642 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6643 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6644 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6645 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6646 params->subtitle_sink_caps = subtitle_caps;
6648 gst_caps_unref (subtitle_caps);
6650 caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6651 if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6652 params->caption_sink_caps = caption_caps;
6654 gst_caps_unref (caption_caps);
6657 /* create the type now */
6658 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6660 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6661 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6662 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6663 &tag_xmp_writer_info);
6664 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6666 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6672 GST_LOG ("Finished registering muxers");
6674 /* FIXME: ideally classification tag should be added and
6675 registered in gstreamer core gsttaglist
6678 GST_LOG ("Registering tags");
6680 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6681 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6682 gst_tag_merge_use_first);
6684 GST_LOG ("Finished registering tags");