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,
401 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
402 PROP_EXPECTED_TRAILER_SIZE,
403 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
406 /* some spare for header size as well */
407 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
409 #define DEFAULT_MOVIE_TIMESCALE 0
410 #define DEFAULT_TRAK_TIMESCALE 0
411 #define DEFAULT_DO_CTTS TRUE
412 #define DEFAULT_FAST_START FALSE
413 #define DEFAULT_FAST_START_TEMP_FILE NULL
414 #define DEFAULT_MOOV_RECOV_FILE NULL
415 #define DEFAULT_FRAGMENT_DURATION 0
416 #define DEFAULT_STREAMABLE TRUE
417 #ifndef GST_REMOVE_DEPRECATED
418 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
420 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
421 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
422 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
423 #define DEFAULT_RESERVED_PREFILL FALSE
424 #define DEFAULT_INTERLEAVE_BYTES 0
425 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
426 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
427 #define DEFAULT_START_GAP_THRESHOLD 0
429 static void gst_qt_mux_finalize (GObject * object);
431 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
432 GstStateChange transition);
434 /* property functions */
435 static void gst_qt_mux_set_property (GObject * object,
436 guint prop_id, const GValue * value, GParamSpec * pspec);
437 static void gst_qt_mux_get_property (GObject * object,
438 guint prop_id, GValue * value, GParamSpec * pspec);
441 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
442 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
443 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
446 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
447 GstCollectData * data, GstEvent * event, gpointer user_data);
449 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
451 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
455 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
457 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
458 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
460 static GstElementClass *parent_class = NULL;
462 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
481 dinf = 36 (8, dref : 16 , url : 12)
486 ii. Variation in file format
494 iii. Variation in codec
496 stsd = 137(16, mp4v : 86, esds : 35)
498 - H.264 = 487(or 489) + (8*stts_count) + (8*frame) + (4*I-frame)
499 stsd = 134 (SPS 9, PPS 4) or 136 (SPS 111, PPS 4)
501 - H.263 = 470 + + (8*stts_count) + (8*frame) + (4*I-frame)
502 stsd = 102 -> different from H.264
504 iv. Variation in frame
505 stts = 16 + (8*stts_count)
506 stss = 16 + (4*I-frame)
508 stsz = 20 + (4*frame)
509 stco = 16 + (4*frame)
520 dinf = 36 (8, dref : 16, url : 12)
531 ii. Variation in file format
537 iii. Variation in codec
539 stts = 16 + (8*stts_count)
541 stsz = 20 + (4*frame)
542 stco = 16 + (4*frame)
545 stsd = 94 (16, mp4a : 78(36 ,esds : 42))
548 stsd = 69 (16, samr : 53(36, damr : 17))
551 /* trailer entry size */
552 #define ENTRY_SIZE_VIDEO_STTS 8
553 #define ENTRY_SIZE_VIDEO_STSS 4
554 #define ENTRY_SIZE_VIDEO_STSZ 4
555 #define ENTRY_SIZE_VIDEO_STCO 4
556 #define ENTRY_SIZE_AUDIO_STTS 8
557 #define ENTRY_SIZE_AUDIO_STSZ 4
558 #define ENTRY_SIZE_AUDIO_STCO 4
560 #define ENTRY_SIZE_VIDEO_MPEG4_STSD 137
561 #define ENTRY_SIZE_VIDEO_H263P_STSD 102
562 #define ENTRY_SIZE_AUDIO_AAC_STSD 94
563 #define ENTRY_SIZE_AUDIO_AMR_STSD 69
565 #define ENTRY_SIZE_STSC 28
566 #define ENTRY_SIZE_VIDEO_ST 68 /*atom size (stss + stts + stsc + stsz + stco ) * (size + atom + version + flags + sample count)+stsz(sample size) */
567 #define ENTRY_SIZE_AUDIO_ST 52 /*atom size (stss + stsc + stsz + stco ) * (size + atom + version + flags + sample count)+stsz(sample size) */
570 #define MUX_COMMON_SIZE_HEADER 124 /* free + moov + moov.mvhd*/
572 #define MUX_COMMON_SIZE_VIDEO_HEADER 257
573 #define MUX_COMMON_SIZE_AUDIO_HEADER 253
575 #define MUX_COMMON_SIZE_MP4_FTYP 32
576 #define MUX_COMMON_SIZE_3GP_FTYP 28
578 #define MUX_COMMON_SIZE_MP4_UDTA 61
579 #define MUX_COMMON_SIZE_3GP_UDTA 8
582 gst_qt_mux_update_expected_trailer_size (GstQTMux *qtmux, GstQTPad *pad)
584 guint nb_video_frames = 0;
585 guint nb_video_i_frames = 0;
586 guint nb_video_stts_entry = 0;
587 guint nb_audio_frames = 0;
588 guint nb_audio_stts_entry = 0;
589 gboolean video_stream = FALSE;
590 gboolean audio_stream = FALSE;
592 GstQTMuxClass *qtmux_klass = NULL;
594 if (qtmux == NULL || pad == NULL) {
595 GST_ERROR_OBJECT (qtmux, "Invalid parameter");
599 qtmux_klass = (GstQTMuxClass *)(G_OBJECT_GET_CLASS(qtmux));
601 if (!strncmp(GST_PAD_NAME(pad->collect.pad), "video", 5)) {
602 nb_video_frames += pad->trak->mdia.minf.stbl.stsz.table_size;
603 nb_video_i_frames += pad->trak->mdia.minf.stbl.stss.entries.len;
604 nb_video_stts_entry += pad->trak->mdia.minf.stbl.stts.entries.len;
607 } else if (!strncmp(GST_PAD_NAME(pad->collect.pad), "audio", 5)) {
608 nb_audio_frames += pad->trak->mdia.minf.stbl.stsz.table_size;
609 nb_audio_stts_entry += pad->trak->mdia.minf.stbl.stts.entries.len;
614 /* free + moov + mvhd */
615 qtmux->expected_trailer_size = MUX_COMMON_SIZE_HEADER;
617 /* ftyp + udta * 3 (There is 3 udta fields and it's same size) */
618 switch (qtmux_klass->format) {
619 case GST_QT_MUX_FORMAT_MP4:
620 qtmux->expected_trailer_size += MUX_COMMON_SIZE_MP4_FTYP + MUX_COMMON_SIZE_MP4_UDTA * 3;
622 case GST_QT_MUX_FORMAT_3GP:
623 qtmux->expected_trailer_size += MUX_COMMON_SIZE_3GP_FTYP + MUX_COMMON_SIZE_3GP_UDTA * 3;
629 /* Calculate trailer size for video stream */
631 switch (pad->fourcc) {
634 exp_size += MUX_COMMON_SIZE_VIDEO_HEADER + ENTRY_SIZE_VIDEO_H263P_STSD;
643 exp_size += MUX_COMMON_SIZE_VIDEO_HEADER + ENTRY_SIZE_VIDEO_MPEG4_STSD;
650 exp_size += ENTRY_SIZE_VIDEO_ST + (ENTRY_SIZE_VIDEO_STTS * nb_video_stts_entry) +
651 (ENTRY_SIZE_VIDEO_STSS * nb_video_i_frames) + (ENTRY_SIZE_STSC) +
652 ((ENTRY_SIZE_VIDEO_STSZ + ENTRY_SIZE_VIDEO_STCO) * nb_video_frames);
654 qtmux->video_expected_trailer_size = exp_size;
657 /* Calculate trailer size for audio stream */
659 exp_size += MUX_COMMON_SIZE_AUDIO_HEADER + ENTRY_SIZE_AUDIO_ST + (ENTRY_SIZE_AUDIO_STTS * nb_audio_stts_entry) +
660 (ENTRY_SIZE_STSC) + ((ENTRY_SIZE_AUDIO_STSZ + ENTRY_SIZE_AUDIO_STCO) * nb_audio_frames);
662 if (pad->fourcc == FOURCC_samr)
663 exp_size += ENTRY_SIZE_AUDIO_AMR_STSD;
665 exp_size += ENTRY_SIZE_AUDIO_AAC_STSD;
667 qtmux->audio_expected_trailer_size = exp_size;
670 qtmux->expected_trailer_size += qtmux->video_expected_trailer_size + qtmux->audio_expected_trailer_size;
673 GST_INFO_OBJECT (qtmux, "pad type %s", GST_PAD_NAME(pad->collect.pad));
674 GST_INFO_OBJECT (qtmux, "VIDEO : stts-entry=[%d], i-frame=[%d], video-sample=[%d]", nb_video_stts_entry, nb_video_i_frames, nb_video_frames);
675 GST_INFO_OBJECT (qtmux, "AUDIO : stts-entry=[%d], audio-sample=[%d]", nb_audio_stts_entry, nb_audio_frames);
676 GST_INFO_OBJECT (qtmux, "expected trailer size %d", qtmux->expected_trailer_size);
681 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
684 gst_qt_mux_base_init (gpointer g_class)
686 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
687 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
688 GstQTMuxClassParams *params;
689 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
691 GstPadTemplate *srctempl;
692 gchar *longname, *description;
695 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
696 GST_QT_MUX_PARAMS_QDATA);
697 g_assert (params != NULL);
699 /* construct the element details struct */
700 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
701 description = g_strdup_printf ("Multiplex audio and video into a %s file",
702 params->prop->long_name);
703 gst_element_class_set_static_metadata (element_class, longname,
704 "Codec/Muxer", description,
705 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
707 g_free (description);
710 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
711 GST_PAD_ALWAYS, params->src_caps);
712 gst_element_class_add_pad_template (element_class, srctempl);
714 if (params->audio_sink_caps) {
715 audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
716 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
717 GST_TYPE_QT_MUX_PAD);
718 gst_element_class_add_pad_template (element_class, audiosinktempl);
721 if (params->video_sink_caps) {
722 videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
723 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
724 GST_TYPE_QT_MUX_PAD);
725 gst_element_class_add_pad_template (element_class, videosinktempl);
728 if (params->subtitle_sink_caps) {
729 subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
730 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
731 GST_TYPE_QT_MUX_PAD);
732 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
735 if (params->caption_sink_caps) {
736 captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
737 GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
738 GST_TYPE_QT_MUX_PAD);
739 gst_element_class_add_pad_template (element_class, captionsinktempl);
742 klass->format = params->prop->format;
746 gst_qt_mux_class_init (GstQTMuxClass * klass)
748 GObjectClass *gobject_class;
749 GstElementClass *gstelement_class;
750 GParamFlags streamable_flags;
751 const gchar *streamable_desc;
753 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
754 GParamSpec *tspec = NULL;
755 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
756 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
757 "be streamed and hence no indexes written or duration written."
759 gobject_class = (GObjectClass *) klass;
760 gstelement_class = (GstElementClass *) klass;
762 parent_class = g_type_class_peek_parent (klass);
764 gobject_class->finalize = gst_qt_mux_finalize;
765 gobject_class->get_property = gst_qt_mux_get_property;
766 gobject_class->set_property = gst_qt_mux_set_property;
768 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
769 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
770 streamable_desc = STREAMABLE_DESC;
771 streamable = DEFAULT_STREAMABLE;
774 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
775 streamable_flags |= G_PARAM_DEPRECATED;
779 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
780 g_param_spec_uint ("movie-timescale", "Movie timescale",
781 "Timescale to use in the movie (units per second, 0 == default)",
782 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
783 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
784 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
785 g_param_spec_uint ("trak-timescale", "Track timescale",
786 "Timescale to use for the tracks (units per second, 0 is automatic)",
787 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
788 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
789 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
790 g_param_spec_boolean ("presentation-time",
791 "Include presentation-time info",
792 "Calculate and include presentation/composition time "
793 "(in addition to decoding time)", DEFAULT_DO_CTTS,
794 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
795 #ifndef GST_REMOVE_DEPRECATED
796 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
797 g_param_spec_enum ("dts-method", "dts-method",
798 "Method to determine DTS time (DEPRECATED)",
799 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
800 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
801 G_PARAM_STATIC_STRINGS));
803 g_object_class_install_property (gobject_class, PROP_FAST_START,
804 g_param_spec_boolean ("faststart", "Format file to faststart",
805 "If the file should be formatted for faststart (headers first)",
806 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
807 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
808 g_param_spec_string ("faststart-file", "File to use for storing buffers",
809 "File that will be used temporarily to store data from the stream "
810 "when creating a faststart file. If null a filepath will be "
811 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
812 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
813 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
814 g_param_spec_string ("moov-recovery-file",
815 "File to store data for posterior moov atom recovery",
816 "File to be used to store "
817 "data for moov atom making movie file recovery possible in case "
818 "of a crash during muxing. Null for disabled. (Experimental)",
819 DEFAULT_MOOV_RECOV_FILE,
820 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
821 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
822 g_param_spec_uint ("fragment-duration", "Fragment duration",
823 "Fragment durations in ms (produce a fragmented file if > 0)",
824 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
825 2000 : DEFAULT_FRAGMENT_DURATION,
826 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
827 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
828 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
829 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
830 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
831 g_param_spec_uint64 ("reserved-max-duration",
832 "Reserved maximum file duration (ns)",
833 "When set to a value > 0, reserves space for index tables at the "
834 "beginning of the file.",
835 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
836 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
837 g_object_class_install_property (gobject_class,
838 PROP_RESERVED_DURATION_REMAINING,
839 g_param_spec_uint64 ("reserved-duration-remaining",
840 "Report the approximate amount of remaining recording space (ns)",
841 "Reports the approximate amount of remaining moov header space "
842 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
843 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
844 g_object_class_install_property (gobject_class,
845 PROP_RESERVED_MOOV_UPDATE_PERIOD,
846 g_param_spec_uint64 ("reserved-moov-update-period",
847 "Interval at which to update index tables (ns)",
848 "When used with reserved-max-duration, periodically updates the "
849 "index tables with information muxed so far.", 0, G_MAXUINT64,
850 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
851 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
852 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
853 g_param_spec_uint ("reserved-bytes-per-sec",
854 "Reserved MOOV bytes per second, per track",
855 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
856 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
857 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
858 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
859 g_param_spec_boolean ("reserved-prefill",
860 "Reserved Prefill Samples Table",
861 "Prefill samples table of reserved duration",
862 DEFAULT_RESERVED_PREFILL,
863 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
864 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
865 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
866 "Interleave between streams in bytes",
867 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
868 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
869 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
870 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
871 "Interleave between streams in nanoseconds",
872 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
873 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
874 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
875 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
876 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
877 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
878 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
879 g_object_class_install_property (gobject_class, PROP_START_GAP_THRESHOLD,
880 g_param_spec_uint64 ("start-gap-threshold", "Start Gap Threshold",
881 "Threshold for creating an edit list for gaps at the start in nanoseconds",
882 0, G_MAXUINT64, DEFAULT_START_GAP_THRESHOLD,
883 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
885 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
886 tspec = g_param_spec_uint("expected-trailer-size", "Expected Trailer Size",
887 "Expected trailer size (bytes)",
888 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
890 g_object_class_install_property(gobject_class, PROP_EXPECTED_TRAILER_SIZE, tspec);
892 GST_ERROR("g_param_spec failed for \"expected-trailer-size\"");
893 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
895 gstelement_class->request_new_pad =
896 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
897 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
898 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
902 gst_qt_mux_pad_reset (GstQTPad * qtpad)
905 qtpad->is_out_of_order = FALSE;
906 qtpad->sample_size = 0;
909 qtpad->sample_offset = 0;
910 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
911 qtpad->first_ts = GST_CLOCK_TIME_NONE;
912 qtpad->first_dts = GST_CLOCK_TIME_NONE;
913 qtpad->prepare_buf_func = NULL;
914 qtpad->create_empty_buffer = NULL;
915 qtpad->avg_bitrate = 0;
916 qtpad->max_bitrate = 0;
917 qtpad->total_duration = 0;
918 qtpad->total_bytes = 0;
919 qtpad->sparse = FALSE;
921 gst_buffer_replace (&qtpad->last_buf, NULL);
924 gst_tag_list_unref (qtpad->tags);
928 /* reference owned elsewhere */
930 qtpad->tc_trak = NULL;
933 atom_traf_free (qtpad->traf);
936 atom_array_clear (&qtpad->fragment_buffers);
938 g_array_unref (qtpad->samples);
939 qtpad->samples = NULL;
941 /* reference owned elsewhere */
944 qtpad->first_pts = GST_CLOCK_TIME_NONE;
947 gst_video_time_code_free (qtpad->first_tc);
948 qtpad->first_tc = NULL;
950 if (qtpad->raw_audio_adapter)
951 gst_object_unref (qtpad->raw_audio_adapter);
952 qtpad->raw_audio_adapter = NULL;
956 * Takes GstQTMux back to its initial state
959 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
963 qtmux->state = GST_QT_MUX_STATE_NONE;
964 qtmux->header_size = 0;
965 qtmux->mdat_size = 0;
968 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
969 qtmux->fragment_sequence = 0;
972 atom_ftyp_free (qtmux->ftyp);
976 atom_moov_free (qtmux->moov);
980 atom_mfra_free (qtmux->mfra);
983 if (qtmux->fast_start_file) {
984 fclose (qtmux->fast_start_file);
985 g_remove (qtmux->fast_start_file_path);
986 qtmux->fast_start_file = NULL;
988 if (qtmux->moov_recov_file) {
989 fclose (qtmux->moov_recov_file);
990 qtmux->moov_recov_file = NULL;
992 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
993 AtomInfo *ainfo = (AtomInfo *) walk->data;
994 ainfo->free_func (ainfo->atom);
997 g_slist_free (qtmux->extra_atoms);
998 qtmux->extra_atoms = NULL;
1000 GST_OBJECT_LOCK (qtmux);
1001 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
1002 GST_OBJECT_UNLOCK (qtmux);
1004 /* reset pad data */
1005 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1006 GstQTPad *qtpad = (GstQTPad *) walk->data;
1007 gst_qt_mux_pad_reset (qtpad);
1009 /* hm, moov_free above yanked the traks away from us,
1010 * so do not free, but do clear */
1015 qtmux->moov = atom_moov_new (qtmux->context);
1016 #ifndef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
1017 /* ensure all is as nice and fresh as request_new_pad would provide it */
1018 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1019 GstQTPad *qtpad = (GstQTPad *) walk->data;
1021 qtpad->trak = atom_trak_new (qtmux->context);
1022 atom_moov_add_trak (qtmux->moov, qtpad->trak);
1027 qtmux->current_pad = NULL;
1028 qtmux->current_chunk_size = 0;
1029 qtmux->current_chunk_duration = 0;
1030 qtmux->current_chunk_offset = -1;
1032 qtmux->reserved_moov_size = 0;
1033 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
1034 qtmux->muxed_since_last_update = 0;
1035 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
1037 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
1038 qtmux->expected_trailer_size = 0;
1039 qtmux->video_expected_trailer_size = 0;
1040 qtmux->audio_expected_trailer_size = 0;
1041 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
1045 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
1047 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
1048 GstPadTemplate *templ;
1050 templ = gst_element_class_get_pad_template (klass, "src");
1051 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
1052 gst_pad_use_fixed_caps (qtmux->srcpad);
1053 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
1055 qtmux->sinkpads = NULL;
1056 qtmux->collect = gst_collect_pads_new ();
1057 gst_collect_pads_set_event_function (qtmux->collect,
1058 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
1059 gst_collect_pads_set_clip_function (qtmux->collect,
1060 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
1061 gst_collect_pads_set_function (qtmux->collect,
1062 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
1064 /* properties set to default upon construction */
1066 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
1067 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
1068 qtmux->reserved_bytes_per_sec_per_trak =
1069 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
1070 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
1071 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
1072 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
1073 qtmux->start_gap_threshold = DEFAULT_START_GAP_THRESHOLD;
1075 /* always need this */
1077 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
1079 /* internals to initial state */
1080 gst_qt_mux_reset (qtmux, TRUE);
1085 gst_qt_mux_finalize (GObject * object)
1087 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
1089 gst_qt_mux_reset (qtmux, FALSE);
1091 g_free (qtmux->fast_start_file_path);
1092 g_free (qtmux->moov_recov_file_path);
1094 atoms_context_free (qtmux->context);
1095 gst_object_unref (qtmux->collect);
1097 g_slist_free (qtmux->sinkpads);
1099 G_OBJECT_CLASS (parent_class)->finalize (object);
1103 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
1110 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
1115 size = gst_buffer_get_size (buf);
1116 newbuf = gst_buffer_new_and_alloc (size + 8);
1117 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
1119 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1120 GST_WRITE_UINT32_BE (map.data, map.size);
1121 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
1123 gst_buffer_unmap (buf, &map);
1124 gst_buffer_unref (buf);
1130 extract_608_field_from_s334_1a (const guint8 * ccdata, gsize ccdata_size,
1131 guint field, guint8 ** res)
1134 gsize storage_size = 128;
1135 gsize i, res_size = 0;
1137 storage = g_malloc0 (storage_size);
1139 /* Iterate over the ccdata and put the corresponding tuples for the given field
1141 for (i = 0; i < ccdata_size; i += 3) {
1142 if ((field == 1 && (ccdata[i * 3] & 0x80)) ||
1143 (field == 2 && !(ccdata[i * 3] & 0x80))) {
1144 GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
1145 ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
1146 if (res_size >= storage_size) {
1147 storage_size += 128;
1148 storage = g_realloc (storage, storage_size);
1150 storage[res_size] = ccdata[i * 3 + 1];
1151 storage[res_size + 1] = ccdata[i * 3 + 2];
1156 if (res_size == 0) {
1168 gst_qt_mux_prepare_caption_buffer (GstQTPad * qtpad, GstBuffer * buf,
1171 GstBuffer *newbuf = NULL;
1172 GstMapInfo map, inmap;
1174 gboolean in_prefill;
1179 in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
1181 size = gst_buffer_get_size (buf);
1182 gst_buffer_map (buf, &inmap, GST_MAP_READ);
1184 GST_LOG_OBJECT (qtmux,
1185 "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
1186 GST_FOURCC_ARGS (qtpad->fourcc), size);
1188 switch (qtpad->fourcc) {
1191 guint8 *cdat, *cdt2;
1192 gsize cdat_size, cdt2_size, total_size = 0;
1193 gsize write_offs = 0;
1196 extract_608_field_from_s334_1a (inmap.data, inmap.size, 1, &cdat);
1198 extract_608_field_from_s334_1a (inmap.data, inmap.size, 2, &cdt2);
1201 total_size += cdat_size + 8;
1203 total_size += cdt2_size + 8;
1204 if (total_size == 0) {
1205 GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
1206 /* FIXME : We might want to *always* store something, even if
1207 * it's "empty" CC (i.e. 0x80 0x80) */
1211 newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
1212 /* Let's copy over all metadata and not the memory */
1213 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1215 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1216 if (cdat_size || in_prefill) {
1217 GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
1218 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
1220 memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
1222 /* Write 'empty' CC */
1226 write_offs = in_prefill ? 10 : cdat_size + 8;
1231 if (cdt2_size || in_prefill) {
1232 GST_WRITE_UINT32_BE (map.data + write_offs,
1233 in_prefill ? 10 : cdt2_size + 8);
1234 GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
1236 memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
1238 /* Write 'empty' CC */
1239 map.data[write_offs + 8] = 0x80;
1240 map.data[write_offs + 9] = 0x80;
1245 gst_buffer_unmap (newbuf, &map);
1251 /* Take the whole CDP */
1252 if (in_prefill && size > 256) {
1253 GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1256 newbuf = gst_buffer_new_and_alloc (in_prefill ? 256 + 8 : size + 8);
1258 /* Let's copy over all metadata and not the memory */
1259 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1261 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1263 GST_WRITE_UINT32_BE (map.data, size + 8);
1264 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1265 memcpy (map.data + 8, inmap.data, inmap.size);
1267 gst_buffer_unmap (newbuf, &map);
1271 /* theoretically this should never happen, but let's keep this here in case */
1272 GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1276 gst_buffer_unmap (buf, &inmap);
1277 gst_buffer_unref (buf);
1283 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1290 const guint8 *dataend;
1292 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1297 gst_buffer_map (buf, &frommap, GST_MAP_READ);
1299 dataend = memchr (frommap.data, 0, frommap.size);
1300 size = dataend ? dataend - frommap.data : frommap.size;
1301 newbuf = gst_buffer_new_and_alloc (size + 2);
1303 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1305 GST_WRITE_UINT16_BE (tomap.data, size);
1306 memcpy (tomap.data + 2, frommap.data, size);
1308 gst_buffer_unmap (newbuf, &tomap);
1309 gst_buffer_unmap (buf, &frommap);
1311 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1313 /* gst_buffer_copy_into is trying to be too clever and
1314 * won't copy duration when size is different */
1315 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1317 gst_buffer_unref (buf);
1323 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1324 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1329 g_return_if_fail (qtpad->trak_ste);
1331 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
1333 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1337 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1341 GstByteReader reader;
1344 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1345 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1349 if (G_UNLIKELY (map.size < 8))
1352 gst_byte_reader_init (&reader, map.data, map.size);
1353 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1358 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1360 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1363 gst_bit_reader_init (&bits, map.data, map.size);
1365 /* off + sync + crc */
1366 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1368 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1369 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1370 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1371 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1372 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1374 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1375 gst_bit_reader_skip_unchecked (&bits, 2);
1376 if ((acmod & 0x4)) /* if a surround channel exists */
1377 gst_bit_reader_skip_unchecked (&bits, 2);
1378 if (acmod == 0x2) /* if in 2/0 mode */
1379 gst_bit_reader_skip_unchecked (&bits, 2);
1381 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1383 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1384 bsmod, acmod, lfe_on);
1386 /* AC-3 spec says that those values should be constant for the
1387 * whole stream when muxed in mp4. We trust the input follows it */
1388 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1389 "prepare buffer function");
1390 qtpad->prepare_buf_func = NULL;
1394 gst_buffer_unmap (buf, &map);
1399 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1403 data = g_malloc (2);
1404 GST_WRITE_UINT16_BE (data, 0);
1406 return gst_buffer_new_wrapped (data, 2);
1410 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1411 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1413 switch (gst_tag_get_type (tag)) {
1419 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1421 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1422 GST_FOURCC_ARGS (fourcc), str);
1423 atom_udta_add_str_tag (udta, fourcc, str);
1432 if (!gst_tag_list_get_double (list, tag, &value))
1434 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1435 GST_FOURCC_ARGS (fourcc), (gint) value);
1436 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1443 /* paired unsigned integers */
1447 got_tag = gst_tag_list_get_uint (list, tag, &value);
1448 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1451 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1452 GST_FOURCC_ARGS (fourcc), value, count);
1453 atom_udta_add_uint_tag (udta, fourcc, 0,
1454 value << 16 | (count & 0xFFFF));
1456 /* unpaired unsigned integers */
1457 if (!gst_tag_list_get_uint (list, tag, &value))
1459 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1460 GST_FOURCC_ARGS (fourcc), value);
1461 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1466 g_assert_not_reached ();
1472 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1473 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1481 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1483 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1486 year = g_date_get_year (date);
1487 month = g_date_get_month (date);
1488 day = g_date_get_day (date);
1492 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1493 day == G_DATE_BAD_DAY) {
1494 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1498 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1499 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1500 GST_FOURCC_ARGS (fourcc), str);
1501 atom_udta_add_str_tag (udta, fourcc, str);
1506 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1507 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1509 GValue value = { 0, };
1513 GstStructure *structure;
1517 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1519 if (!gst_tag_list_copy_value (&value, list, tag))
1522 sample = gst_value_get_sample (&value);
1527 buf = gst_sample_get_buffer (sample);
1531 caps = gst_sample_get_caps (sample);
1533 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1537 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1539 structure = gst_caps_get_structure (caps, 0);
1540 if (gst_structure_has_name (structure, "image/jpeg"))
1542 else if (gst_structure_has_name (structure, "image/png"))
1546 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1550 gst_buffer_map (buf, &map, GST_MAP_READ);
1551 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1552 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1553 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1554 gst_buffer_unmap (buf, &map);
1556 g_value_unset (&value);
1560 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1561 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1566 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1567 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1569 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1573 if (!gst_tag_list_get_uint (list, tag2, &number))
1577 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1578 GST_FOURCC_ARGS (fourcc), str);
1579 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1581 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1582 GST_FOURCC_ARGS (fourcc), str, number);
1583 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1590 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1591 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1596 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1598 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1601 year = g_date_get_year (date);
1604 if (year == G_DATE_BAD_YEAR) {
1605 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1609 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1610 GST_FOURCC_ARGS (fourcc), year);
1611 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1615 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1616 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1618 gdouble latitude = -360, longitude = -360, altitude = 0;
1619 gchar *location = NULL;
1620 guint8 *data, *ddata;
1621 gint size = 0, len = 0;
1622 gboolean ret = FALSE;
1624 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1626 ret = gst_tag_list_get_string (list, tag, &location);
1627 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1629 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1631 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1638 len = strlen (location);
1639 size += len + 1 + 2;
1641 /* role + (long, lat, alt) + body + notes */
1642 size += 1 + 3 * 4 + 1 + 1;
1644 data = ddata = g_malloc (size);
1647 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1650 memcpy (data + 2, location, len);
1651 GST_WRITE_UINT8 (data + 2 + len, 0);
1652 data += len + 1 + 2;
1654 GST_WRITE_UINT8 (data, 0);
1655 /* long, lat, alt */
1656 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1657 QT_WRITE_SFP32 (data + 1, longitude);
1658 QT_WRITE_SFP32 (data + 5, latitude);
1659 QT_WRITE_SFP32 (data + 9, altitude);
1660 /* neither astronomical body nor notes */
1661 GST_WRITE_UINT16_BE (data + 13, 0);
1663 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1664 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1669 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1670 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1672 gchar *keywords = NULL;
1673 guint8 *data, *ddata;
1677 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1679 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1682 kwds = g_strsplit (keywords, ",", 0);
1686 for (i = 0; kwds[i]; i++) {
1687 /* size byte + null-terminator */
1688 size += strlen (kwds[i]) + 1 + 1;
1691 /* language tag + count + keywords */
1694 data = ddata = g_malloc (size);
1697 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1699 GST_WRITE_UINT8 (data + 2, i);
1702 for (i = 0; kwds[i]; ++i) {
1703 gint len = strlen (kwds[i]);
1705 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1706 GST_FOURCC_ARGS (fourcc), kwds[i]);
1708 GST_WRITE_UINT8 (data, len + 1);
1709 memcpy (data + 1, kwds[i], len + 1);
1715 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1720 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1721 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1729 size = strlen (input);
1731 if (size < 4 + 3 + 1 + 1 + 1) {
1732 /* at least the minimum xxxx://y/z */
1733 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1738 /* read the fourcc */
1739 memcpy (&fourcc, data, 4);
1743 if (strncmp (data, "://", 3) != 0) {
1749 /* read the table number */
1750 if (sscanf (data, "%d", &table) != 1) {
1754 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1755 ", table numbers should be positive, ignoring tag", table);
1759 /* find the next / */
1760 while (size > 0 && data[0] != '/') {
1767 g_assert (data[0] == '/');
1776 /* read up the rest of the string */
1777 *p_content = g_strdup (data);
1778 *p_table = (guint16) table;
1784 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1785 "input (%s) didn't match the expected entitycode://table/content",
1792 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1793 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1795 gchar *clsf_data = NULL;
1799 gchar *content = NULL;
1802 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1804 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1807 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1808 GST_FOURCC_ARGS (fourcc), clsf_data);
1810 /* parse the string, format is:
1811 * entityfourcc://table/content
1813 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1817 size = strlen (content) + 1;
1819 /* now we have everything, build the atom
1820 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1821 data = g_malloc (4 + 2 + 2 + size);
1822 GST_WRITE_UINT32_LE (data, entity);
1823 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1824 GST_WRITE_UINT16_BE (data + 6, 0);
1825 memcpy (data + 8, content, size);
1828 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1832 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1833 const GstTagList * list, AtomUDTA * udta, const char *tag,
1834 const char *tag2, guint32 fourcc);
1837 * Struct to record mappings from gstreamer tags to fourcc codes
1839 typedef struct _GstTagToFourcc
1842 const gchar *gsttag;
1843 const gchar *gsttag2;
1844 const GstQTMuxAddUdtaTagFunc func;
1847 /* tag list tags to fourcc matching */
1848 static const GstTagToFourcc tag_matches_mp4[] = {
1849 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1850 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1851 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1852 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1853 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1854 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1855 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1856 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1857 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1858 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1859 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1860 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1861 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1862 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1863 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1864 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1865 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1866 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1867 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1868 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1869 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1870 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1871 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1872 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1873 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1874 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1875 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1876 gst_qt_mux_add_mp4_tag},
1877 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1878 gst_qt_mux_add_mp4_tag},
1879 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1880 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1884 static const GstTagToFourcc tag_matches_3gp[] = {
1885 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1886 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1887 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1888 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1889 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1890 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1891 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1892 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1893 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1894 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1895 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1896 gst_qt_mux_add_3gp_classification},
1900 /* qtdemux produces these for atoms it cannot parse */
1901 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1904 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1906 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1907 GstBuffer *xmp = NULL;
1909 /* adobe specs only have 'quicktime' and 'mp4',
1910 * but I guess we can extrapolate to gpp.
1911 * Keep mj2 out for now as we don't add any tags for it yet.
1912 * If you have further info about xmp on these formats, please share */
1913 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1916 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1918 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1919 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1922 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1925 /* for isom/mp4, it is a top level uuid atom */
1926 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1929 ainfo = build_uuid_xmp_atom (xmp);
1931 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1936 gst_buffer_unref (xmp);
1940 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1943 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1946 const gchar *tag, *tag2;
1947 const GstTagToFourcc *tag_matches;
1949 switch (qtmux_klass->format) {
1950 case GST_QT_MUX_FORMAT_3GP:
1951 tag_matches = tag_matches_3gp;
1953 case GST_QT_MUX_FORMAT_MJ2:
1957 /* sort of iTunes style for mp4 and QT (?) */
1958 tag_matches = tag_matches_mp4;
1965 /* Clear existing tags so we don't add them over and over */
1966 atom_udta_clear_tags (udta);
1968 for (i = 0; tag_matches[i].fourcc; i++) {
1969 fourcc = tag_matches[i].fourcc;
1970 tag = tag_matches[i].gsttag;
1971 tag2 = tag_matches[i].gsttag2;
1973 g_assert (tag_matches[i].func);
1974 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1977 /* add unparsed blobs if present */
1978 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1981 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1982 for (i = 0; i < num_tags; ++i) {
1983 GstSample *sample = NULL;
1985 const GstStructure *s;
1987 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1990 buf = gst_sample_get_buffer (sample);
1992 if (buf && (s = gst_sample_get_info (sample))) {
1993 const gchar *style = NULL;
1996 gst_buffer_map (buf, &map, GST_MAP_READ);
1997 GST_DEBUG_OBJECT (qtmux,
1998 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1999 GST_PTR_FORMAT, i, num_tags, map.size, s);
2000 if (s && (style = gst_structure_get_string (s, "style"))) {
2001 /* try to prevent some style tag ending up into another variant
2002 * (todo: make into a list if more cases) */
2003 if ((strcmp (style, "itunes") == 0 &&
2004 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
2005 (strcmp (style, "iso") == 0 &&
2006 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
2007 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
2008 atom_udta_add_blob_tag (udta, map.data, map.size);
2011 gst_buffer_unmap (buf, &map);
2013 gst_sample_unref (sample);
2021 * Gets the tagsetter iface taglist and puts the known tags
2022 * into the output stream
2025 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
2027 const GstTagList *tags = NULL;
2030 GST_OBJECT_LOCK (qtmux);
2031 if (qtmux->tags_changed) {
2032 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
2033 qtmux->tags_changed = FALSE;
2035 GST_OBJECT_UNLOCK (qtmux);
2037 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
2039 if (tags && !gst_tag_list_is_empty (tags)) {
2040 GstTagList *copy = gst_tag_list_copy (tags);
2042 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
2043 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
2044 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
2045 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
2047 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
2048 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
2049 gst_qt_mux_add_xmp_tags (qtmux, copy);
2050 gst_tag_list_unref (copy);
2052 GST_DEBUG_OBJECT (qtmux, "No new tags received");
2055 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2056 GstCollectData *cdata = (GstCollectData *) walk->data;
2057 GstQTPad *qpad = (GstQTPad *) cdata;
2058 GstPad *pad = qpad->collect.pad;
2060 if (qpad->tags_changed && qpad->tags) {
2061 GST_DEBUG_OBJECT (pad, "Adding tags");
2062 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
2063 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
2064 qpad->tags_changed = FALSE;
2065 GST_DEBUG_OBJECT (pad, "Tags added");
2067 GST_DEBUG_OBJECT (pad, "No new tags received");
2072 static inline GstBuffer *
2073 _gst_buffer_new_take_data (guint8 * data, guint size)
2077 buf = gst_buffer_new ();
2078 gst_buffer_append_memory (buf,
2079 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
2084 static GstFlowReturn
2085 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
2091 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
2093 size = gst_buffer_get_size (buf);
2094 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
2096 if (mind_fast && qtmux->fast_start_file) {
2100 GST_LOG_OBJECT (qtmux, "to temporary file");
2101 gst_buffer_map (buf, &map, GST_MAP_READ);
2102 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
2103 gst_buffer_unmap (buf, &map);
2104 gst_buffer_unref (buf);
2110 GST_LOG_OBJECT (qtmux, "downstream");
2111 res = gst_pad_push (qtmux->srcpad, buf);
2114 if (G_LIKELY (offset))
2122 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
2123 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
2124 return GST_FLOW_ERROR;
2129 gst_qt_mux_seek_to_beginning (FILE * f)
2132 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
2134 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
2135 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
2138 if (fseek (f, (long) 0, SEEK_SET) != 0)
2144 static GstFlowReturn
2145 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
2147 GstFlowReturn ret = GST_FLOW_OK;
2148 GstBuffer *buf = NULL;
2150 if (fflush (qtmux->fast_start_file))
2153 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
2156 /* hm, this could all take a really really long time,
2157 * but there may not be another way to get moov atom first
2158 * (somehow optimize copy?) */
2159 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
2160 while (ret == GST_FLOW_OK) {
2161 const int bufsize = 4096;
2165 buf = gst_buffer_new_and_alloc (bufsize);
2166 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2167 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
2169 gst_buffer_unmap (buf, &map);
2172 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
2173 gst_buffer_unmap (buf, &map);
2174 if (size != bufsize)
2175 gst_buffer_set_size (buf, size);
2176 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2180 gst_buffer_unref (buf);
2182 if (ftruncate (fileno (qtmux->fast_start_file), 0))
2184 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
2192 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
2193 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
2194 ret = GST_FLOW_ERROR;
2199 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
2200 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
2201 ret = GST_FLOW_ERROR;
2206 /* clear descriptor so we don't remove temp file later on,
2207 * might be possible to recover */
2208 fclose (qtmux->fast_start_file);
2209 qtmux->fast_start_file = NULL;
2215 * Sends the initial mdat atom fields (size fields and fourcc type),
2216 * the subsequent buffers are considered part of it's data.
2217 * As we can't predict the amount of data that we are going to place in mdat
2218 * we need to record the position of the size field in the stream so we can
2219 * seek back to it later and update when the streams have finished.
2221 static GstFlowReturn
2222 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
2223 gboolean extended, gboolean fsync_after)
2228 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
2229 "size %" G_GUINT64_FORMAT, size);
2231 /* if the qtmux state is EOS, really write the mdat, otherwise
2232 * allow size == 0 for a placeholder atom */
2233 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
2237 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
2238 /* Always write 16-bytes, but put a free atom first
2239 * if the size is < 4GB. */
2240 buf = gst_buffer_new_and_alloc (16);
2241 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2244 /* Write extended mdat header and large_size field */
2245 GST_WRITE_UINT32_BE (map.data, 1);
2246 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2247 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
2249 /* Write an empty free atom, then standard 32-bit mdat */
2250 GST_WRITE_UINT32_BE (map.data, 8);
2251 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
2252 GST_WRITE_UINT32_BE (map.data + 8, size);
2253 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2255 gst_buffer_unmap (buf, &map);
2257 buf = gst_buffer_new_and_alloc (8);
2258 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2260 /* Vanilla 32-bit mdat */
2261 GST_WRITE_UINT32_BE (map.data, size);
2262 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2263 gst_buffer_unmap (buf, &map);
2266 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2268 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2270 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2275 * We get the position of the mdat size field, seek back to it
2276 * and overwrite with the real value
2278 static GstFlowReturn
2279 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2280 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2284 /* We must have recorded the mdat position for this to work */
2285 g_assert (mdat_pos != 0);
2287 /* seek and rewrite the header */
2288 gst_segment_init (&segment, GST_FORMAT_BYTES);
2289 segment.start = mdat_pos;
2290 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2292 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2296 static GstFlowReturn
2297 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2300 guint64 size = 0, offset = 0;
2301 guint8 *data = NULL;
2303 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2305 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2306 goto serialize_error;
2308 buf = _gst_buffer_new_take_data (data, offset);
2310 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2311 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2316 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2317 ("Failed to serialize ftyp"));
2318 return GST_FLOW_ERROR;
2323 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2324 GstBuffer ** p_prefix)
2326 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2327 guint32 major, version;
2329 GstBuffer *prefix = NULL;
2330 AtomFTYP *ftyp = NULL;
2332 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2334 /* init and send context and ftyp based on current property state */
2335 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2336 &version, &comp, qtmux->moov, qtmux->longest_chunk,
2337 qtmux->fast_start_file != NULL);
2338 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2345 gst_buffer_unref (prefix);
2350 static GstFlowReturn
2351 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2353 GstFlowReturn ret = GST_FLOW_OK;
2354 GstBuffer *prefix = NULL;
2356 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2358 /* init and send context and ftyp based on current property state */
2360 atom_ftyp_free (qtmux->ftyp);
2363 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2365 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2366 if (ret != GST_FLOW_OK)
2369 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2373 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2375 GstStructure *structure;
2376 GValue array = { 0 };
2377 GValue value = { 0 };
2378 GstCaps *caps, *tcaps;
2380 tcaps = gst_pad_get_current_caps (mux->srcpad);
2381 caps = gst_caps_copy (tcaps);
2382 gst_caps_unref (tcaps);
2384 structure = gst_caps_get_structure (caps, 0);
2386 g_value_init (&array, GST_TYPE_ARRAY);
2388 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2389 g_value_init (&value, GST_TYPE_BUFFER);
2390 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2391 gst_value_array_append_value (&array, &value);
2392 g_value_unset (&value);
2394 gst_structure_set_value (structure, "streamheader", &array);
2395 g_value_unset (&array);
2396 gst_pad_set_caps (mux->srcpad, caps);
2397 gst_caps_unref (caps);
2401 * Write out a free space atom. The offset is adjusted by the full
2402 * size, but a smaller buffer is sent
2404 static GstFlowReturn
2405 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2406 gboolean fsync_after)
2410 guint8 *data = NULL;
2411 guint64 offset = 0, bsize = 0;
2414 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2416 /* We can't make a free space atom smaller than the header */
2420 node_header = g_malloc0 (sizeof (Atom));
2421 node_header->type = FOURCC_free;
2422 node_header->size = size;
2425 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2426 goto serialize_error;
2428 buf = _gst_buffer_new_take_data (data, offset);
2429 g_free (node_header);
2432 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2434 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2435 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2442 /* Make sure downstream position ends up at the end of this free box */
2443 gst_segment_init (&segment, GST_FORMAT_BYTES);
2444 segment.start = *off;
2445 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2453 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2454 ("Not enough free reserved space"));
2455 return GST_FLOW_ERROR;
2459 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2460 ("Failed to serialize mdat"));
2461 g_free (node_header);
2462 return GST_FLOW_ERROR;
2467 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2469 gboolean fragmented = FALSE;
2472 GST_OBJECT_LOCK (qtmux);
2473 timescale = qtmux->timescale;
2474 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2475 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2477 GST_OBJECT_UNLOCK (qtmux);
2479 /* inform lower layers of our property wishes, and determine duration.
2480 * Let moov take care of this using its list of traks;
2481 * so that released pads are also included */
2482 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2484 atom_moov_update_timescale (qtmux->moov, timescale);
2485 atom_moov_set_fragmented (qtmux->moov, fragmented);
2487 atom_moov_update_duration (qtmux->moov);
2490 static GstFlowReturn
2491 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2492 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2494 guint64 offset = 0, size = 0;
2497 GstFlowReturn ret = GST_FLOW_OK;
2499 guint64 current_time = atoms_get_current_qt_time ();
2501 /* update modification times */
2502 qtmux->moov->mvhd.time_info.modification_time = current_time;
2503 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2504 GstCollectData *cdata = (GstCollectData *) walk->data;
2505 GstQTPad *qtpad = (GstQTPad *) cdata;
2507 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2508 qtpad->trak->tkhd.modification_time = current_time;
2511 /* serialize moov */
2514 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2515 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2516 goto serialize_error;
2517 qtmux->last_moov_size = offset;
2519 /* Check we have enough reserved space for this and a Free atom */
2520 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2521 goto too_small_reserved;
2522 buf = _gst_buffer_new_take_data (data, offset);
2523 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2525 /* If at EOS, this is the final moov, put in the streamheader
2526 * (apparently used by a flumotion util) */
2527 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2528 gst_qt_mux_set_header_on_caps (qtmux, buf);
2531 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2532 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2534 /* Write out a free atom if needed */
2535 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2536 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2537 (guint32) (padded_moov_size - offset));
2539 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2546 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2547 ("Not enough free reserved header space"),
2548 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2549 offset, padded_moov_size));
2550 return GST_FLOW_ERROR;
2555 return GST_FLOW_ERROR;
2559 /* either calculates size of extra atoms or pushes them */
2560 static GstFlowReturn
2561 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2565 guint64 loffset = 0, size = 0;
2567 GstFlowReturn ret = GST_FLOW_OK;
2569 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2570 AtomInfo *ainfo = (AtomInfo *) walk->data;
2574 if (!ainfo->copy_data_func (ainfo->atom,
2575 send ? &data : NULL, &size, &loffset))
2576 goto serialize_error;
2581 GST_DEBUG_OBJECT (qtmux,
2582 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2583 GST_FOURCC_ARGS (ainfo->atom->type));
2584 buf = _gst_buffer_new_take_data (data, loffset);
2585 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2586 if (ret != GST_FLOW_OK)
2599 return GST_FLOW_ERROR;
2604 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2606 gboolean seekable = FALSE;
2607 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2609 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2610 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2611 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2613 /* have to assume seeking is not supported if query not handled downstream */
2614 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2617 gst_query_unref (query);
2623 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2626 gboolean fail = FALSE;
2627 AtomFTYP *ftyp = NULL;
2628 GstBuffer *prefix = NULL;
2630 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2631 qtmux->moov_recov_file_path);
2633 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2634 if (qtmux->moov_recov_file == NULL) {
2635 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2636 qtmux->moov_recov_file_path);
2640 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2642 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2643 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2644 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2648 atom_ftyp_free (ftyp);
2650 gst_buffer_unref (prefix);
2652 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2653 GstCollectData *cdata = (GstCollectData *) walk->data;
2654 GstQTPad *qpad = (GstQTPad *) cdata;
2655 /* write info for each stream */
2656 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2658 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2668 fclose (qtmux->moov_recov_file);
2669 qtmux->moov_recov_file = NULL;
2673 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2675 switch (qpad->fourcc) {
2684 return qpad->sample_offset;
2687 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2688 qpad->expected_sample_duration_n,
2689 qpad->expected_sample_duration_d *
2690 atom_trak_get_timescale (qpad->trak));
2697 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2699 switch (qpad->fourcc) {
2701 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2703 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2705 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2707 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2714 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2716 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2718 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2720 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2727 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2729 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2731 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2733 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2740 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2742 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2744 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2746 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2753 /* We always write both cdat and cdt2 atom in prefill mode */
2756 /* We're cheating a bit by always allocating 256 bytes plus 8 bytes for the atom header
2757 * even if we use less */
2762 guint64 next_sample_offset;
2764 block_idx = prefill_get_block_index (qtmux, qpad);
2765 next_sample_offset =
2766 gst_util_uint64_scale (block_idx + 1,
2767 qpad->expected_sample_duration_d *
2768 atom_trak_get_timescale (qpad->trak),
2769 qpad->expected_sample_duration_n);
2771 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2776 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2784 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2786 switch (qpad->fourcc) {
2795 return gst_util_uint64_scale (qpad->sample_offset + 1,
2796 qpad->expected_sample_duration_d * GST_SECOND,
2797 qpad->expected_sample_duration_n);
2801 guint64 next_sample_offset;
2803 block_idx = prefill_get_block_index (qtmux, qpad);
2804 next_sample_offset =
2805 gst_util_uint64_scale (block_idx + 1,
2806 qpad->expected_sample_duration_d *
2807 atom_trak_get_timescale (qpad->trak),
2808 qpad->expected_sample_duration_n);
2810 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2811 atom_trak_get_timescale (qpad->trak));
2814 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2822 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2827 GstClockTime input_timestamp;
2828 guint64 input_timestamp_distance;
2831 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2833 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2834 qtpad->expected_sample_duration_n,
2835 qtpad->expected_sample_duration_d *
2836 atom_trak_get_timescale (qtpad->trak));
2838 gst_util_uint64_scale (block_idx + 1,
2839 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2840 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2842 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2843 GST_COLLECT_PADS_STATE_EOS)
2844 && gst_adapter_available (qtpad->raw_audio_adapter) <
2845 nsamples * qtpad->sample_size)
2846 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2851 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2852 &input_timestamp_distance);
2853 if (input_timestamp != GST_CLOCK_TIME_NONE)
2855 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2856 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2859 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2860 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2861 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2862 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2863 GST_BUFFER_PTS (buf) = input_timestamp;
2864 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2865 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2867 qtpad->raw_audio_adapter_offset += nsamples;
2869 /* Check if we have yet another block of raw audio in the adapter */
2871 gst_util_uint64_scale (block_idx + 2,
2872 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2873 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2874 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2875 nsamples * qtpad->sample_size) {
2877 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2878 &input_timestamp_distance);
2879 if (input_timestamp != GST_CLOCK_TIME_NONE)
2881 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2882 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2883 qtpad->raw_audio_adapter_pts = input_timestamp;
2885 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2892 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2896 /* Find the (first) video track and assume that we have to output
2898 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2899 GstCollectData *cdata = (GstCollectData *) walk->data;
2900 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2902 if (tmp_qpad->trak->is_video) {
2903 *dur_n = tmp_qpad->expected_sample_duration_n;
2904 *dur_d = tmp_qpad->expected_sample_duration_d;
2910 GST_INFO_OBJECT (qtmux,
2911 "Found no video framerate, using 40ms audio buffers");
2917 /* Called when all pads are prerolled to adjust and */
2919 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2921 switch (qpad->fourcc) {
2929 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2930 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2936 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2937 /* We need a "valid" duration */
2938 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2939 &qpad->expected_sample_duration_d);
2940 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2945 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2946 &qpad->expected_sample_duration_d);
2947 /* Set a prepare_buf_func that ensures this */
2948 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2949 qpad->raw_audio_adapter = gst_adapter_new ();
2950 qpad->raw_audio_adapter_offset = 0;
2951 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2960 /* Only called at startup when doing the "fake" iteration of all tracks in order
2961 * to prefill the sample tables in the header. */
2963 find_best_pad_prefill_start (GstQTMux * qtmux)
2966 GstQTPad *best_pad = NULL;
2968 /* If interleave limits have been specified and the current pad is within
2969 * those interleave limits, pick that one, otherwise let's try to figure out
2970 * the next best one. */
2971 if (qtmux->current_pad &&
2972 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2973 (qtmux->interleave_bytes == 0
2974 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2975 && (qtmux->interleave_time == 0
2976 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2977 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2978 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2980 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2981 best_pad = qtmux->current_pad;
2983 } else if (qtmux->collect->data->next) {
2984 /* Attempt to try another pad if we have one. Otherwise use the only pad
2986 best_pad = qtmux->current_pad = NULL;
2989 /* The next best pad is the one which has the lowest timestamp and hasn't
2990 * exceeded the reserved max duration */
2992 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2994 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2995 GstCollectData *cdata = (GstCollectData *) walk->data;
2996 GstQTPad *qtpad = (GstQTPad *) cdata;
2997 GstClockTime timestamp;
2999 if (qtpad->total_duration >= qtmux->reserved_max_duration)
3002 timestamp = qtpad->total_duration;
3004 if (best_pad == NULL ||
3005 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
3007 best_time = timestamp;
3015 /* Called when starting the file in prefill_mode to figure out all the entries
3016 * of the header based on the input stream and reserved maximum duration.
3018 * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
3019 * will be updated and written on EOS. */
3021 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
3025 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3027 /* Update expected sample sizes/durations as needed, this is for raw
3028 * audio where samples are actual audio samples. */
3029 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3030 GstCollectData *cdata = (GstCollectData *) walk->data;
3031 GstQTPad *qpad = (GstQTPad *) cdata;
3033 if (!prefill_update_sample_size (qtmux, qpad))
3037 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
3038 /* For the first sample check/update timecode as needed. We do that before
3039 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
3040 * initial buffer directly, not with last_buf */
3041 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3042 GstCollectData *cdata = (GstCollectData *) walk->data;
3043 GstQTPad *qpad = (GstQTPad *) cdata;
3045 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
3046 GstVideoTimeCodeMeta *tc_meta;
3048 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))
3049 && qpad->trak->is_video) {
3050 GstVideoTimeCode *tc = &tc_meta->tc;
3052 qpad->tc_trak = atom_trak_new (qtmux->context);
3053 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
3055 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
3056 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
3058 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
3059 qpad->trak->mdia.mdhd.time_info.timescale, tc);
3061 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
3062 qtmux->mdat_size, FALSE, 0);
3064 qpad->tc_pos = qtmux->mdat_size;
3065 qpad->first_tc = gst_video_time_code_copy (tc);
3066 qpad->first_pts = GST_BUFFER_PTS (buffer);
3068 qtmux->current_chunk_offset = -1;
3069 qtmux->current_chunk_size = 0;
3070 qtmux->current_chunk_duration = 0;
3071 qtmux->mdat_size += 4;
3074 gst_buffer_unref (buffer);
3078 while ((qpad = find_best_pad_prefill_start (qtmux))) {
3079 GstClockTime timestamp, next_timestamp, duration;
3080 guint nsamples, sample_size;
3081 guint64 chunk_offset;
3082 gint64 scaled_duration;
3083 gint64 pts_offset = 0;
3084 gboolean sync = FALSE;
3085 TrakBufferEntryInfo sample_entry;
3087 sample_size = prefill_get_sample_size (qtmux, qpad);
3089 if (sample_size == -1) {
3094 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
3096 timestamp = qpad->total_duration;
3097 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
3098 duration = next_timestamp - timestamp;
3100 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
3101 qpad->first_ts = timestamp;
3102 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
3103 qpad->first_dts = timestamp;
3105 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
3106 qtmux->current_pad = qpad;
3107 if (qtmux->current_chunk_offset == -1)
3108 qtmux->current_chunk_offset = qtmux->mdat_size;
3110 qtmux->current_chunk_offset += qtmux->current_chunk_size;
3111 qtmux->current_chunk_size = 0;
3112 qtmux->current_chunk_duration = 0;
3114 if (qpad->sample_size)
3115 nsamples = sample_size / qpad->sample_size;
3118 qpad->last_dts = timestamp;
3119 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
3120 atom_trak_get_timescale (qpad->trak),
3121 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
3122 atom_trak_get_timescale (qpad->trak), GST_SECOND);
3124 qtmux->current_chunk_size += sample_size;
3125 qtmux->current_chunk_duration += duration;
3126 qpad->total_bytes += sample_size;
3128 chunk_offset = qtmux->current_chunk_offset;
3130 /* I-frame only, no frame reordering */
3134 if (qtmux->current_chunk_duration > qtmux->longest_chunk
3135 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
3136 qtmux->longest_chunk = qtmux->current_chunk_duration;
3139 sample_entry.track_id = qpad->trak->tkhd.track_ID;
3140 sample_entry.nsamples = nsamples;
3141 sample_entry.delta = scaled_duration / nsamples;
3142 sample_entry.size = sample_size / nsamples;
3143 sample_entry.chunk_offset = chunk_offset;
3144 sample_entry.pts_offset = pts_offset;
3145 sample_entry.sync = sync;
3146 sample_entry.do_pts = TRUE;
3147 g_array_append_val (qpad->samples, sample_entry);
3148 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
3149 sample_size / nsamples, chunk_offset, sync, pts_offset);
3151 qpad->total_duration = next_timestamp;
3152 qtmux->mdat_size += sample_size;
3153 qpad->sample_offset += nsamples;
3159 static GstFlowReturn
3160 gst_qt_mux_start_file (GstQTMux * qtmux)
3162 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3163 GstFlowReturn ret = GST_FLOW_OK;
3167 GstClockTime reserved_max_duration;
3168 guint reserved_bytes_per_sec_per_trak;
3171 GST_DEBUG_OBJECT (qtmux, "starting file");
3173 GST_OBJECT_LOCK (qtmux);
3174 reserved_max_duration = qtmux->reserved_max_duration;
3175 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
3176 GST_OBJECT_UNLOCK (qtmux);
3178 /* stream-start (FIXME: create id based on input ids) */
3179 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
3180 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
3182 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
3183 /* qtmux has structure with and without variant, remove all but the first */
3184 while (gst_caps_get_size (caps) > 1)
3185 gst_caps_remove_structure (caps, 1);
3186 gst_pad_set_caps (qtmux->srcpad, caps);
3187 gst_caps_unref (caps);
3189 /* Default is 'normal' mode */
3190 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
3192 /* Require a sensible fragment duration when muxing
3193 * using the ISML muxer */
3194 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
3195 qtmux->fragment_duration == 0)
3198 if (qtmux->fragment_duration > 0) {
3199 if (qtmux->streamable)
3200 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
3202 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
3203 } else if (qtmux->fast_start) {
3204 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
3205 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
3206 if (qtmux->reserved_prefill)
3207 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
3209 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
3212 switch (qtmux->mux_mode) {
3213 case GST_QT_MUX_MODE_MOOV_AT_END:
3214 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3215 /* We have to be able to seek to rewrite the mdat header, or any
3216 * moov atom we write will not be visible in the file, because an
3217 * MDAT with 0 as the size covers the rest of the file. A file
3218 * with no moov is not playable, so error out now. */
3219 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
3220 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3221 ("Downstream is not seekable - will not be able to create a playable file"),
3223 return GST_FLOW_ERROR;
3225 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3226 GST_WARNING_OBJECT (qtmux,
3227 "Robust muxing requires reserved-moov-update-period to be set");
3230 case GST_QT_MUX_MODE_FAST_START:
3231 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3232 break; /* Don't need seekability, ignore */
3233 case GST_QT_MUX_MODE_FRAGMENTED:
3234 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
3235 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
3236 "streamable=false. Will ignore that and create streamable output "
3238 qtmux->streamable = TRUE;
3239 g_object_notify (G_OBJECT (qtmux), "streamable");
3242 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3243 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
3244 GST_WARNING_OBJECT (qtmux,
3245 "downstream is not seekable, will not be able "
3246 "to trim samples table at the end if less than reserved-duration is "
3252 /* let downstream know we think in BYTES and expect to do seeking later on */
3253 gst_segment_init (&segment, GST_FORMAT_BYTES);
3254 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3256 GST_OBJECT_LOCK (qtmux);
3258 if (qtmux->timescale == 0) {
3259 guint32 suggested_timescale = 0;
3262 /* Calculate a reasonable timescale for the moov:
3263 * If there is video, it is the biggest video track timescale or an even
3264 * multiple of it if it's smaller than 1800.
3265 * Otherwise it is 1800 */
3266 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3267 GstCollectData *cdata = (GstCollectData *) walk->data;
3268 GstQTPad *qpad = (GstQTPad *) cdata;
3274 if (!qpad->trak->mdia.minf.vmhd)
3277 suggested_timescale =
3278 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3281 if (suggested_timescale == 0)
3282 suggested_timescale = 1800;
3284 while (suggested_timescale < 1800)
3285 suggested_timescale *= 2;
3287 qtmux->timescale = suggested_timescale;
3290 /* Set width/height/timescale of any closed caption tracks to that of the
3291 * first video track */
3293 guint video_width = 0, video_height = 0;
3294 guint32 video_timescale = 0;
3297 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3298 GstCollectData *cdata = (GstCollectData *) walk->data;
3299 GstQTPad *qpad = (GstQTPad *) cdata;
3304 /* Not closed caption */
3305 if (qpad->trak->mdia.hdlr.handler_type != FOURCC_clcp)
3308 if (video_width == 0 || video_height == 0 || video_timescale == 0) {
3311 for (walk2 = qtmux->sinkpads; walk2; walk2 = g_slist_next (walk2)) {
3312 GstCollectData *cdata2 = (GstCollectData *) walk2->data;
3313 GstQTPad *qpad2 = (GstQTPad *) cdata2;
3319 if (!qpad2->trak->mdia.minf.vmhd)
3322 video_width = qpad2->trak->tkhd.width;
3323 video_height = qpad2->trak->tkhd.height;
3324 video_timescale = qpad2->trak->mdia.mdhd.time_info.timescale;
3328 qpad->trak->tkhd.width = video_width << 16;
3329 qpad->trak->tkhd.height = video_height << 16;
3330 qpad->trak->mdia.mdhd.time_info.timescale = video_timescale;
3334 /* initialize our moov recovery file */
3335 if (qtmux->moov_recov_file_path) {
3336 gst_qt_mux_prepare_moov_recovery (qtmux);
3339 /* Make sure the first time we update the moov, we'll
3340 * include any tagsetter tags */
3341 qtmux->tags_changed = TRUE;
3343 GST_OBJECT_UNLOCK (qtmux);
3346 * send mdat header if already needed, and mark position for later update.
3347 * We don't send ftyp now if we are on fast start mode, because we can
3348 * better fine tune using the information we gather to create the whole moov
3351 switch (qtmux->mux_mode) {
3352 case GST_QT_MUX_MODE_MOOV_AT_END:
3353 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3354 if (ret != GST_FLOW_OK)
3357 /* Store this as the mdat offset for later updating
3358 * when we write the moov */
3359 qtmux->mdat_pos = qtmux->header_size;
3360 /* extended atom in case we go over 4GB while writing and need
3361 * the full 64-bit atom */
3363 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3366 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3367 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3368 if (ret != GST_FLOW_OK)
3371 /* Pad ftyp out to an 8-byte boundary before starting the moov
3372 * ping pong region. It should be well less than 1 disk sector,
3373 * unless there's a bajillion compatible types listed,
3374 * but let's be sure the free atom doesn't cross a sector
3375 * boundary anyway */
3376 if (qtmux->header_size % 8) {
3377 /* Extra 8 bytes for the padding free atom header */
3378 guint padding = (guint) (16 - (qtmux->header_size % 8));
3379 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3381 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3383 if (ret != GST_FLOW_OK)
3387 /* Store this as the moov offset for later updating.
3388 * We record mdat position below */
3389 qtmux->moov_pos = qtmux->header_size;
3391 /* Set up the initial 'ping' state of the ping-pong buffers */
3392 qtmux->reserved_moov_first_active = TRUE;
3394 gst_qt_mux_configure_moov (qtmux);
3395 gst_qt_mux_setup_metadata (qtmux);
3396 /* Empty free atom to begin, starting on an 8-byte boundary */
3397 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3398 if (ret != GST_FLOW_OK)
3400 /* Moov header, not padded yet */
3401 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3402 if (ret != GST_FLOW_OK)
3404 /* The moov we just sent contains the 'base' size of the moov, before
3405 * we put in any time-dependent per-trak data. Use that to make
3406 * a good estimate of how much extra to reserve */
3407 /* Calculate how much space to reserve for our MOOV atom.
3408 * We actually reserve twice that, for ping-pong buffers */
3409 qtmux->base_moov_size = qtmux->last_moov_size;
3410 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3411 qtmux->base_moov_size);
3412 qtmux->reserved_moov_size = qtmux->base_moov_size +
3413 gst_util_uint64_scale (reserved_max_duration,
3414 reserved_bytes_per_sec_per_trak *
3415 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3417 /* Need space for at least 4 atom headers. More really, but
3418 * this as an absolute minimum */
3419 if (qtmux->reserved_moov_size < 4 * 8)
3420 goto reserved_moov_too_small;
3422 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3423 2 * qtmux->reserved_moov_size + 16);
3425 GST_OBJECT_LOCK (qtmux);
3426 qtmux->reserved_duration_remaining =
3427 gst_util_uint64_scale (qtmux->reserved_moov_size -
3428 qtmux->base_moov_size, GST_SECOND,
3429 reserved_bytes_per_sec_per_trak *
3430 atom_moov_get_trak_count (qtmux->moov));
3431 GST_OBJECT_UNLOCK (qtmux);
3433 /* Now that we know how much reserved space is targetted,
3434 * output a free atom to fill the extra reserved */
3435 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3436 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3437 if (ret != GST_FLOW_OK)
3440 /* Then a free atom containing 'pong' buffer, with an
3441 * extra 8 bytes to account for the free atom header itself */
3442 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3443 qtmux->reserved_moov_size + 8, FALSE);
3444 if (ret != GST_FLOW_OK)
3447 /* extra atoms go after the free/moov(s), before the mdat */
3449 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3450 if (ret != GST_FLOW_OK)
3453 qtmux->mdat_pos = qtmux->header_size;
3454 /* extended atom in case we go over 4GB while writing and need
3455 * the full 64-bit atom */
3457 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3460 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3461 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3462 if (ret != GST_FLOW_OK)
3465 /* Store this as the moov offset for later updating.
3466 * We record mdat position below */
3467 qtmux->moov_pos = qtmux->header_size;
3469 if (!gst_qt_mux_prefill_samples (qtmux)) {
3470 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3471 ("Unsupported codecs or configuration for prefill mode"), (NULL));
3473 return GST_FLOW_ERROR;
3476 gst_qt_mux_update_global_statistics (qtmux);
3477 gst_qt_mux_configure_moov (qtmux);
3478 gst_qt_mux_update_edit_lists (qtmux);
3479 gst_qt_mux_setup_metadata (qtmux);
3481 /* Moov header with pre-filled samples */
3482 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3483 if (ret != GST_FLOW_OK)
3486 /* last_moov_size now contains the full size of the moov, moov_pos the
3487 * position. This allows us to rewrite it in the very end as needed */
3488 qtmux->reserved_moov_size =
3489 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3491 /* Send an additional free atom at the end so we definitely have space
3492 * to rewrite the moov header at the end and remove the samples that
3493 * were not actually written */
3495 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3496 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3497 if (ret != GST_FLOW_OK)
3500 /* extra atoms go after the free/moov(s), before the mdat */
3502 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3503 if (ret != GST_FLOW_OK)
3506 qtmux->mdat_pos = qtmux->header_size;
3508 /* And now send the mdat header */
3510 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3511 qtmux->mdat_size, TRUE, FALSE);
3513 /* chunks position is set relative to the first byte of the
3514 * MDAT atom payload. Set the overall offset into the file */
3515 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3520 gst_segment_init (&segment, GST_FORMAT_BYTES);
3521 segment.start = qtmux->moov_pos;
3522 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3524 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3525 if (ret != GST_FLOW_OK)
3528 segment.start = qtmux->header_size;
3529 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3532 qtmux->current_chunk_size = 0;
3533 qtmux->current_chunk_duration = 0;
3534 qtmux->current_chunk_offset = -1;
3535 qtmux->mdat_size = 0;
3536 qtmux->current_pad = NULL;
3537 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3539 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3540 GstCollectData *cdata = (GstCollectData *) walk->data;
3541 GstQTPad *qtpad = (GstQTPad *) cdata;
3543 qtpad->total_bytes = 0;
3544 qtpad->total_duration = 0;
3545 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3546 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3547 qtpad->sample_offset = 0;
3551 case GST_QT_MUX_MODE_FAST_START:
3552 GST_OBJECT_LOCK (qtmux);
3553 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3554 if (!qtmux->fast_start_file)
3556 GST_OBJECT_UNLOCK (qtmux);
3557 /* send a dummy buffer for preroll */
3558 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3560 case GST_QT_MUX_MODE_FRAGMENTED:
3561 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3562 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3563 if (ret != GST_FLOW_OK)
3565 /* store the moov pos so we can update the duration later
3566 * in non-streamable mode */
3567 qtmux->moov_pos = qtmux->header_size;
3569 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3570 qtmux->fragment_duration);
3571 /* also used as snapshot marker to indicate fragmented file */
3572 qtmux->fragment_sequence = 1;
3573 /* prepare moov and/or tags */
3574 gst_qt_mux_configure_moov (qtmux);
3575 gst_qt_mux_setup_metadata (qtmux);
3576 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3577 if (ret != GST_FLOW_OK)
3581 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3582 if (ret != GST_FLOW_OK)
3584 /* prepare index if not streamable */
3585 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3586 qtmux->mfra = atom_mfra_new (qtmux->context);
3594 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3595 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3596 return GST_FLOW_ERROR;
3598 reserved_moov_too_small:
3600 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3601 ("Not enough reserved space for creating headers"), (NULL));
3602 return GST_FLOW_ERROR;
3606 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3607 (("Could not open temporary file \"%s\""),
3608 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3609 GST_OBJECT_UNLOCK (qtmux);
3610 return GST_FLOW_ERROR;
3614 static GstFlowReturn
3615 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3617 GstFlowReturn ret = GST_FLOW_OK;
3620 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3621 GstCollectData *cdata = (GstCollectData *) walk->data;
3622 GstQTPad *qtpad = (GstQTPad *) cdata;
3624 /* avoid add_buffer complaining if not negotiated
3625 * in which case no buffers either, so skipping */
3626 if (!qtpad->fourcc) {
3627 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3628 GST_PAD_NAME (qtpad->collect.pad));
3632 /* send last buffer; also flushes possibly queued buffers/ts */
3633 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3634 GST_PAD_NAME (qtpad->collect.pad));
3635 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3636 if (ret != GST_FLOW_OK) {
3637 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3638 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3639 gst_flow_get_name (ret));
3647 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3651 /* for setting some subtitles fields */
3652 guint max_width = 0;
3653 guint max_height = 0;
3655 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3657 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3658 GstCollectData *cdata = (GstCollectData *) walk->data;
3659 GstQTPad *qtpad = (GstQTPad *) cdata;
3661 if (!qtpad->fourcc) {
3662 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3663 GST_PAD_NAME (qtpad->collect.pad));
3667 /* having flushed above, can check for buffers now */
3668 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3669 GstClockTime first_pts_in = qtpad->first_ts;
3670 /* it should be, since we got first_ts by adding adjustment
3671 * to a positive incoming PTS */
3672 if (qtpad->dts_adjustment <= first_pts_in)
3673 first_pts_in -= qtpad->dts_adjustment;
3674 /* determine max stream duration */
3675 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3676 || qtpad->last_dts > qtmux->last_dts) {
3677 qtmux->last_dts = qtpad->last_dts;
3679 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3680 || first_pts_in < qtmux->first_ts) {
3681 /* we need the original incoming PTS here, as this first_ts
3682 * is used in update_edit_lists to construct the edit list that arrange
3683 * for sync'ed streams. The first_ts is most likely obtained from
3684 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3685 * so it makes no difference, though it matters in other cases */
3686 qtmux->first_ts = first_pts_in;
3690 /* subtitles need to know the video width/height,
3691 * it is stored shifted 16 bits to the left according to the
3693 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3694 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3696 /* update average bitrate of streams if needed */
3698 guint32 avgbitrate = 0;
3699 guint32 maxbitrate = qtpad->max_bitrate;
3701 if (qtpad->avg_bitrate)
3702 avgbitrate = qtpad->avg_bitrate;
3703 else if (qtpad->total_duration > 0)
3704 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3705 8 * GST_SECOND, qtpad->total_duration);
3707 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3711 /* need to update values on subtitle traks now that we know the
3712 * max width and height */
3713 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3714 GstCollectData *cdata = (GstCollectData *) walk->data;
3715 GstQTPad *qtpad = (GstQTPad *) cdata;
3717 if (!qtpad->fourcc) {
3718 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3719 GST_PAD_NAME (qtpad->collect.pad));
3723 if (qtpad->fourcc == FOURCC_tx3g) {
3724 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3729 /* Called after gst_qt_mux_update_global_statistics() updates the
3730 * first_ts tracking, to create/set edit lists for delayed streams */
3732 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3736 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3737 GST_TIME_ARGS (qtmux->first_ts));
3738 /* add/update EDTSs for late streams. configure_moov will have
3739 * set the trak durations above by summing the sample tables,
3740 * here we extend that if needing to insert an empty segment */
3741 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3742 GstCollectData *cdata = (GstCollectData *) walk->data;
3743 GstQTPad *qtpad = (GstQTPad *) cdata;
3745 atom_trak_edts_clear (qtpad->trak);
3747 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3748 guint32 lateness = 0;
3749 guint32 duration = qtpad->trak->tkhd.duration;
3752 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3755 GstClockTime diff, trak_lateness;
3757 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3758 lateness = gst_util_uint64_scale_round (diff,
3759 qtmux->timescale, GST_SECOND);
3761 /* Allow up to 1 trak timescale unit of lateness, Such a small
3762 * timestamp/duration can't be represented by the trak-specific parts
3763 * of the headers anyway, so it's irrelevantly small */
3764 trak_lateness = gst_util_uint64_scale (diff,
3765 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3767 if (trak_lateness > 0 && diff > qtmux->start_gap_threshold) {
3768 GST_DEBUG_OBJECT (qtmux,
3769 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3770 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3772 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3773 (guint32) (1 * 65536.0));
3777 /* Always write an edit list for the whole track. In general this is not
3778 * necessary except for the case of having a gap or DTS adjustment but
3779 * it allows to give the whole track's duration in the usually more
3780 * accurate media timescale
3783 GstClockTime ctts = 0;
3784 guint32 media_start;
3786 if (qtpad->first_ts > qtpad->first_dts)
3787 ctts = qtpad->first_ts - qtpad->first_dts;
3789 media_start = gst_util_uint64_scale_round (ctts,
3790 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3792 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3793 * is empty because there's no gap added above, this call
3794 * will not replace index 1, it will create the entry at index 0.
3795 * Luckily, that's exactly what we want here */
3796 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3797 (guint32) (1 * 65536.0));
3800 /* need to add the empty time to the trak duration */
3801 duration += lateness;
3802 qtpad->trak->tkhd.duration = duration;
3803 if (qtpad->tc_trak) {
3804 qtpad->tc_trak->tkhd.duration = duration;
3805 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3808 /* And possibly grow the moov duration */
3809 if (duration > qtmux->moov->mvhd.time_info.duration) {
3810 qtmux->moov->mvhd.time_info.duration = duration;
3811 qtmux->moov->mvex.mehd.fragment_duration = duration;
3817 static GstFlowReturn
3818 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3823 guint64 offset = qtpad->tc_pos;
3824 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3826 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3829 g_assert (qtpad->tc_pos != -1);
3831 gst_segment_init (&segment, GST_FORMAT_BYTES);
3832 segment.start = offset;
3833 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3835 buf = gst_buffer_new_and_alloc (4);
3836 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3838 GST_WRITE_UINT32_BE (map.data,
3839 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3840 gst_buffer_unmap (buf, &map);
3842 /* Reset this value, so the timecode won't be re-rewritten */
3845 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3848 static GstFlowReturn
3849 gst_qt_mux_stop_file (GstQTMux * qtmux)
3851 gboolean ret = GST_FLOW_OK;
3852 guint64 offset = 0, size = 0;
3853 gboolean large_file;
3856 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3858 /* pushing last buffers for each pad */
3859 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3862 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3863 /* Streamable mode; no need to write duration or MFRA */
3864 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3868 gst_qt_mux_update_global_statistics (qtmux);
3869 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3870 GstQTPad *qtpad = (GstQTPad *) walk->data;
3872 if (qtpad->tc_pos != -1) {
3873 /* File is being stopped and timecode hasn't been updated. Update it now
3874 * with whatever we have */
3875 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3876 if (ret != GST_FLOW_OK)
3881 switch (qtmux->mux_mode) {
3882 case GST_QT_MUX_MODE_FRAGMENTED:{
3884 guint8 *data = NULL;
3888 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3889 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3890 goto serialize_error;
3891 buf = _gst_buffer_new_take_data (data, offset);
3892 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3893 if (ret != GST_FLOW_OK)
3896 /* only mvex duration is updated,
3897 * mvhd should be consistent with empty moov
3898 * (but TODO maybe some clients do not handle that well ?) */
3899 qtmux->moov->mvex.mehd.fragment_duration =
3900 gst_util_uint64_scale_round (qtmux->last_dts, qtmux->timescale,
3902 GST_DEBUG_OBJECT (qtmux,
3903 "rewriting moov with mvex duration %" GST_TIME_FORMAT,
3904 GST_TIME_ARGS (qtmux->last_dts));
3905 /* seek and rewrite the header */
3906 gst_segment_init (&segment, GST_FORMAT_BYTES);
3907 segment.start = qtmux->moov_pos;
3908 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3909 /* no need to seek back */
3910 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3912 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3913 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3914 if (G_UNLIKELY (ret != GST_FLOW_OK))
3916 /* Finalise by writing the final size into the mdat. Up until now
3917 * it's been 0, which means 'rest of the file'
3918 * No need to seek back after this, we won't write any more */
3919 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3920 qtmux->mdat_size, NULL, TRUE);
3922 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3924 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3926 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3927 GstCollectData *cdata = (GstCollectData *) walk->data;
3928 GstQTPad *qpad = (GstQTPad *) cdata;
3930 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3932 /* Get the block index of the last sample we wrote, not of the next
3933 * sample we would write */
3934 block_idx = prefill_get_block_index (qtmux, qpad);
3937 if (block_idx > 0) {
3939 guint64 nsamples = 0;
3942 n = atom_array_get_len (&stbl->stts.entries);
3943 for (i = 0; i < n; i++) {
3944 entry = &atom_array_index (&stbl->stts.entries, i);
3945 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3946 entry->sample_count = qpad->sample_offset - nsamples;
3947 stbl->stts.entries.len = i + 1;
3950 nsamples += entry->sample_count;
3954 stbl->stts.entries.len = 0;
3959 g_assert (stbl->stsz.entries.len == 0);
3960 stbl->stsz.table_size = qpad->sample_offset;
3966 guint64 nsamples = 0;
3967 gint chunk_index = 0;
3968 const TrakBufferEntryInfo *sample_entry;
3970 if (block_idx > 0) {
3972 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3975 n = stbl->stco64.entries.len;
3976 for (i = 0; i < n; i++) {
3977 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3979 if (*entry == sample_entry->chunk_offset) {
3980 stbl->stco64.entries.len = i + 1;
3981 chunk_index = i + 1;
3986 g_assert (chunk_index > 0);
3988 n = stbl->stsc.entries.len;
3989 for (i = 0; i < n; i++) {
3990 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3992 if (entry->first_chunk >= chunk_index)
3997 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3999 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
4000 i - 1).samples_per_chunk;
4006 STSCEntry *prev_entry =
4007 &atom_array_index (&stbl->stsc.entries, i - 1);
4010 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
4011 if (qpad->sample_offset - nsamples > 0) {
4012 stbl->stsc.entries.len = i;
4013 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
4014 qpad->sample_offset - nsamples);
4016 stbl->stsc.entries.len = i;
4017 stbl->stco64.entries.len--;
4020 /* Everything in a single chunk */
4021 stbl->stsc.entries.len = 0;
4022 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
4023 qpad->sample_offset);
4026 stbl->stco64.entries.len = 0;
4027 stbl->stsc.entries.len = 0;
4034 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
4035 AtomTREX *trex = walk2->data;
4037 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
4038 trex->track_ID = next_track_id;
4043 qpad->trak->tkhd.track_ID = next_track_id++;
4046 qtmux->moov->mvhd.next_track_id = next_track_id;
4048 gst_qt_mux_update_global_statistics (qtmux);
4049 gst_qt_mux_configure_moov (qtmux);
4051 gst_qt_mux_update_edit_lists (qtmux);
4053 /* Check if any gap edit lists were added. We don't have any space
4054 * reserved for this in the moov and the pre-finalized moov would have
4055 * broken A/V synchronization. Error out here now
4057 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4058 GstCollectData *cdata = (GstCollectData *) walk->data;
4059 GstQTPad *qpad = (GstQTPad *) cdata;
4061 if (qpad->trak->edts
4062 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
4063 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4064 ("Can't support gaps in prefill mode"));
4066 return GST_FLOW_ERROR;
4070 gst_qt_mux_setup_metadata (qtmux);
4071 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4076 gst_segment_init (&segment, GST_FORMAT_BYTES);
4077 segment.start = qtmux->moov_pos;
4078 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4081 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4083 if (ret != GST_FLOW_OK)
4086 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
4088 gst_qt_mux_send_free_atom (qtmux, NULL,
4089 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
4092 if (ret != GST_FLOW_OK)
4096 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
4097 qtmux->mdat_size, NULL, FALSE);
4104 /* Moov-at-end or fast-start mode from here down */
4105 gst_qt_mux_configure_moov (qtmux);
4107 gst_qt_mux_update_edit_lists (qtmux);
4109 /* tags into file metadata */
4110 gst_qt_mux_setup_metadata (qtmux);
4112 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
4114 switch (qtmux->mux_mode) {
4115 case GST_QT_MUX_MODE_FAST_START:{
4116 /* if faststart, update the offset of the atoms in the movie with the offset
4117 * that the movie headers before mdat will cause.
4118 * Also, send the ftyp */
4121 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
4122 if (ret != GST_FLOW_OK) {
4125 /* copy into NULL to obtain size */
4126 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
4127 goto serialize_error;
4128 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
4130 offset += qtmux->header_size + (large_file ? 16 : 8);
4132 /* sum up with the extra atoms size */
4133 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
4134 if (ret != GST_FLOW_OK)
4139 offset = qtmux->header_size;
4143 /* Now that we know the size of moov + extra atoms, we can adjust
4144 * the chunk offsets stored into the moov */
4145 atom_moov_chunks_set_offset (qtmux->moov, offset);
4147 /* write out moov and extra atoms */
4148 /* note: as of this point, we no longer care about tracking written data size,
4149 * since there is no more use for it anyway */
4150 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
4151 if (ret != GST_FLOW_OK)
4155 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
4156 if (ret != GST_FLOW_OK)
4159 switch (qtmux->mux_mode) {
4160 case GST_QT_MUX_MODE_MOOV_AT_END:
4162 /* mdat needs update iff not using faststart */
4163 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
4164 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
4165 qtmux->mdat_size, NULL, FALSE);
4166 /* note; no seeking back to the end of file is done,
4167 * since we no longer write anything anyway */
4170 case GST_QT_MUX_MODE_FAST_START:
4172 /* send mdat atom and move buffered data into it */
4173 /* mdat_size = accumulated (buffered data) */
4174 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
4176 if (ret != GST_FLOW_OK)
4178 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
4179 if (ret != GST_FLOW_OK)
4184 g_assert_not_reached ();
4192 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4193 ("Failed to serialize moov"));
4194 return GST_FLOW_ERROR;
4198 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
4199 return GST_FLOW_ERROR;
4203 static GstFlowReturn
4204 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
4205 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
4206 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
4208 GstFlowReturn ret = GST_FLOW_OK;
4210 /* setup if needed */
4211 if (G_UNLIKELY (!pad->traf || force))
4215 /* flush pad fragment if threshold reached,
4216 * or at new keyframe if we should be minding those in the first place */
4217 if (G_UNLIKELY (force || (sync && pad->sync) ||
4218 pad->fragment_duration < (gint64) delta)) {
4220 guint64 size = 0, offset = 0;
4221 guint8 *data = NULL;
4223 guint i, total_size;
4225 /* now we know where moof ends up, update offset in tfra */
4227 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
4229 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
4230 /* takes ownership */
4231 atom_moof_add_traf (moof, pad->traf);
4233 atom_moof_copy_data (moof, &data, &size, &offset);
4234 buffer = _gst_buffer_new_take_data (data, offset);
4235 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
4236 gst_buffer_get_size (buffer));
4237 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
4239 /* and actual data */
4241 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4243 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
4246 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
4247 atom_array_get_len (&pad->fragment_buffers), total_size);
4248 if (ret == GST_FLOW_OK)
4249 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
4251 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4252 if (G_LIKELY (ret == GST_FLOW_OK))
4253 ret = gst_qt_mux_send_buffer (qtmux,
4254 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
4257 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4260 atom_array_clear (&pad->fragment_buffers);
4261 atom_moof_free (moof);
4262 qtmux->fragment_sequence++;
4267 if (G_UNLIKELY (!pad->traf)) {
4268 GST_LOG_OBJECT (qtmux, "setting up new fragment");
4269 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4270 atom_array_init (&pad->fragment_buffers, 512);
4271 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4272 atom_trak_get_timescale (pad->trak), 1000);
4274 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
4275 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
4276 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
4278 atom_traf_set_base_decode_time (pad->traf, dts);
4281 /* add buffer and metadata */
4282 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
4284 atom_array_append (&pad->fragment_buffers, buf, 256);
4285 pad->fragment_duration -= delta;
4288 guint32 sn = atom_traf_get_sample_num (pad->traf);
4290 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
4291 atom_tfra_add_entry (pad->tfra, dts, sn);
4294 if (G_UNLIKELY (force))
4300 /* Here's the clever bit of robust recording: Updating the moov
4301 * header is done using a ping-pong scheme inside 2 blocks of size
4302 * 'reserved_moov_size' at the start of the file, in such a way that the
4303 * file on-disk is always valid if interrupted.
4304 * Inside the reserved space, we have 2 pairs of free + moov atoms
4305 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4306 * at offset "reserved_moov_size".
4308 * 1. Free-A has 0 size payload, moov-A immediately after is
4309 * active/current, and is padded with an internal Free atom to
4310 * end at reserved_space/2. Free-B is at reserved_space/2, sized
4311 * to cover the remaining free space (including moov-B).
4312 * 2. We write moov-B (which is invisible inside free-B), and pad it to
4313 * end at the end of free space. Then, we update free-A to size
4314 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
4315 * free-B header, and makes moov-B active.
4316 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4317 * Change the size of free-A to make moov-A active again.
4318 * 4. Rinse and repeat.
4321 static GstFlowReturn
4322 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4326 guint64 freeA_offset;
4327 guint32 new_freeA_size;
4328 guint64 new_moov_offset;
4330 /* Update moov info, then seek and rewrite the MOOV atom */
4331 gst_qt_mux_update_global_statistics (qtmux);
4332 gst_qt_mux_configure_moov (qtmux);
4334 gst_qt_mux_update_edit_lists (qtmux);
4336 /* tags into file metadata */
4337 gst_qt_mux_setup_metadata (qtmux);
4339 /* chunks position is set relative to the first byte of the
4340 * MDAT atom payload. Set the overall offset into the file */
4341 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4343 /* Calculate which moov to rewrite. qtmux->moov_pos points to
4344 * the start of the free-A header */
4345 freeA_offset = qtmux->moov_pos;
4346 if (qtmux->reserved_moov_first_active) {
4347 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4348 /* After this, freeA will include itself, moovA, plus the freeB
4350 new_freeA_size = qtmux->reserved_moov_size + 16;
4352 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4355 /* the moov we update is after free-A, calculate its offset */
4356 new_moov_offset = freeA_offset + new_freeA_size;
4358 /* Swap ping-pong cadence marker */
4359 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4361 /* seek and rewrite the MOOV atom */
4362 gst_segment_init (&segment, GST_FORMAT_BYTES);
4363 segment.start = new_moov_offset;
4364 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4367 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4369 if (ret != GST_FLOW_OK)
4372 /* Update the estimated recording space remaining, based on amount used so
4373 * far and duration muxed so far */
4374 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4375 GstClockTime remain;
4376 GstClockTime time_muxed = qtmux->last_dts;
4379 gst_util_uint64_scale (qtmux->reserved_moov_size -
4380 qtmux->last_moov_size, time_muxed,
4381 qtmux->last_moov_size - qtmux->base_moov_size);
4382 /* Always under-estimate slightly, so users
4383 * have time to stop muxing before we run out */
4384 if (remain < GST_SECOND / 2)
4387 remain -= GST_SECOND / 2;
4389 GST_INFO_OBJECT (qtmux,
4390 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4391 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4392 qtmux->reserved_moov_size, qtmux->last_moov_size,
4393 GST_TIME_ARGS (qtmux->last_dts),
4394 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4396 GST_OBJECT_LOCK (qtmux);
4397 qtmux->reserved_duration_remaining = remain;
4398 qtmux->muxed_since_last_update = 0;
4399 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4400 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4401 GST_OBJECT_UNLOCK (qtmux);
4405 /* Now update the moov-A size. Don't pass offset, since we don't need
4406 * send_free_atom() to seek for us - all our callers seek back to
4407 * where they need after this, or they don't need it */
4408 gst_segment_init (&segment, GST_FORMAT_BYTES);
4409 segment.start = freeA_offset;
4410 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4412 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4417 static GstFlowReturn
4418 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4421 GstFlowReturn flow_ret;
4423 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4425 GST_OBJECT_LOCK (qtmux);
4427 /* Update the offset of how much we've muxed, so the
4428 * report of remaining space keeps counting down */
4429 if (position > qtmux->last_moov_update &&
4430 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4431 GST_LOG_OBJECT (qtmux,
4432 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4433 qtmux->muxed_since_last_update);
4434 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4437 /* Next, check if we're supposed to send periodic moov updates downstream */
4438 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4439 GST_OBJECT_UNLOCK (qtmux);
4443 /* Update if position is > the threshold or there's been no update yet */
4444 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4445 (position <= qtmux->last_moov_update ||
4446 (position - qtmux->last_moov_update) <
4447 qtmux->reserved_moov_update_period)) {
4448 GST_OBJECT_UNLOCK (qtmux);
4449 return GST_FLOW_OK; /* No update needed yet */
4452 qtmux->last_moov_update = position;
4453 GST_OBJECT_UNLOCK (qtmux);
4455 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4456 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4457 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4459 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4460 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4463 /* Seek back to previous position */
4464 gst_segment_init (&segment, GST_FORMAT_BYTES);
4465 segment.start = mdat_offset;
4466 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4471 static GstFlowReturn
4472 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4473 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4474 gint64 last_dts, gint64 scaled_duration, guint sample_size,
4475 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4477 GstFlowReturn ret = GST_FLOW_OK;
4479 /* note that a new chunk is started each time (not fancy but works) */
4480 if (qtmux->moov_recov_file) {
4481 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4482 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4483 do_pts, pts_offset)) {
4484 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4485 "recovery file, disabling recovery");
4486 fclose (qtmux->moov_recov_file);
4487 qtmux->moov_recov_file = NULL;
4491 switch (qtmux->mux_mode) {
4492 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4493 const TrakBufferEntryInfo *sample_entry;
4494 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4496 if (block_idx >= pad->samples->len) {
4497 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4498 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4499 block_idx, pad->samples->len));
4500 gst_buffer_unref (buffer);
4501 return GST_FLOW_ERROR;
4504 /* Check if all values are as expected */
4506 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4508 /* Allow +/- 1 difference for the scaled_duration to allow
4509 * for some rounding errors
4511 if (sample_entry->nsamples != nsamples
4512 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4513 || sample_entry->size != sample_size
4514 || sample_entry->chunk_offset != chunk_offset
4515 || sample_entry->pts_offset != pts_offset
4516 || sample_entry->sync != sync) {
4517 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4518 ("Unexpected values in sample %" G_GUINT64_FORMAT,
4519 pad->sample_offset + 1));
4520 GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4521 "chunk offset %" G_GUINT64_FORMAT ", "
4522 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4523 sample_entry->nsamples,
4524 sample_entry->delta,
4526 sample_entry->chunk_offset,
4527 sample_entry->pts_offset, sample_entry->sync);
4528 GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4529 "chunk offset %" G_GUINT64_FORMAT ", "
4530 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4532 (guint) scaled_duration,
4533 sample_size, chunk_offset, pts_offset, sync);
4535 gst_buffer_unref (buffer);
4536 return GST_FLOW_ERROR;
4539 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4542 case GST_QT_MUX_MODE_MOOV_AT_END:
4543 case GST_QT_MUX_MODE_FAST_START:
4544 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4545 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4546 sample_size, chunk_offset, sync, pts_offset);
4547 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4548 /* Check if it's time to re-write the headers in robust-recording mode */
4549 if (ret == GST_FLOW_OK
4550 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4551 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4553 case GST_QT_MUX_MODE_FRAGMENTED:
4554 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4555 /* ensure that always sync samples are marked as such */
4556 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4557 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4558 sample_size, !pad->sync || sync, pts_offset);
4566 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4567 guint buffer_size, GstClockTime duration)
4569 /* not that much happens here,
4570 * but updating any of this very likely needs to happen all in sync,
4571 * unless there is a very good reason not to */
4573 /* for computing the avg bitrate */
4574 pad->total_bytes += buffer_size;
4575 pad->total_duration += duration;
4576 /* for keeping track of where we are in chunk;
4577 * ensures that data really is located as recorded in atoms */
4578 qtmux->current_chunk_size += buffer_size;
4579 qtmux->current_chunk_duration += duration;
4582 static GstFlowReturn
4583 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4584 GstBuffer * buf, GstFlowReturn ret)
4586 GstVideoTimeCodeMeta *tc_meta;
4587 GstVideoTimeCode *tc;
4590 guint32 frames_since_daily_jam;
4591 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4593 if (!pad->trak->is_video)
4596 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4599 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4602 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4608 /* This means we never got a timecode before */
4609 if (pad->first_tc == NULL) {
4610 #ifndef GST_DISABLE_GST_DEBUG
4611 gchar *tc_str = gst_video_time_code_to_string (tc);
4612 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4615 g_assert (pad->tc_trak == NULL);
4616 pad->first_tc = gst_video_time_code_copy (tc);
4617 /* If frames are out of order, the frame we're currently getting might
4618 * not be the first one. Just write a 0 timecode for now and wait
4619 * until we receive a timecode that's lower than the current one */
4620 if (pad->is_out_of_order) {
4621 pad->first_pts = GST_BUFFER_PTS (buf);
4622 frames_since_daily_jam = 0;
4623 /* Position to rewrite */
4624 pad->tc_pos = qtmux->mdat_size;
4626 frames_since_daily_jam =
4627 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4628 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4630 /* Write the timecode trak now */
4631 pad->tc_trak = atom_trak_new (qtmux->context);
4632 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4634 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4635 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4637 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4638 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4640 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4641 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4642 g_assert (szret == 4);
4644 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4645 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4647 /* Need to reset the current chunk (of the previous pad) here because
4648 * some other data was written now above, and the pad has to start a
4650 qtmux->current_chunk_offset = -1;
4651 qtmux->current_chunk_size = 0;
4652 qtmux->current_chunk_duration = 0;
4653 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4654 frames_since_daily_jam =
4655 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4656 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4658 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4659 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4660 g_assert (szret == 4);
4662 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4665 qtmux->current_chunk_offset = -1;
4666 qtmux->current_chunk_size = 0;
4667 qtmux->current_chunk_duration = 0;
4668 } else if (pad->is_out_of_order) {
4669 /* Check for a lower timecode than the one stored */
4670 g_assert (pad->tc_trak != NULL);
4671 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4672 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4673 gst_video_time_code_free (pad->first_tc);
4674 pad->first_tc = gst_video_time_code_copy (tc);
4677 guint64 bk_size = qtmux->mdat_size;
4679 /* If this frame's DTS is after the first PTS received, it means
4680 * we've already received the first frame to be presented. Otherwise
4681 * the decoder would need to go back in time */
4682 gst_qt_mux_update_timecode (qtmux, pad);
4684 /* Reset writing position */
4685 gst_segment_init (&segment, GST_FORMAT_BYTES);
4686 segment.start = bk_size;
4687 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4695 * Here we push the buffer and update the tables in the track atoms
4697 static GstFlowReturn
4698 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4700 GstBuffer *last_buf = NULL;
4701 GstClockTime duration;
4702 guint nsamples, sample_size;
4703 guint64 chunk_offset;
4704 gint64 last_dts, scaled_duration;
4705 gint64 pts_offset = 0;
4706 gboolean sync = FALSE;
4707 GstFlowReturn ret = GST_FLOW_OK;
4711 goto not_negotiated;
4713 /* if this pad has a prepare function, call it */
4714 if (pad->prepare_buf_func != NULL) {
4717 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4718 if (buf && !new_buf)
4723 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4724 if (ret != GST_FLOW_OK) {
4726 gst_buffer_unref (buf);
4730 last_buf = pad->last_buf;
4731 pad->last_buf = buf;
4733 if (last_buf == NULL) {
4734 #ifndef GST_DISABLE_GST_DEBUG
4736 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4737 "received NULL buffer, doing nothing",
4738 GST_PAD_NAME (pad->collect.pad));
4740 GST_LOG_OBJECT (qtmux,
4741 "Pad %s has no previous buffer stored, storing now",
4742 GST_PAD_NAME (pad->collect.pad));
4748 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4751 /* if this is the first buffer, store the timestamp */
4752 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4753 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4754 pad->first_ts = GST_BUFFER_PTS (last_buf);
4755 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4756 pad->first_ts = GST_BUFFER_DTS (last_buf);
4759 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4760 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4761 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4762 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4765 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4766 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4768 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4769 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4770 pad->first_ts = pad->first_dts = 0;
4772 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4773 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4774 GST_TIME_ARGS (pad->first_ts));
4777 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4778 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4779 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4780 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4781 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4782 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4783 pad->last_buf = buf = gst_buffer_make_writable (buf);
4784 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4787 buffer_size = gst_buffer_get_size (last_buf);
4789 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4790 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4791 guint fill_size = required_buffer_size - buffer_size;
4795 if (required_buffer_size < buffer_size) {
4796 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4797 ("Sample size %u bigger than expected maximum %u", buffer_size,
4798 required_buffer_size));
4802 if (fill_size > 0) {
4803 GST_DEBUG_OBJECT (qtmux,
4804 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4805 required_buffer_size);
4806 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4807 gst_memory_map (mem, &map, GST_MAP_WRITE);
4808 memset (map.data, 0, map.size);
4809 gst_memory_unmap (mem, &map);
4810 last_buf = gst_buffer_make_writable (last_buf);
4811 gst_buffer_append_memory (last_buf, mem);
4812 buffer_size = required_buffer_size;
4816 /* duration actually means time delta between samples, so we calculate
4817 * the duration based on the difference in DTS or PTS, falling back
4818 * to DURATION if the other two don't exist, such as with the last
4819 * sample before EOS. Or use 0 if nothing else is available */
4820 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4821 duration = GST_BUFFER_DURATION (last_buf);
4825 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4826 && GST_BUFFER_DTS_IS_VALID (last_buf))
4827 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4828 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4829 && GST_BUFFER_PTS_IS_VALID (last_buf))
4830 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4833 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4834 GST_DEBUG_OBJECT (qtmux,
4835 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4836 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4837 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4838 qtmux->current_chunk_size,
4839 GST_TIME_ARGS (qtmux->current_chunk_duration));
4840 qtmux->current_pad = pad;
4841 if (qtmux->current_chunk_offset == -1)
4842 qtmux->current_chunk_offset = qtmux->mdat_size;
4844 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4845 qtmux->current_chunk_size = 0;
4846 qtmux->current_chunk_duration = 0;
4849 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4850 atom_trak_get_timescale (pad->trak), GST_SECOND);
4852 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4853 if (pad->sample_size && !qtmux->fragment_sequence) {
4854 GstClockTime expected_timestamp;
4856 /* Constant size packets: usually raw audio (with many samples per
4857 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4859 sample_size = pad->sample_size;
4860 if (buffer_size % sample_size != 0)
4861 goto fragmented_sample;
4863 /* note: qt raw audio storage warps it implicitly into a timewise
4864 * perfect stream, discarding buffer times.
4865 * If the difference between the current PTS and the expected one
4866 * becomes too big, we error out: there was a gap and we have no way to
4867 * represent that, causing A/V sync to be off */
4868 expected_timestamp =
4869 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4870 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4871 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4872 expected_timestamp) > qtmux->max_raw_audio_drift)
4873 goto raw_audio_timestamp_drift;
4875 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4876 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4877 atom_trak_get_timescale (pad->trak), GST_SECOND);
4878 duration = GST_BUFFER_DURATION (last_buf);
4880 nsamples = buffer_size / sample_size;
4882 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4883 atom_trak_get_timescale (pad->trak));
4886 /* timescale = samplerate */
4887 scaled_duration = 1;
4889 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4890 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4893 sample_size = buffer_size;
4894 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4895 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4897 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4898 pad->last_dts = GST_BUFFER_DTS (buf);
4900 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4902 if ((gint64) (pad->last_dts) < 0) {
4903 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4904 atom_trak_get_timescale (pad->trak), GST_SECOND);
4906 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4907 atom_trak_get_timescale (pad->trak), GST_SECOND);
4909 scaled_duration = scaled_dts - last_dts;
4910 last_dts = scaled_dts;
4912 /* first convert intended timestamp (in GstClockTime resolution) to
4913 * trak timescale, then derive delta;
4914 * this ensures sums of (scale)delta add up to converted timestamp,
4915 * which only deviates at most 1/scale from timestamp itself */
4916 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4917 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4918 pad->last_dts += duration;
4922 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4924 chunk_offset = qtmux->current_chunk_offset;
4926 GST_LOG_OBJECT (qtmux,
4927 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4928 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4929 GST_LOG_OBJECT (qtmux,
4930 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4931 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4932 nsamples, scaled_duration, sample_size, chunk_offset);
4934 /* might be a sync sample */
4936 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4937 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4938 GST_PAD_NAME (pad->collect.pad));
4942 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4943 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4944 atom_trak_get_timescale (pad->trak), GST_SECOND);
4946 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4947 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4950 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4951 atom_trak_get_timescale (pad->trak), GST_SECOND);
4953 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4954 " timebase_dts: %d pts_offset: %d",
4955 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4956 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4957 (int) (last_dts), (int) (pts_offset));
4959 if (GST_CLOCK_TIME_IS_VALID (duration)
4960 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4961 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4962 GST_DEBUG_OBJECT (qtmux,
4963 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4964 GST_TIME_ARGS (qtmux->current_chunk_duration),
4965 GST_PAD_NAME (pad->collect.pad));
4966 qtmux->longest_chunk = qtmux->current_chunk_duration;
4969 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4970 const TrakBufferEntryInfo *sample_entry;
4971 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4973 if (block_idx >= pad->samples->len) {
4974 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4975 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4976 block_idx, pad->samples->len));
4980 /* Check if all values are as expected */
4982 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4984 if (chunk_offset < sample_entry->chunk_offset) {
4985 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4986 GstBuffer *fill_buf;
4988 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4989 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4991 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4992 if (ret != GST_FLOW_OK)
4994 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4995 qtmux->current_chunk_size = buffer_size;
4996 qtmux->current_chunk_duration = duration;
4997 } else if (chunk_offset != sample_entry->chunk_offset) {
4998 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4999 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
5000 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
5005 /* now we go and register this buffer/sample all over */
5006 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
5007 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
5008 chunk_offset, sync, TRUE, pts_offset);
5009 pad->sample_offset += nsamples;
5011 /* if this is sparse and we have a next buffer, check if there is any gap
5012 * between them to insert an empty sample */
5013 if (pad->sparse && buf) {
5014 if (pad->create_empty_buffer) {
5015 GstBuffer *empty_buf;
5016 gint64 empty_duration =
5017 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
5018 gint64 empty_duration_scaled;
5021 empty_buf = pad->create_empty_buffer (pad, empty_duration);
5023 pad->last_dts = GST_BUFFER_PTS (buf);
5024 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
5025 atom_trak_get_timescale (pad->trak), GST_SECOND)
5026 - (last_dts + scaled_duration);
5027 empty_size = gst_buffer_get_size (empty_buf);
5029 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
5033 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
5034 last_dts + scaled_duration, empty_duration_scaled,
5035 empty_size, chunk_offset, sync, TRUE, 0);
5036 } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
5037 /* This assert is kept here to make sure implementors of new
5038 * sparse input format decide whether there needs to be special
5039 * gap handling or not */
5040 g_assert_not_reached ();
5041 GST_WARNING_OBJECT (qtmux,
5042 "no empty buffer creation function found for pad %s",
5043 GST_PAD_NAME (pad->collect.pad));
5047 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
5048 gst_qt_mux_update_expected_trailer_size(qtmux, pad);
5049 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
5058 gst_buffer_unref (last_buf);
5059 return GST_FLOW_ERROR;
5063 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5064 ("Audio buffer contains fragmented sample."));
5067 raw_audio_timestamp_drift:
5069 /* TODO: Could in theory be implemented with edit lists */
5070 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5071 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
5072 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
5073 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
5074 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
5076 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
5081 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
5086 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
5087 ("format wasn't negotiated before buffer flow on pad %s",
5088 GST_PAD_NAME (pad->collect.pad)));
5090 gst_buffer_unref (buf);
5091 return GST_FLOW_NOT_NEGOTIATED;
5096 * DTS running time can be negative. There is no way to represent that in
5097 * MP4 however, thus we need to offset DTS so that it starts from 0.
5100 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
5101 GstCollectData * cdata, GstBuffer ** buf)
5106 pts = GST_BUFFER_PTS (*buf);
5107 dts = GST_COLLECT_PADS_DTS (cdata);
5109 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
5110 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
5111 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
5113 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
5114 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
5115 pad->dts_adjustment = -dts;
5117 pad->dts_adjustment = 0;
5120 if (pad->dts_adjustment > 0) {
5121 *buf = gst_buffer_make_writable (*buf);
5123 dts += pad->dts_adjustment;
5125 if (GST_CLOCK_TIME_IS_VALID (pts))
5126 pts += pad->dts_adjustment;
5128 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
5129 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
5134 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
5138 GST_BUFFER_PTS (*buf) = pts;
5139 GST_BUFFER_DTS (*buf) = dts;
5141 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
5142 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
5147 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
5150 GstQTPad *best_pad = NULL;
5152 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
5153 guint64 smallest_offset = G_MAXUINT64;
5154 guint64 chunk_offset = 0;
5156 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
5157 GstCollectData *cdata = (GstCollectData *) walk->data;
5158 GstQTPad *qtpad = (GstQTPad *) cdata;
5159 const TrakBufferEntryInfo *sample_entry;
5160 guint64 block_idx, current_block_idx;
5161 guint64 chunk_offset_offset = 0;
5162 GstBuffer *tmp_buf =
5163 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
5165 /* Check for EOS pads and just skip them */
5166 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
5167 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
5170 gst_buffer_unref (tmp_buf);
5172 /* Find the exact offset where the next sample of this track is supposed
5173 * to be written at */
5174 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
5176 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
5177 while (block_idx > 0) {
5178 const TrakBufferEntryInfo *tmp =
5179 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
5181 if (tmp->chunk_offset != sample_entry->chunk_offset)
5183 chunk_offset_offset += tmp->size * tmp->nsamples;
5187 /* Except for the previously selected pad being EOS we always have
5188 * qtmux->current_chunk_offset + qtmux->current_chunk_size
5190 * sample_entry->chunk_offset + chunk_offset_offset
5191 * for the best pad. Instead of checking that, we just return the
5192 * pad that has the smallest offset for the next to-be-written sample.
5194 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
5195 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
5197 chunk_offset = sample_entry->chunk_offset;
5201 if (chunk_offset != qtmux->current_chunk_offset) {
5202 qtmux->current_pad = NULL;
5208 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
5209 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
5210 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
5211 && (qtmux->interleave_time == 0
5212 || qtmux->current_chunk_duration <= qtmux->interleave_time)
5213 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
5214 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
5215 GstBuffer *tmp_buf =
5216 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
5218 if (tmp_buf || qtmux->current_pad->last_buf) {
5219 best_pad = qtmux->current_pad;
5221 gst_buffer_unref (tmp_buf);
5222 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
5223 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
5225 } else if (qtmux->collect->data->next) {
5226 /* Only switch pads if we have more than one, otherwise
5227 * we can just put everything into a single chunk and save
5228 * a few bytes of offsets
5230 if (qtmux->current_pad)
5231 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
5232 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
5233 best_pad = qtmux->current_pad = NULL;
5237 GstClockTime best_time = GST_CLOCK_TIME_NONE;
5239 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
5240 GstCollectData *cdata = (GstCollectData *) walk->data;
5241 GstQTPad *qtpad = (GstQTPad *) cdata;
5243 GstClockTime timestamp;
5245 tmp_buf = gst_collect_pads_peek (pads, cdata);
5247 /* This one is newly EOS now, finish it for real */
5248 if (qtpad->last_buf) {
5249 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5254 if (qtpad->last_buf)
5255 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5257 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
5260 if (best_pad == NULL ||
5261 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
5263 best_time = timestamp;
5267 gst_buffer_unref (tmp_buf);
5271 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
5272 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
5274 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
5281 static GstFlowReturn
5282 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
5284 GstFlowReturn ret = GST_FLOW_OK;
5285 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
5286 GstQTPad *best_pad = NULL;
5288 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
5289 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
5292 qtmux->state = GST_QT_MUX_STATE_DATA;
5295 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
5296 return GST_FLOW_EOS;
5298 best_pad = find_best_pad (qtmux, pads);
5300 /* clipping already converted to running time */
5301 if (best_pad != NULL) {
5302 GstBuffer *buf = NULL;
5304 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
5305 best_pad->raw_audio_adapter == NULL ||
5306 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
5307 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
5309 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
5310 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
5313 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
5314 (GstCollectData *) best_pad, &buf);
5316 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5318 qtmux->state = GST_QT_MUX_STATE_EOS;
5319 ret = gst_qt_mux_stop_file (qtmux);
5320 if (ret == GST_FLOW_OK) {
5321 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
5322 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5325 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5326 gst_flow_get_name (ret));
5334 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5336 GstStructure *structure = (GstStructure *) user_data;
5337 const GValue *other = gst_structure_id_get_value (structure, field_id);
5340 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5344 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5347 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5348 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5350 return gst_structure_foreach (sub_s, check_field, sup_s);
5353 /* will unref @qtmux */
5355 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5357 GstCaps *current_caps;
5359 /* does not go well to renegotiate stream mid-way, unless
5360 * the old caps are a subset of the new one (this means upstream
5361 * added more info to the caps, as both should be 'fixed' caps) */
5362 current_caps = gst_pad_get_current_caps (pad);
5363 g_assert (caps != NULL);
5365 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5366 gst_caps_unref (current_caps);
5367 GST_WARNING_OBJECT (qtmux,
5368 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5369 GST_PAD_NAME (pad), caps);
5370 gst_object_unref (qtmux);
5374 GST_DEBUG_OBJECT (qtmux,
5375 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5376 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5377 gst_object_unref (qtmux);
5378 gst_caps_unref (current_caps);
5384 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5386 GstPad *pad = qtpad->collect.pad;
5387 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5388 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5389 GstStructure *structure;
5390 const gchar *mimetype;
5391 gint rate, channels;
5392 const GValue *value = NULL;
5393 const GstBuffer *codec_data = NULL;
5394 GstQTMuxFormat format;
5395 AudioSampleEntry entry = { 0, };
5396 AtomInfo *ext_atom = NULL;
5397 gint constant_size = 0;
5398 const gchar *stream_format;
5402 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5404 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5405 GST_DEBUG_PAD_NAME (pad), caps);
5407 qtpad->prepare_buf_func = NULL;
5409 format = qtmux_klass->format;
5410 structure = gst_caps_get_structure (caps, 0);
5411 mimetype = gst_structure_get_name (structure);
5414 if (!gst_structure_get_int (structure, "channels", &channels) ||
5415 !gst_structure_get_int (structure, "rate", &rate)) {
5420 value = gst_structure_get_value (structure, "codec_data");
5422 codec_data = gst_value_get_buffer (value);
5424 qtpad->is_out_of_order = FALSE;
5426 /* set common properties */
5427 entry.sample_rate = rate;
5428 entry.channels = channels;
5430 entry.sample_size = 16;
5431 /* this is the typical compressed case */
5432 if (format == GST_QT_MUX_FORMAT_QT) {
5434 entry.compression_id = -2;
5437 /* now map onto a fourcc, and some extra properties */
5438 if (strcmp (mimetype, "audio/mpeg") == 0) {
5439 gint mpegversion = 0, mpegaudioversion = 0;
5442 gst_structure_get_int (structure, "mpegversion", &mpegversion);
5443 switch (mpegversion) {
5445 gst_structure_get_int (structure, "layer", &layer);
5446 gst_structure_get_int (structure, "mpegaudioversion",
5450 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5451 if (format == GST_QT_MUX_FORMAT_QT)
5452 entry.fourcc = FOURCC__mp3;
5454 entry.fourcc = FOURCC_mp4a;
5456 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5457 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5458 qtpad->max_bitrate);
5461 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5462 || format == GST_QT_MUX_FORMAT_QT);
5463 entry.samples_per_packet = 384;
5464 } else if (layer == 2) {
5465 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5466 || format == GST_QT_MUX_FORMAT_QT);
5467 entry.samples_per_packet = 1152;
5469 g_warn_if_fail (layer == 3);
5470 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5472 entry.bytes_per_sample = 2;
5476 /* check stream-format */
5477 stream_format = gst_structure_get_string (structure, "stream-format");
5478 if (stream_format) {
5479 if (strcmp (stream_format, "raw") != 0) {
5480 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5481 "please use 'raw'", stream_format);
5485 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5489 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5490 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5495 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5496 /* warn if not Low Complexity profile */
5499 GST_WARNING_OBJECT (qtmux,
5500 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5504 entry.fourcc = FOURCC_mp4a;
5506 if (format == GST_QT_MUX_FORMAT_QT)
5507 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5508 qtpad->avg_bitrate, qtpad->max_bitrate);
5511 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5512 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5513 qtpad->max_bitrate);
5518 } else if (strcmp (mimetype, "audio/AMR") == 0) {
5519 entry.fourcc = FOURCC_samr;
5520 entry.sample_size = 16;
5521 entry.samples_per_packet = 160;
5522 entry.bytes_per_sample = 2;
5523 ext_atom = build_amr_extension ();
5524 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5525 entry.fourcc = FOURCC_sawb;
5526 entry.sample_size = 16;
5527 entry.samples_per_packet = 320;
5528 entry.bytes_per_sample = 2;
5529 ext_atom = build_amr_extension ();
5530 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5533 gst_audio_info_init (&info);
5534 if (!gst_audio_info_from_caps (&info, caps))
5537 /* spec has no place for a distinction in these */
5538 if (info.finfo->width != info.finfo->depth) {
5539 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5543 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5544 if (info.finfo->endianness == G_LITTLE_ENDIAN)
5545 entry.fourcc = FOURCC_sowt;
5546 else if (info.finfo->endianness == G_BIG_ENDIAN)
5547 entry.fourcc = FOURCC_twos;
5549 entry.fourcc = FOURCC_sowt;
5550 /* maximum backward compatibility; only new version for > 16 bit */
5551 if (info.finfo->depth <= 16)
5553 /* not compressed in any case */
5554 entry.compression_id = 0;
5555 /* QT spec says: max at 16 bit even if sample size were actually larger,
5556 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5557 entry.sample_size = info.finfo->depth;
5558 entry.bytes_per_sample = info.finfo->depth / 8;
5559 entry.samples_per_packet = 1;
5560 entry.bytes_per_packet = info.finfo->depth / 8;
5561 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5563 if (info.finfo->width == 8 && info.finfo->depth == 8) {
5564 /* fall back to old 8-bit version */
5565 entry.fourcc = FOURCC_raw_;
5567 entry.compression_id = 0;
5568 entry.sample_size = 8;
5570 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5574 constant_size = (info.finfo->depth / 8) * info.channels;
5575 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5576 entry.fourcc = FOURCC_alaw;
5577 entry.samples_per_packet = 1023;
5578 entry.bytes_per_sample = 2;
5579 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5580 entry.fourcc = FOURCC_ulaw;
5581 entry.samples_per_packet = 1023;
5582 entry.bytes_per_sample = 2;
5583 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5585 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5586 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5589 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5591 entry.fourcc = MS_WAVE_FOURCC (0x11);
5592 /* 4 byte header per channel (including one sample). 2 samples per byte
5593 remaining. Simplifying gives the following (samples per block per
5595 entry.samples_per_packet = 2 * blocksize / channels - 7;
5596 entry.bytes_per_sample = 2;
5598 entry.bytes_per_frame = blocksize;
5599 entry.bytes_per_packet = blocksize / channels;
5600 /* ADPCM has constant size packets */
5602 /* TODO: I don't really understand why this helps, but it does! Constant
5603 * size and compression_id of -2 seem to be incompatible, and other files
5604 * in the wild use this too. */
5605 entry.compression_id = -1;
5607 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5608 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5609 GstBuffer *codec_config;
5613 entry.fourcc = FOURCC_alac;
5614 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5615 /* let's check if codec data already comes with 'alac' atom prefix */
5616 if (!codec_data || (len = map.size) < 28) {
5617 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5618 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5621 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5624 gst_buffer_copy_region ((GstBuffer *) codec_data,
5625 GST_BUFFER_COPY_MEMORY, 8, len);
5627 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5629 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5631 /* does not look good, but perhaps some trailing unneeded stuff */
5632 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5634 if (format == GST_QT_MUX_FORMAT_QT)
5635 ext_atom = build_mov_alac_extension (codec_config);
5637 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5638 /* set some more info */
5639 gst_buffer_map (codec_config, &map, GST_MAP_READ);
5640 entry.bytes_per_sample = 2;
5641 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5642 gst_buffer_unmap (codec_config, &map);
5643 gst_buffer_unref (codec_config);
5644 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5645 entry.fourcc = FOURCC_ac_3;
5647 /* Fixed values according to TS 102 366 but it also mentions that
5648 * they should be ignored */
5650 entry.sample_size = 16;
5652 /* AC-3 needs an extension atom but its data can only be obtained from
5653 * the stream itself. Abuse the prepare_buf_func so we parse a frame
5654 * and get the needed data */
5655 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5656 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5657 /* Based on the specification defined in:
5658 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5659 guint8 channels, mapping_family, stream_count, coupled_count;
5663 guint8 channel_mapping[256];
5664 const GValue *streamheader;
5665 const GValue *first_element;
5668 entry.fourcc = FOURCC_opus;
5669 entry.sample_size = 16;
5671 streamheader = gst_structure_get_value (structure, "streamheader");
5672 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5673 gst_value_array_get_size (streamheader) != 0) {
5674 first_element = gst_value_array_get_value (streamheader, 0);
5675 header = gst_value_get_buffer (first_element);
5676 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5677 &mapping_family, &stream_count, &coupled_count, channel_mapping,
5678 &pre_skip, &output_gain)) {
5679 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5683 GST_WARNING_OBJECT (qtmux,
5684 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5686 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5687 &mapping_family, &stream_count, &coupled_count,
5689 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5696 entry.channels = channels;
5697 ext_atom = build_opus_extension (rate, channels, mapping_family,
5698 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5704 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5705 if (!timescale && qtmux->trak_timescale)
5706 timescale = qtmux->trak_timescale;
5707 else if (!timescale)
5708 timescale = entry.sample_rate;
5710 /* ok, set the pad info accordingly */
5711 qtpad->fourcc = entry.fourcc;
5712 qtpad->sample_size = constant_size;
5714 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5715 qtmux->context, &entry, timescale, ext_atom, constant_size);
5717 gst_object_unref (qtmux);
5723 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5724 GST_PAD_NAME (pad), caps);
5725 gst_object_unref (qtmux);
5731 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5733 GstPad *pad = qtpad->collect.pad;
5734 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5735 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5736 GstStructure *structure;
5737 const gchar *mimetype;
5738 gint width, height, depth = -1;
5739 gint framerate_num, framerate_den;
5741 const GValue *value = NULL;
5742 const GstBuffer *codec_data = NULL;
5743 VisualSampleEntry entry = { 0, };
5744 GstQTMuxFormat format;
5745 AtomInfo *ext_atom = NULL;
5746 GList *ext_atom_list = NULL;
5747 gboolean sync = FALSE;
5748 int par_num, par_den;
5749 const gchar *multiview_mode;
5752 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5754 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5755 GST_DEBUG_PAD_NAME (pad), caps);
5757 qtpad->prepare_buf_func = NULL;
5759 format = qtmux_klass->format;
5760 structure = gst_caps_get_structure (caps, 0);
5761 mimetype = gst_structure_get_name (structure);
5763 /* required parts */
5764 if (!gst_structure_get_int (structure, "width", &width) ||
5765 !gst_structure_get_int (structure, "height", &height))
5770 /* works as a default timebase */
5771 framerate_num = 10000;
5773 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5775 gst_structure_get_int (structure, "depth", &depth);
5776 value = gst_structure_get_value (structure, "codec_data");
5778 codec_data = gst_value_get_buffer (value);
5782 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5785 qtpad->is_out_of_order = FALSE;
5787 /* bring frame numerator into a range that ensures both reasonable resolution
5788 * as well as a fair duration */
5789 qtpad->expected_sample_duration_n = framerate_num;
5790 qtpad->expected_sample_duration_d = framerate_den;
5792 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5793 if (!rate && qtmux->trak_timescale)
5794 rate = qtmux->trak_timescale;
5796 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5798 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5801 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5802 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5803 GstVideoMultiviewMode mode;
5804 GstVideoMultiviewFlags flags = 0;
5806 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5807 gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5809 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5810 qtpad->trak->mdia.minf.stbl.svmi =
5812 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5814 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5815 qtpad->trak->mdia.minf.stbl.svmi =
5817 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5819 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5820 qtpad->trak->mdia.minf.stbl.svmi =
5822 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5825 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5831 /* set common properties */
5832 entry.width = width;
5833 entry.height = height;
5834 entry.par_n = par_num;
5835 entry.par_d = par_den;
5836 /* should be OK according to qt and iso spec, override if really needed */
5837 entry.color_table_id = -1;
5838 entry.frame_count = 1;
5841 /* sync entries by default */
5844 /* now map onto a fourcc, and some extra properties */
5845 if (strcmp (mimetype, "video/x-raw") == 0) {
5846 const gchar *format;
5848 const GstVideoFormatInfo *vinfo;
5850 format = gst_structure_get_string (structure, "format");
5851 fmt = gst_video_format_from_string (format);
5852 vinfo = gst_video_format_get_info (fmt);
5855 case GST_VIDEO_FORMAT_UYVY:
5858 entry.fourcc = FOURCC_2vuy;
5859 entry.depth = depth;
5862 case GST_VIDEO_FORMAT_v210:
5865 entry.fourcc = FOURCC_v210;
5866 entry.depth = depth;
5870 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5871 entry.fourcc = FOURCC_raw_;
5872 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5877 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5879 if (format == GST_QT_MUX_FORMAT_QT)
5880 entry.fourcc = FOURCC_h263;
5882 entry.fourcc = FOURCC_s263;
5883 ext_atom = build_h263_extension ();
5884 if (ext_atom != NULL)
5885 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5886 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5887 strcmp (mimetype, "video/mpeg") == 0) {
5890 if (strcmp (mimetype, "video/x-divx") == 0) {
5891 gst_structure_get_int (structure, "divxversion", &version);
5892 version = version == 5 ? 1 : 0;
5894 gst_structure_get_int (structure, "mpegversion", &version);
5895 version = version == 4 ? 1 : 0;
5898 entry.fourcc = FOURCC_mp4v;
5900 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5901 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5902 qtpad->max_bitrate);
5903 if (ext_atom != NULL)
5904 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5906 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5907 "output might not play in Apple QuickTime (try global-headers?)");
5909 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5911 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5915 entry.fourcc = FOURCC_avc1;
5917 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5918 if (ext_atom != NULL)
5919 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5920 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5921 if (ext_atom != NULL)
5922 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5923 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5924 const gchar *format;
5927 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5931 format = gst_structure_get_string (structure, "stream-format");
5932 if (strcmp (format, "hvc1") == 0)
5933 entry.fourcc = FOURCC_hvc1;
5934 else if (strcmp (format, "hev1") == 0)
5935 entry.fourcc = FOURCC_hev1;
5937 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5938 if (ext_atom != NULL)
5939 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5941 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5942 if (ext_atom != NULL)
5943 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5945 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5947 const GstBuffer *seqh = NULL;
5948 const GValue *seqh_value;
5951 gst_structure_get_int (structure, "svqversion", &version);
5953 entry.fourcc = FOURCC_SVQ3;
5957 seqh_value = gst_structure_get_value (structure, "seqh");
5959 seqh = gst_value_get_buffer (seqh_value);
5960 ext_atom = build_SMI_atom (seqh);
5962 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5965 /* we need to add the gamma anyway because quicktime might crash
5966 * when it doesn't find it */
5967 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5968 /* it seems that using 0 here makes it ignored */
5971 ext_atom = build_gama_atom (gamma);
5973 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5975 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5976 "a bug at http://bugzilla.gnome.org", version);
5978 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5980 gboolean pal = TRUE;
5983 if (framerate_num != 25 || framerate_den != 1)
5985 gst_structure_get_int (structure, "dvversion", &version);
5986 /* fall back to typical one */
5992 entry.fourcc = FOURCC_dvcp;
5994 entry.fourcc = FOURCC_dvc_;
5998 entry.fourcc = FOURCC_dv5p;
6000 entry.fourcc = FOURCC_dv5n;
6003 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
6006 } else if (strcmp (mimetype, "image/jpeg") == 0) {
6007 entry.fourcc = FOURCC_jpeg;
6009 } else if (strcmp (mimetype, "image/png") == 0) {
6010 entry.fourcc = FOURCC_png;
6012 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
6013 strcmp (mimetype, "image/x-jpc") == 0) {
6014 const gchar *colorspace;
6015 const GValue *cmap_array;
6016 const GValue *cdef_array;
6019 if (strcmp (mimetype, "image/x-jpc") == 0) {
6020 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
6023 gst_structure_get_int (structure, "num-components", &ncomp);
6024 cmap_array = gst_structure_get_value (structure, "component-map");
6025 cdef_array = gst_structure_get_value (structure, "channel-definitions");
6028 entry.fourcc = FOURCC_mjp2;
6031 colorspace = gst_structure_get_string (structure, "colorspace");
6034 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
6035 cdef_array)) != NULL) {
6036 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6038 ext_atom = build_jp2x_extension (codec_data);
6040 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6042 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
6045 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
6046 entry.fourcc = FOURCC_vp08;
6047 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
6048 entry.fourcc = FOURCC_vp09;
6049 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
6050 entry.fourcc = FOURCC_drac;
6051 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
6054 gst_structure_get_uint (structure, "format", &fourcc);
6055 entry.fourcc = fourcc;
6056 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
6059 gst_structure_get_uint (structure, "format", &fourcc);
6060 entry.fourcc = fourcc;
6061 } else if (strcmp (mimetype, "video/x-prores") == 0) {
6062 const gchar *variant;
6064 variant = gst_structure_get_string (structure, "variant");
6065 if (!variant || !g_strcmp0 (variant, "standard"))
6066 entry.fourcc = FOURCC_apcn;
6067 else if (!g_strcmp0 (variant, "lt"))
6068 entry.fourcc = FOURCC_apcs;
6069 else if (!g_strcmp0 (variant, "hq"))
6070 entry.fourcc = FOURCC_apch;
6071 else if (!g_strcmp0 (variant, "proxy"))
6072 entry.fourcc = FOURCC_apco;
6073 else if (!g_strcmp0 (variant, "4444"))
6074 entry.fourcc = FOURCC_ap4h;
6075 else if (!g_strcmp0 (variant, "4444xq"))
6076 entry.fourcc = FOURCC_ap4x;
6080 if (!qtmux->interleave_time_set)
6081 qtmux->interleave_time = 500 * GST_MSECOND;
6082 if (!qtmux->interleave_bytes_set)
6083 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
6084 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
6085 entry.fourcc = FOURCC_cfhd;
6087 } else if (strcmp (mimetype, "video/x-av1") == 0) {
6088 gint presentation_delay;
6089 guint8 presentation_delay_byte = 0;
6090 GstBuffer *av1_codec_data;
6092 if (gst_structure_get_int (structure, "presentation-delay",
6093 &presentation_delay)) {
6094 presentation_delay_byte = 1 << 5;
6095 presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
6099 av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
6100 /* Fill version and 3 bytes of flags to 0 */
6101 gst_buffer_memset (av1_codec_data, 0, 0, 4);
6102 gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
6104 av1_codec_data = gst_buffer_append (av1_codec_data,
6105 gst_buffer_ref ((GstBuffer *) codec_data));
6107 entry.fourcc = FOURCC_av01;
6109 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
6110 if (ext_atom != NULL)
6111 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6112 ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
6113 if (ext_atom != NULL)
6114 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6115 gst_buffer_unref (av1_codec_data);
6121 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
6122 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
6124 GstVideoColorimetry colorimetry;
6126 s = gst_structure_get_string (structure, "colorimetry");
6127 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
6129 build_colr_extension (&colorimetry,
6130 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
6132 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6136 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
6137 || strcmp (mimetype, "image/x-j2c") == 0
6138 || strcmp (mimetype, "image/x-jpc") == 0) {
6140 GstVideoInterlaceMode interlace_mode;
6141 GstVideoFieldOrder field_order;
6144 if (strcmp (mimetype, "image/x-j2c") == 0 ||
6145 strcmp (mimetype, "image/x-jpc") == 0) {
6148 gst_structure_get_int (structure, "fields", &fields);
6151 s = gst_structure_get_string (structure, "interlace-mode");
6153 interlace_mode = gst_video_interlace_mode_from_string (s);
6157 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
6158 GST_VIDEO_INTERLACE_MODE_MIXED;
6160 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
6161 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
6162 s = gst_structure_get_string (structure, "field-order");
6164 field_order = gst_video_field_order_from_string (s);
6167 ext_atom = build_fiel_extension (interlace_mode, field_order);
6169 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6173 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
6174 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
6175 /* The 'clap' extension is also defined for MP4 but inventing values in
6176 * general seems a bit tricky for this one. We only write it for
6177 * SD resolution in MOV, where it is a requirement.
6178 * The same goes for the 'tapt' extension, just that it is not defined for
6179 * MP4 and only for MOV
6181 gint dar_num, dar_den;
6182 gint clef_width, clef_height, prof_width;
6183 gint clap_width_n, clap_width_d, clap_height;
6187 /* First, guess display aspect ratio based on pixel aspect ratio,
6188 * width and height. We assume that display aspect ratio is either
6191 approx_dar = (gdouble) (width * par_num) / (height * par_den);
6192 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
6195 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
6199 dar_num = width * par_num;
6200 dar_den = height * par_den;
6201 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
6206 /* Then, calculate clean-aperture values (clap and clef)
6207 * using the guessed DAR.
6209 clef_height = clap_height = (height == 486 ? 480 : height);
6210 clef_width = gst_util_uint64_scale (clef_height,
6211 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
6212 prof_width = gst_util_uint64_scale (width,
6213 par_num * G_GUINT64_CONSTANT (65536), par_den);
6214 clap_width_n = clap_height * dar_num * par_den;
6215 clap_width_d = dar_den * par_num;
6216 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
6217 clap_width_n /= cdiv;
6218 clap_width_d /= cdiv;
6220 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
6221 height << 16, width << 16, height << 16);
6222 qtpad->trak->tapt = ext_atom;
6224 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
6225 clap_height, 1, 0, 1, 0, 1);
6227 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6230 /* ok, set the pad info accordingly */
6231 qtpad->fourcc = entry.fourcc;
6234 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
6235 qtmux->context, &entry, rate, ext_atom_list);
6236 if (strcmp (mimetype, "video/x-prores") == 0) {
6237 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
6238 const gchar *compressor = NULL;
6239 mp4v->spatial_quality = 0x3FF;
6240 mp4v->temporal_quality = 0;
6241 mp4v->vendor = FOURCC_appl;
6242 mp4v->horizontal_resolution = 72 << 16;
6243 mp4v->vertical_resolution = 72 << 16;
6244 mp4v->depth = (entry.fourcc == FOURCC_ap4h
6245 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
6247 /* Set compressor name, required by some software */
6248 switch (entry.fourcc) {
6250 compressor = "Apple ProRes 422";
6253 compressor = "Apple ProRes 422 LT";
6256 compressor = "Apple ProRes 422 HQ";
6259 compressor = "Apple ProRes 422 Proxy";
6262 compressor = "Apple ProRes 4444";
6265 compressor = "Apple ProRes 4444 XQ";
6269 strcpy ((gchar *) mp4v->compressor + 1, compressor);
6270 mp4v->compressor[0] = strlen (compressor);
6274 gst_object_unref (qtmux);
6280 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6281 GST_PAD_NAME (pad), caps);
6282 gst_object_unref (qtmux);
6288 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6290 GstPad *pad = qtpad->collect.pad;
6291 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6292 GstStructure *structure;
6293 SubtitleSampleEntry entry = { 0, };
6296 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6298 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6299 GST_DEBUG_PAD_NAME (pad), caps);
6301 /* subtitles default */
6302 subtitle_sample_entry_init (&entry);
6303 qtpad->is_out_of_order = FALSE;
6304 qtpad->sync = FALSE;
6305 qtpad->sparse = TRUE;
6306 qtpad->prepare_buf_func = NULL;
6308 structure = gst_caps_get_structure (caps, 0);
6310 if (gst_structure_has_name (structure, "text/x-raw")) {
6311 const gchar *format = gst_structure_get_string (structure, "format");
6312 if (format && strcmp (format, "utf8") == 0) {
6313 entry.fourcc = FOURCC_tx3g;
6314 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6315 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6322 qtpad->fourcc = entry.fourcc;
6324 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6325 qtmux->context, &entry);
6327 gst_object_unref (qtmux);
6333 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6334 GST_PAD_NAME (pad), caps);
6335 gst_object_unref (qtmux);
6341 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6343 GstPad *pad = qtpad->collect.pad;
6344 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6345 GstStructure *structure;
6346 guint32 fourcc_entry;
6350 return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6352 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6353 GST_DEBUG_PAD_NAME (pad), caps);
6355 /* captions default */
6356 qtpad->is_out_of_order = FALSE;
6357 qtpad->sync = FALSE;
6358 qtpad->sparse = TRUE;
6359 /* Closed caption data are within atoms */
6360 qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6362 structure = gst_caps_get_structure (caps, 0);
6364 /* We know we only handle 608,format=s334-1a and 708,format=cdp */
6365 if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6366 fourcc_entry = FOURCC_c608;
6367 } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6368 fourcc_entry = FOURCC_c708;
6372 /* We set the real timescale later to the one from the video track when
6373 * writing the headers */
6374 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6375 if (!timescale && qtmux->trak_timescale)
6376 timescale = qtmux->trak_timescale;
6377 else if (!timescale)
6380 qtpad->fourcc = fourcc_entry;
6382 (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6383 qtmux->context, timescale, fourcc_entry);
6385 /* Initialize caption track language code to 0 unless something else is
6386 * specified. Without this, Final Cut considers it "non-standard"
6388 qtpad->trak->mdia.mdhd.language_code = 0;
6390 gst_object_unref (qtmux);
6396 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6397 GST_PAD_NAME (pad), caps);
6398 gst_object_unref (qtmux);
6404 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6405 GstEvent * event, gpointer user_data)
6408 guint32 avg_bitrate = 0, max_bitrate = 0;
6409 GstPad *pad = data->pad;
6410 gboolean ret = TRUE;
6412 qtmux = GST_QT_MUX_CAST (user_data);
6413 switch (GST_EVENT_TYPE (event)) {
6414 case GST_EVENT_CAPS:
6417 GstQTPad *collect_pad;
6419 gst_event_parse_caps (event, &caps);
6421 /* find stream data */
6422 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6423 g_assert (collect_pad);
6424 g_assert (collect_pad->set_caps);
6426 ret = collect_pad->set_caps (collect_pad, caps);
6427 gst_event_unref (event);
6431 case GST_EVENT_TAG:{
6433 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6434 GstTagMergeMode mode;
6436 GstQTPad *collect_pad;
6438 GST_OBJECT_LOCK (qtmux);
6439 mode = gst_tag_setter_get_tag_merge_mode (setter);
6440 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6442 gst_event_parse_tag (event, &list);
6443 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6444 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6446 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6447 gst_tag_setter_merge_tags (setter, list, mode);
6448 qtmux->tags_changed = TRUE;
6450 if (!collect_pad->tags)
6451 collect_pad->tags = gst_tag_list_new_empty ();
6452 gst_tag_list_insert (collect_pad->tags, list, mode);
6453 collect_pad->tags_changed = TRUE;
6455 GST_OBJECT_UNLOCK (qtmux);
6457 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6458 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6459 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6462 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6463 qtpad->avg_bitrate = avg_bitrate;
6464 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6465 qtpad->max_bitrate = max_bitrate;
6468 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6469 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6471 GstQTPad *qtpad = gst_pad_get_element_private (pad);
6474 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6475 qtpad->trak->mdia.mdhd.language_code = language_code (iso_code);
6481 gst_event_unref (event);
6491 return gst_collect_pads_event_default (pads, data, event, FALSE);
6497 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6499 GstQTMux *mux = GST_QT_MUX_CAST (element);
6502 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6504 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6505 GstQTPad *qtpad = (GstQTPad *) walk->data;
6506 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6507 if (qtpad->collect.pad == pad) {
6508 /* this is it, remove */
6509 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6510 gst_element_remove_pad (element, pad);
6515 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6516 mux->current_pad = NULL;
6517 mux->current_chunk_size = 0;
6518 mux->current_chunk_duration = 0;
6521 gst_collect_pads_remove_pad (mux->collect, pad);
6523 if (mux->sinkpads == NULL) {
6524 /* No more outstanding request pads, reset our counters */
6525 mux->video_pads = 0;
6526 mux->audio_pads = 0;
6527 mux->subtitle_pads = 0;
6532 gst_qt_mux_request_new_pad (GstElement * element,
6533 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6535 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6536 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6537 GstQTPad *collect_pad;
6539 GstQTPadSetCapsFunc setcaps_func;
6542 gboolean lock = TRUE;
6544 if (templ->direction != GST_PAD_SINK)
6545 goto wrong_direction;
6547 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6550 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6551 setcaps_func = gst_qt_mux_audio_sink_set_caps;
6552 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6553 name = g_strdup (req_name);
6555 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6557 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6558 setcaps_func = gst_qt_mux_video_sink_set_caps;
6559 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6560 name = g_strdup (req_name);
6562 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6564 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6565 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6566 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6567 name = g_strdup (req_name);
6569 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6572 } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6573 setcaps_func = gst_qt_mux_caption_sink_set_caps;
6574 if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6575 name = g_strdup (req_name);
6577 name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6581 goto wrong_template;
6583 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6585 /* create pad and add to collections */
6587 g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6588 templ->direction, "template", templ, NULL);
6590 collect_pad = (GstQTPad *)
6591 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6592 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6594 gst_qt_mux_pad_reset (collect_pad);
6595 collect_pad->trak = atom_trak_new (qtmux->context);
6596 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6598 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6600 /* set up pad functions */
6601 collect_pad->set_caps = setcaps_func;
6603 gst_pad_set_active (newpad, TRUE);
6604 gst_element_add_pad (element, newpad);
6611 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6616 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6621 GST_WARNING_OBJECT (qtmux, "This is not our template!");
6627 gst_qt_mux_get_property (GObject * object,
6628 guint prop_id, GValue * value, GParamSpec * pspec)
6630 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6632 GST_OBJECT_LOCK (qtmux);
6634 case PROP_MOVIE_TIMESCALE:
6635 g_value_set_uint (value, qtmux->timescale);
6637 case PROP_TRAK_TIMESCALE:
6638 g_value_set_uint (value, qtmux->trak_timescale);
6641 g_value_set_boolean (value, qtmux->guess_pts);
6643 #ifndef GST_REMOVE_DEPRECATED
6644 case PROP_DTS_METHOD:
6645 g_value_set_enum (value, qtmux->dts_method);
6648 case PROP_FAST_START:
6649 g_value_set_boolean (value, qtmux->fast_start);
6651 case PROP_FAST_START_TEMP_FILE:
6652 g_value_set_string (value, qtmux->fast_start_file_path);
6654 case PROP_MOOV_RECOV_FILE:
6655 g_value_set_string (value, qtmux->moov_recov_file_path);
6657 case PROP_FRAGMENT_DURATION:
6658 g_value_set_uint (value, qtmux->fragment_duration);
6660 case PROP_STREAMABLE:
6661 g_value_set_boolean (value, qtmux->streamable);
6663 case PROP_RESERVED_MAX_DURATION:
6664 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6666 case PROP_RESERVED_DURATION_REMAINING:
6667 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6668 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6670 GstClockTime remaining = qtmux->reserved_duration_remaining;
6672 /* Report the remaining space as the calculated remaining, minus
6673 * however much we've muxed since the last update */
6674 if (remaining > qtmux->muxed_since_last_update)
6675 remaining -= qtmux->muxed_since_last_update;
6678 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6679 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6680 remaining, qtmux->reserved_duration_remaining,
6681 qtmux->muxed_since_last_update);
6682 g_value_set_uint64 (value, remaining);
6685 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6686 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6688 case PROP_RESERVED_BYTES_PER_SEC:
6689 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6691 case PROP_RESERVED_PREFILL:
6692 g_value_set_boolean (value, qtmux->reserved_prefill);
6694 case PROP_INTERLEAVE_BYTES:
6695 g_value_set_uint64 (value, qtmux->interleave_bytes);
6697 case PROP_INTERLEAVE_TIME:
6698 g_value_set_uint64 (value, qtmux->interleave_time);
6700 case PROP_MAX_RAW_AUDIO_DRIFT:
6701 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6703 case PROP_START_GAP_THRESHOLD:
6704 g_value_set_uint64 (value, qtmux->start_gap_threshold);
6706 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
6707 case PROP_EXPECTED_TRAILER_SIZE:
6708 g_value_set_uint(value, qtmux->expected_trailer_size);
6710 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
6712 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6715 GST_OBJECT_UNLOCK (qtmux);
6719 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6723 g_free (qtmux->fast_start_file_path);
6724 qtmux->fast_start_file_path = NULL;
6726 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6727 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6732 gst_qt_mux_set_property (GObject * object,
6733 guint prop_id, const GValue * value, GParamSpec * pspec)
6735 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6737 GST_OBJECT_LOCK (qtmux);
6739 case PROP_MOVIE_TIMESCALE:
6740 qtmux->timescale = g_value_get_uint (value);
6742 case PROP_TRAK_TIMESCALE:
6743 qtmux->trak_timescale = g_value_get_uint (value);
6746 qtmux->guess_pts = g_value_get_boolean (value);
6748 #ifndef GST_REMOVE_DEPRECATED
6749 case PROP_DTS_METHOD:
6750 qtmux->dts_method = g_value_get_enum (value);
6753 case PROP_FAST_START:
6754 qtmux->fast_start = g_value_get_boolean (value);
6756 case PROP_FAST_START_TEMP_FILE:
6757 g_free (qtmux->fast_start_file_path);
6758 qtmux->fast_start_file_path = g_value_dup_string (value);
6759 /* NULL means to generate a random one */
6760 if (!qtmux->fast_start_file_path) {
6761 gst_qt_mux_generate_fast_start_file_path (qtmux);
6764 case PROP_MOOV_RECOV_FILE:
6765 g_free (qtmux->moov_recov_file_path);
6766 qtmux->moov_recov_file_path = g_value_dup_string (value);
6768 case PROP_FRAGMENT_DURATION:
6769 qtmux->fragment_duration = g_value_get_uint (value);
6771 case PROP_STREAMABLE:{
6772 GstQTMuxClass *qtmux_klass =
6773 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6774 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6775 qtmux->streamable = g_value_get_boolean (value);
6779 case PROP_RESERVED_MAX_DURATION:
6780 qtmux->reserved_max_duration = g_value_get_uint64 (value);
6782 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6783 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6785 case PROP_RESERVED_BYTES_PER_SEC:
6786 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6788 case PROP_RESERVED_PREFILL:
6789 qtmux->reserved_prefill = g_value_get_boolean (value);
6791 case PROP_INTERLEAVE_BYTES:
6792 qtmux->interleave_bytes = g_value_get_uint64 (value);
6793 qtmux->interleave_bytes_set = TRUE;
6795 case PROP_INTERLEAVE_TIME:
6796 qtmux->interleave_time = g_value_get_uint64 (value);
6797 qtmux->interleave_time_set = TRUE;
6799 case PROP_MAX_RAW_AUDIO_DRIFT:
6800 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6802 case PROP_START_GAP_THRESHOLD:
6803 qtmux->start_gap_threshold = g_value_get_uint64 (value);
6806 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6809 GST_OBJECT_UNLOCK (qtmux);
6812 static GstStateChangeReturn
6813 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6815 GstStateChangeReturn ret;
6816 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6818 switch (transition) {
6819 case GST_STATE_CHANGE_NULL_TO_READY:
6821 case GST_STATE_CHANGE_READY_TO_PAUSED:
6822 gst_collect_pads_start (qtmux->collect);
6823 qtmux->state = GST_QT_MUX_STATE_STARTED;
6825 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6827 case GST_STATE_CHANGE_PAUSED_TO_READY:
6828 gst_collect_pads_stop (qtmux->collect);
6834 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6836 switch (transition) {
6837 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6839 case GST_STATE_CHANGE_PAUSED_TO_READY:
6840 gst_qt_mux_reset (qtmux, TRUE);
6842 case GST_STATE_CHANGE_READY_TO_NULL:
6852 gst_qt_mux_register (GstPlugin * plugin)
6854 GTypeInfo typeinfo = {
6855 sizeof (GstQTMuxClass),
6856 (GBaseInitFunc) gst_qt_mux_base_init,
6858 (GClassInitFunc) gst_qt_mux_class_init,
6863 (GInstanceInitFunc) gst_qt_mux_init,
6865 static const GInterfaceInfo tag_setter_info = {
6868 static const GInterfaceInfo tag_xmp_writer_info = {
6871 static const GInterfaceInfo preset_info = {
6875 GstQTMuxFormat format;
6876 GstQTMuxClassParams *params;
6879 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6881 GST_LOG ("Registering muxers");
6884 GstQTMuxFormatProp *prop;
6885 GstCaps *subtitle_caps, *caption_caps;
6887 prop = &gst_qt_mux_format_list[i];
6888 format = prop->format;
6889 if (format == GST_QT_MUX_FORMAT_NONE)
6892 /* create a cache for these properties */
6893 params = g_new0 (GstQTMuxClassParams, 1);
6894 params->prop = prop;
6895 params->src_caps = gst_static_caps_get (&prop->src_caps);
6896 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6897 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6898 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6899 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6900 params->subtitle_sink_caps = subtitle_caps;
6902 gst_caps_unref (subtitle_caps);
6904 caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6905 if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6906 params->caption_sink_caps = caption_caps;
6908 gst_caps_unref (caption_caps);
6911 /* create the type now */
6912 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6914 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6915 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6916 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6917 &tag_xmp_writer_info);
6918 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6920 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6926 GST_LOG ("Finished registering muxers");
6928 /* FIXME: ideally classification tag should be added and
6929 registered in gstreamer core gsttaglist
6932 GST_LOG ("Registering tags");
6934 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6935 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6936 gst_tag_merge_use_first);
6938 GST_LOG ("Finished registering tags");