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) allow
69 * adjusting some technical parameters, which might be useful in (rare) cases to
70 * resolve compatibility issues in some situations.
72 * Some other properties influence the result more fundamentally.
73 * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
74 * file, somewhat contrary to this usually being called "the header".
75 * However, a #GstQTMux:faststart file will (with some effort) arrange this to
76 * be located near start of the file, which then allows it e.g. to be played
77 * while downloading. Alternatively, rather than having one chunk of metadata at
78 * start (or end), there can be some metadata at start and most of the other
79 * data can be spread out into fragments of #GstQTMux:fragment-duration.
80 * If such fragmented layout is intended for streaming purposes, then
81 * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
84 * When the maximum duration to be recorded can be known in advance, #GstQTMux
85 * also supports a 'Robust Muxing' mode. In robust muxing mode, space for the
86 * headers are reserved at the start of muxing, and rewritten at a configurable
87 * interval, so that the output file is always playable, even if the recording
88 * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
89 * output, such as filesink, because it needs to rewrite the start of the file.
91 * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
92 * and #GstQTMux::reserved-max-duration property. Also present is the
93 * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
94 * for some reason the default is not large enough and the initial reserved
95 * space for headers is too small. Applications can monitor the
96 * #GstQTMux::reserved-duration-remaining property to see how close to full
97 * the reserved space is becoming.
100 * <title>Example pipelines</title>
102 * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
104 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
116 #include <glib/gstdio.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/base/gstbytereader.h>
121 #include <gst/base/gstbitreader.h>
122 #include <gst/audio/audio.h>
123 #include <gst/video/video.h>
124 #include <gst/tag/tag.h>
126 #include <sys/types.h>
128 #include <io.h> /* lseek, open, close, read */
130 #define lseek _lseeki64
132 #define off_t guint64
136 #define ftruncate g_win32_ftruncate
143 #include "gstqtmux.h"
145 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
146 #define GST_CAT_DEFAULT gst_qt_mux_debug
150 * The basic building blocks of MP4 files are:
151 * - an 'ftyp' box at the very start
152 * - an 'mdat' box which contains the raw audio/video/subtitle data;
153 * this is just a bunch of bytes, completely unframed and possibly
154 * unordered with no additional meta-information
155 * - a 'moov' box that contains information about the different streams
156 * and what they contain, as well as sample tables for each stream
157 * that tell the demuxer where in the mdat box each buffer/sample is
158 * and what its duration/timestamp etc. is, and whether it's a
160 * Additionally, fragmented MP4 works by writing chunks of data in
161 * pairs of 'moof' and 'mdat' boxes:
162 * - 'moof' boxes, header preceding each mdat fragment describing the
163 * contents, like a moov but only for that fragment.
164 * - a 'mfra' box for Fragmented MP4, which is written at the end and
165 * contains a summary of all fragments and seek tables.
167 * Currently mp4mux can work in 4 different modes / generate 4 types
168 * of output files/streams:
170 * - Normal mp4: mp4mux will write a little ftyp identifier at the
171 * beginning, then start an mdat box into which it will write all the
172 * sample data. At EOS it will then write the moov header with track
173 * headers and sample tables at the end of the file, and rewrite the
174 * start of the file to fix up the mdat box size at the beginning.
175 * It has to wait for EOS to write the moov (which includes the
176 * sample tables) because it doesn't know how much space those
177 * tables will be. The output downstream must be seekable to rewrite
178 * the mdat box at EOS.
180 * - Fragmented mp4: moov header with track headers at start
181 * but no sample table, followed by N fragments, each containing
182 * track headers with sample tables followed by some data. Downstream
183 * does not need to be seekable if the 'streamable' flag is TRUE,
184 * as the final mfra and total duration will be omitted.
186 * - Fast-start mp4: the goal here is to create a file where the moov
187 * headers are at the beginning; what mp4mux will do is write all
188 * sample data into a temp file and build moov header plus sample
189 * tables in memory and then when EOS comes, it will push out the
190 * moov header plus sample tables at the beginning, followed by the
191 * mdat sample data at the end which is read in from the temp file
192 * Files created in this mode are better for streaming over the
193 * network, since the client doesn't have to seek to the end of the
194 * file to get the headers, but it requires copying all sample data
195 * out of the temp file at EOS, which can be expensive. Downstream does
196 * not need to be seekable, because of the use of the temp file.
198 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
199 * and reserved-moov-update-period properties to reserve free space
200 * at the start of the file and periodically write the MOOV atom out
201 * to it. That means that killing the muxing at any point still
202 * results in a playable file, at the cost of wasting some amount of
203 * free space at the start of file. The approximate recording duration
204 * has to be known in advance to estimate how much free space to reserve
205 * for the moov, and the downstream must be seekable.
206 * If the moov header grows larger than the reserved space, an error
207 * is generated - so it's better to over-estimate the amount of space
208 * to reserve. To ensure the file is playable at any point, the moov
209 * is updated using a 'ping-pong' strategy, so the output is never in
213 #ifndef GST_REMOVE_DEPRECATED
222 gst_qt_mux_dts_method_get_type (void)
224 static GType gst_qt_mux_dts_method = 0;
226 if (!gst_qt_mux_dts_method) {
227 static const GEnumValue dts_methods[] = {
228 {DTS_METHOD_DD, "delta/duration", "dd"},
229 {DTS_METHOD_REORDER, "reorder", "reorder"},
230 {DTS_METHOD_ASC, "ascending", "asc"},
234 gst_qt_mux_dts_method =
235 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
238 return gst_qt_mux_dts_method;
241 #define GST_TYPE_QT_MUX_DTS_METHOD \
242 (gst_qt_mux_dts_method_get_type ())
245 /* QTMux signals and args */
255 PROP_MOVIE_TIMESCALE,
258 PROP_FAST_START_TEMP_FILE,
259 PROP_MOOV_RECOV_FILE,
260 PROP_FRAGMENT_DURATION,
262 PROP_RESERVED_MAX_DURATION,
263 PROP_RESERVED_DURATION_REMAINING,
264 PROP_RESERVED_MOOV_UPDATE_PERIOD,
265 PROP_RESERVED_BYTES_PER_SEC,
266 #ifndef GST_REMOVE_DEPRECATED
270 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
271 PROP_EXPECTED_TRAILER_SIZE,
272 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
275 /* some spare for header size as well */
276 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
278 #define DEFAULT_MOVIE_TIMESCALE 1800
279 #define DEFAULT_TRAK_TIMESCALE 0
280 #define DEFAULT_DO_CTTS TRUE
281 #define DEFAULT_FAST_START FALSE
282 #define DEFAULT_FAST_START_TEMP_FILE NULL
283 #define DEFAULT_MOOV_RECOV_FILE NULL
284 #define DEFAULT_FRAGMENT_DURATION 0
285 #define DEFAULT_STREAMABLE TRUE
286 #ifndef GST_REMOVE_DEPRECATED
287 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
289 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
290 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
291 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
293 static void gst_qt_mux_finalize (GObject * object);
295 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
296 GstStateChange transition);
298 /* property functions */
299 static void gst_qt_mux_set_property (GObject * object,
300 guint prop_id, const GValue * value, GParamSpec * pspec);
301 static void gst_qt_mux_get_property (GObject * object,
302 guint prop_id, GValue * value, GParamSpec * pspec);
305 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
306 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
307 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
310 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
311 GstCollectData * data, GstEvent * event, gpointer user_data);
313 static GstFlowReturn gst_qt_mux_handle_buffer (GstCollectPads * pads,
314 GstCollectData * cdata, GstBuffer * buf, gpointer user_data);
315 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
319 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
321 static GstElementClass *parent_class = NULL;
323 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
342 dinf = 36 (8, dref : 16 , url : 12)
347 ii. Variation in file format
355 iii. Variation in codec
357 stsd = 137(16, mp4v : 86, esds : 35)
359 - H.264 = 487(or 489) + (8*stts_count) + (8*frame) + (4*I-frame)
360 stsd = 134 (SPS 9, PPS 4) or 136 (SPS 111, PPS 4)
362 - H.263 = 470 + + (8*stts_count) + (8*frame) + (4*I-frame)
363 stsd = 102 -> different from H.264
365 iv. Variation in frame
366 stts = 16 + (8*stts_count)
367 stss = 16 + (4*I-frame)
369 stsz = 20 + (4*frame)
370 stco = 16 + (4*frame)
381 dinf = 36 (8, dref : 16, url : 12)
392 ii. Variation in file format
398 iii. Variation in codec
400 stts = 16 + (8*stts_count)
402 stsz = 20 + (4*frame)
403 stco = 16 + (4*frame)
406 stsd = 94 (16, mp4a : 78(36 ,esds : 42))
409 stsd = 69 (16, samr : 53(36, damr : 17))
412 /* trailer entry size */
413 #define ENTRY_SIZE_VIDEO_STTS 8
414 #define ENTRY_SIZE_VIDEO_STSS 4
415 #define ENTRY_SIZE_VIDEO_STSZ 4
416 #define ENTRY_SIZE_VIDEO_STCO 4
417 #define ENTRY_SIZE_AUDIO_STTS 8
418 #define ENTRY_SIZE_AUDIO_STSZ 4
419 #define ENTRY_SIZE_AUDIO_STCO 4
421 #define ENTRY_SIZE_VIDEO_MPEG4_STSD 137
422 #define ENTRY_SIZE_VIDEO_H263P_STSD 102
423 #define ENTRY_SIZE_AUDIO_AAC_STSD 94
424 #define ENTRY_SIZE_AUDIO_AMR_STSD 69
426 #define ENTRY_SIZE_STSC 28
427 #define ENTRY_SIZE_VIDEO_ST 68 /*atom size (stss + stts + stsc + stsz + stco ) * (size + atom + version + flags + sample count)+stsz(sample size) */
428 #define ENTRY_SIZE_AUDIO_ST 52 /*atom size (stss + stsc + stsz + stco ) * (size + atom + version + flags + sample count)+stsz(sample size) */
431 #define MUX_COMMON_SIZE_HEADER 124 /* free + moov + moov.mvhd*/
433 #define MUX_COMMON_SIZE_VIDEO_HEADER 257
434 #define MUX_COMMON_SIZE_AUDIO_HEADER 253
436 #define MUX_COMMON_SIZE_MP4_FTYP 32
437 #define MUX_COMMON_SIZE_3GP_FTYP 28
439 #define MUX_COMMON_SIZE_MP4_UDTA 61
440 #define MUX_COMMON_SIZE_3GP_UDTA 8
443 gst_qt_mux_update_expected_trailer_size (GstQTMux *qtmux, GstQTPad *pad)
445 guint nb_video_frames = 0;
446 guint nb_video_i_frames = 0;
447 guint nb_video_stts_entry = 0;
448 guint nb_audio_frames = 0;
449 guint nb_audio_stts_entry = 0;
450 gboolean video_stream = FALSE;
451 gboolean audio_stream = FALSE;
453 GstQTMuxClass *qtmux_klass = NULL;
455 if (qtmux == NULL || pad == NULL) {
456 GST_ERROR_OBJECT (qtmux, "Invalid parameter");
460 qtmux_klass = (GstQTMuxClass *)(G_OBJECT_GET_CLASS(qtmux));
462 if (!strncmp(GST_PAD_NAME(pad->collect.pad), "video", 5)) {
463 nb_video_frames += pad->trak->mdia.minf.stbl.stsz.table_size;
464 nb_video_i_frames += pad->trak->mdia.minf.stbl.stss.entries.len;
465 nb_video_stts_entry += pad->trak->mdia.minf.stbl.stts.entries.len;
468 } else if (!strncmp(GST_PAD_NAME(pad->collect.pad), "audio", 5)) {
469 nb_audio_frames += pad->trak->mdia.minf.stbl.stsz.table_size;
470 nb_audio_stts_entry += pad->trak->mdia.minf.stbl.stts.entries.len;
475 /* free + moov + mvhd */
476 qtmux->expected_trailer_size = MUX_COMMON_SIZE_HEADER;
478 /* ftyp + udta * 3 (There is 3 udta fields and it's same size) */
479 switch (qtmux_klass->format) {
480 case GST_QT_MUX_FORMAT_MP4:
481 qtmux->expected_trailer_size += MUX_COMMON_SIZE_MP4_FTYP + MUX_COMMON_SIZE_MP4_UDTA * 3;
483 case GST_QT_MUX_FORMAT_3GP:
484 qtmux->expected_trailer_size += MUX_COMMON_SIZE_3GP_FTYP + MUX_COMMON_SIZE_3GP_UDTA * 3;
490 /* Calculate trailer size for video stream */
492 switch (pad->fourcc) {
495 exp_size += MUX_COMMON_SIZE_VIDEO_HEADER + ENTRY_SIZE_VIDEO_H263P_STSD;
504 exp_size += MUX_COMMON_SIZE_VIDEO_HEADER + ENTRY_SIZE_VIDEO_MPEG4_STSD;
511 exp_size += ENTRY_SIZE_VIDEO_ST + (ENTRY_SIZE_VIDEO_STTS * nb_video_stts_entry) +
512 (ENTRY_SIZE_VIDEO_STSS * nb_video_i_frames) + (ENTRY_SIZE_STSC) +
513 ((ENTRY_SIZE_VIDEO_STSZ + ENTRY_SIZE_VIDEO_STCO) * nb_video_frames);
515 qtmux->video_expected_trailer_size = exp_size;
518 /* Calculate trailer size for audio stream */
520 exp_size += MUX_COMMON_SIZE_AUDIO_HEADER + ENTRY_SIZE_AUDIO_ST + (ENTRY_SIZE_AUDIO_STTS * nb_audio_stts_entry) +
521 (ENTRY_SIZE_STSC) + ((ENTRY_SIZE_AUDIO_STSZ + ENTRY_SIZE_AUDIO_STCO) * nb_audio_frames);
523 if (pad->fourcc == FOURCC_samr)
524 exp_size += ENTRY_SIZE_AUDIO_AMR_STSD;
526 exp_size += ENTRY_SIZE_AUDIO_AAC_STSD;
528 qtmux->audio_expected_trailer_size = exp_size;
531 qtmux->expected_trailer_size += qtmux->video_expected_trailer_size + qtmux->audio_expected_trailer_size;
534 GST_INFO_OBJECT (qtmux, "pad type %s", GST_PAD_NAME(pad->collect.pad));
535 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);
536 GST_INFO_OBJECT (qtmux, "AUDIO : stts-entry=[%d], audio-sample=[%d]", nb_audio_stts_entry, nb_audio_frames);
537 GST_INFO_OBJECT (qtmux, "expected trailer size %d", qtmux->expected_trailer_size);
542 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
545 gst_qt_mux_base_init (gpointer g_class)
547 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
548 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
549 GstQTMuxClassParams *params;
550 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
551 GstPadTemplate *srctempl;
552 gchar *longname, *description;
555 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
556 GST_QT_MUX_PARAMS_QDATA);
557 g_assert (params != NULL);
559 /* construct the element details struct */
560 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
561 description = g_strdup_printf ("Multiplex audio and video into a %s file",
562 params->prop->long_name);
563 gst_element_class_set_static_metadata (element_class, longname,
564 "Codec/Muxer", description,
565 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
567 g_free (description);
570 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
571 GST_PAD_ALWAYS, params->src_caps);
572 gst_element_class_add_pad_template (element_class, srctempl);
574 if (params->audio_sink_caps) {
575 audiosinktempl = gst_pad_template_new ("audio_%u",
576 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
577 gst_element_class_add_pad_template (element_class, audiosinktempl);
580 if (params->video_sink_caps) {
581 videosinktempl = gst_pad_template_new ("video_%u",
582 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
583 gst_element_class_add_pad_template (element_class, videosinktempl);
586 if (params->subtitle_sink_caps) {
587 subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
588 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
589 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
592 klass->format = params->prop->format;
596 gst_qt_mux_class_init (GstQTMuxClass * klass)
598 GObjectClass *gobject_class;
599 GstElementClass *gstelement_class;
600 GParamFlags streamable_flags;
601 const gchar *streamable_desc;
603 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
604 GParamSpec *tspec = NULL;
605 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
606 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
607 "be streamed and hence no indexes written or duration written."
609 gobject_class = (GObjectClass *) klass;
610 gstelement_class = (GstElementClass *) klass;
612 parent_class = g_type_class_peek_parent (klass);
614 gobject_class->finalize = gst_qt_mux_finalize;
615 gobject_class->get_property = gst_qt_mux_get_property;
616 gobject_class->set_property = gst_qt_mux_set_property;
618 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
619 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
620 streamable_desc = STREAMABLE_DESC;
621 streamable = DEFAULT_STREAMABLE;
624 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
625 streamable_flags |= G_PARAM_DEPRECATED;
629 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
630 g_param_spec_uint ("movie-timescale", "Movie timescale",
631 "Timescale to use in the movie (units per second)",
632 1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
633 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
634 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
635 g_param_spec_uint ("trak-timescale", "Track timescale",
636 "Timescale to use for the tracks (units per second, 0 is automatic)",
637 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
638 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
639 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
640 g_param_spec_boolean ("presentation-time",
641 "Include presentation-time info",
642 "Calculate and include presentation/composition time "
643 "(in addition to decoding time)", DEFAULT_DO_CTTS,
644 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
645 #ifndef GST_REMOVE_DEPRECATED
646 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
647 g_param_spec_enum ("dts-method", "dts-method",
648 "Method to determine DTS time (DEPRECATED)",
649 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
650 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
651 G_PARAM_STATIC_STRINGS));
653 g_object_class_install_property (gobject_class, PROP_FAST_START,
654 g_param_spec_boolean ("faststart", "Format file to faststart",
655 "If the file should be formatted for faststart (headers first)",
656 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
657 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
658 g_param_spec_string ("faststart-file", "File to use for storing buffers",
659 "File that will be used temporarily to store data from the stream "
660 "when creating a faststart file. If null a filepath will be "
661 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
662 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
663 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
664 g_param_spec_string ("moov-recovery-file",
665 "File to store data for posterior moov atom recovery",
666 "File to be used to store "
667 "data for moov atom making movie file recovery possible in case "
668 "of a crash during muxing. Null for disabled. (Experimental)",
669 DEFAULT_MOOV_RECOV_FILE,
670 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
671 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
672 g_param_spec_uint ("fragment-duration", "Fragment duration",
673 "Fragment durations in ms (produce a fragmented file if > 0)",
674 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
675 2000 : DEFAULT_FRAGMENT_DURATION,
676 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
677 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
678 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
679 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
680 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
681 g_param_spec_uint64 ("reserved-max-duration",
682 "Reserved maximum file duration (ns)",
683 "When set to a value > 0, reserves space for index tables at the "
684 "beginning of the file.",
685 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
686 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
687 g_object_class_install_property (gobject_class,
688 PROP_RESERVED_DURATION_REMAINING,
689 g_param_spec_uint64 ("reserved-duration-remaining",
690 "Report the approximate amount of remaining recording space (ns)",
691 "Reports the approximate amount of remaining moov header space "
692 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
693 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
694 g_object_class_install_property (gobject_class,
695 PROP_RESERVED_MOOV_UPDATE_PERIOD,
696 g_param_spec_uint64 ("reserved-moov-update-period",
697 "Interval at which to update index tables (ns)",
698 "When used with reserved-max-duration, periodically updates the "
699 "index tables with information muxed so far.", 0, G_MAXUINT64,
700 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
701 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
702 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
703 g_param_spec_uint ("reserved-bytes-per-sec",
704 "Reserved MOOV bytes per second, per track",
705 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
706 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
707 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
709 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
710 tspec = g_param_spec_uint("expected-trailer-size", "Expected Trailer Size",
711 "Expected trailer size (bytes)",
712 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
714 g_object_class_install_property(gobject_class, PROP_EXPECTED_TRAILER_SIZE, tspec);
716 GST_ERROR("g_param_spec failed for \"expected-trailer-size\"");
717 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
719 gstelement_class->request_new_pad =
720 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
721 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
722 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
726 gst_qt_mux_pad_reset (GstQTPad * qtpad)
729 qtpad->is_out_of_order = FALSE;
730 qtpad->sample_size = 0;
733 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
734 qtpad->first_ts = GST_CLOCK_TIME_NONE;
735 qtpad->first_dts = GST_CLOCK_TIME_NONE;
736 qtpad->prepare_buf_func = NULL;
737 qtpad->create_empty_buffer = NULL;
738 qtpad->avg_bitrate = 0;
739 qtpad->max_bitrate = 0;
740 qtpad->total_duration = 0;
741 qtpad->total_bytes = 0;
742 qtpad->sparse = FALSE;
747 gst_buffer_replace (&qtpad->last_buf, NULL);
750 gst_tag_list_unref (qtpad->tags);
754 /* reference owned elsewhere */
758 atom_traf_free (qtpad->traf);
761 atom_array_clear (&qtpad->fragment_buffers);
763 /* reference owned elsewhere */
768 * Takes GstQTMux back to its initial state
771 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
775 qtmux->state = GST_QT_MUX_STATE_NONE;
776 qtmux->header_size = 0;
777 qtmux->mdat_size = 0;
780 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
781 qtmux->video_pads = 0;
782 qtmux->audio_pads = 0;
783 qtmux->fragment_sequence = 0;
786 atom_ftyp_free (qtmux->ftyp);
790 atom_moov_free (qtmux->moov);
794 atom_mfra_free (qtmux->mfra);
797 if (qtmux->fast_start_file) {
798 fclose (qtmux->fast_start_file);
799 g_remove (qtmux->fast_start_file_path);
800 qtmux->fast_start_file = NULL;
802 if (qtmux->moov_recov_file) {
803 fclose (qtmux->moov_recov_file);
804 qtmux->moov_recov_file = NULL;
806 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
807 AtomInfo *ainfo = (AtomInfo *) walk->data;
808 ainfo->free_func (ainfo->atom);
811 g_slist_free (qtmux->extra_atoms);
812 qtmux->extra_atoms = NULL;
814 GST_OBJECT_LOCK (qtmux);
815 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
816 GST_OBJECT_UNLOCK (qtmux);
819 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
820 GstQTPad *qtpad = (GstQTPad *) walk->data;
821 gst_qt_mux_pad_reset (qtpad);
823 /* hm, moov_free above yanked the traks away from us,
824 * so do not free, but do clear */
829 qtmux->moov = atom_moov_new (qtmux->context);
830 /* ensure all is as nice and fresh as request_new_pad would provide it */
831 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
832 GstQTPad *qtpad = (GstQTPad *) walk->data;
834 qtpad->trak = atom_trak_new (qtmux->context);
835 atom_moov_add_trak (qtmux->moov, qtpad->trak);
839 qtmux->reserved_moov_size = 0;
840 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
841 qtmux->muxed_since_last_update = 0;
842 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
844 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
845 qtmux->expected_trailer_size = 0;
846 qtmux->video_expected_trailer_size = 0;
847 qtmux->audio_expected_trailer_size = 0;
848 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
852 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
854 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
855 GstPadTemplate *templ;
857 templ = gst_element_class_get_pad_template (klass, "src");
858 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
859 gst_pad_use_fixed_caps (qtmux->srcpad);
860 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
862 qtmux->sinkpads = NULL;
863 qtmux->collect = gst_collect_pads_new ();
864 gst_collect_pads_set_buffer_function (qtmux->collect,
865 GST_DEBUG_FUNCPTR (gst_qt_mux_handle_buffer), qtmux);
866 gst_collect_pads_set_event_function (qtmux->collect,
867 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
868 gst_collect_pads_set_clip_function (qtmux->collect,
869 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
871 /* properties set to default upon construction */
873 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
874 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
875 qtmux->reserved_bytes_per_sec_per_trak =
876 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
878 /* always need this */
880 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
882 /* internals to initial state */
883 gst_qt_mux_reset (qtmux, TRUE);
888 gst_qt_mux_finalize (GObject * object)
890 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
892 gst_qt_mux_reset (qtmux, FALSE);
894 g_free (qtmux->fast_start_file_path);
895 g_free (qtmux->moov_recov_file_path);
897 atoms_context_free (qtmux->context);
898 gst_object_unref (qtmux->collect);
900 g_slist_free (qtmux->sinkpads);
902 G_OBJECT_CLASS (parent_class)->finalize (object);
906 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
913 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
918 size = gst_buffer_get_size (buf);
919 newbuf = gst_buffer_new_and_alloc (size + 8);
920 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
922 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
923 GST_WRITE_UINT32_BE (map.data, map.size);
924 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
926 gst_buffer_unmap (buf, &map);
927 gst_buffer_unref (buf);
933 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
940 const guint8 *dataend;
942 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
947 gst_buffer_map (buf, &frommap, GST_MAP_READ);
949 dataend = memchr (frommap.data, 0, frommap.size);
950 size = dataend ? dataend - frommap.data : frommap.size;
951 newbuf = gst_buffer_new_and_alloc (size + 2);
953 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
955 GST_WRITE_UINT16_BE (tomap.data, size);
956 memcpy (tomap.data + 2, frommap.data, size);
958 gst_buffer_unmap (newbuf, &tomap);
959 gst_buffer_unmap (buf, &frommap);
961 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
963 /* gst_buffer_copy_into is trying to be too clever and
964 * won't copy duration when size is different */
965 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
967 gst_buffer_unref (buf);
973 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
974 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
979 g_return_if_fail (qtpad->trak_ste);
981 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
983 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
987 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
991 GstByteReader reader;
994 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
995 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
999 if (G_UNLIKELY (map.size < 8))
1002 gst_byte_reader_init (&reader, map.data, map.size);
1003 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1008 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1010 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1013 gst_bit_reader_init (&bits, map.data, map.size);
1015 /* off + sync + crc */
1016 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1018 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1019 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1020 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1021 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1022 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1024 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1025 gst_bit_reader_skip_unchecked (&bits, 2);
1026 if ((acmod & 0x4)) /* if a surround channel exists */
1027 gst_bit_reader_skip_unchecked (&bits, 2);
1028 if (acmod == 0x2) /* if in 2/0 mode */
1029 gst_bit_reader_skip_unchecked (&bits, 2);
1031 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1033 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1034 bsmod, acmod, lfe_on);
1036 /* AC-3 spec says that those values should be constant for the
1037 * whole stream when muxed in mp4. We trust the input follows it */
1038 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1039 "prepare buffer function");
1040 qtpad->prepare_buf_func = NULL;
1044 gst_buffer_unmap (buf, &map);
1049 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1053 data = g_malloc (2);
1054 GST_WRITE_UINT16_BE (data, 0);
1056 return gst_buffer_new_wrapped (data, 2);
1060 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1061 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1063 switch (gst_tag_get_type (tag)) {
1069 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1071 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1072 GST_FOURCC_ARGS (fourcc), str);
1073 atom_udta_add_str_tag (udta, fourcc, str);
1082 if (!gst_tag_list_get_double (list, tag, &value))
1084 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1085 GST_FOURCC_ARGS (fourcc), (gint) value);
1086 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1093 /* paired unsigned integers */
1097 got_tag = gst_tag_list_get_uint (list, tag, &value);
1098 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1101 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1102 GST_FOURCC_ARGS (fourcc), value, count);
1103 atom_udta_add_uint_tag (udta, fourcc, 0,
1104 value << 16 | (count & 0xFFFF));
1106 /* unpaired unsigned integers */
1107 if (!gst_tag_list_get_uint (list, tag, &value))
1109 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1110 GST_FOURCC_ARGS (fourcc), value);
1111 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1116 g_assert_not_reached ();
1122 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1123 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1131 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1133 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1136 year = g_date_get_year (date);
1137 month = g_date_get_month (date);
1138 day = g_date_get_day (date);
1142 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1143 day == G_DATE_BAD_DAY) {
1144 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1148 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1149 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1150 GST_FOURCC_ARGS (fourcc), str);
1151 atom_udta_add_str_tag (udta, fourcc, str);
1156 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1157 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1159 GValue value = { 0, };
1163 GstStructure *structure;
1167 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1169 if (!gst_tag_list_copy_value (&value, list, tag))
1172 sample = gst_value_get_sample (&value);
1177 buf = gst_sample_get_buffer (sample);
1181 caps = gst_sample_get_caps (sample);
1183 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1187 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1189 structure = gst_caps_get_structure (caps, 0);
1190 if (gst_structure_has_name (structure, "image/jpeg"))
1192 else if (gst_structure_has_name (structure, "image/png"))
1196 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1200 gst_buffer_map (buf, &map, GST_MAP_READ);
1201 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1202 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1203 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1204 gst_buffer_unmap (buf, &map);
1206 g_value_unset (&value);
1210 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1211 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1216 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1217 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1219 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1223 if (!gst_tag_list_get_uint (list, tag2, &number))
1227 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1228 GST_FOURCC_ARGS (fourcc), str);
1229 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1231 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1232 GST_FOURCC_ARGS (fourcc), str, number);
1233 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1240 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1241 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1246 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1248 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1251 year = g_date_get_year (date);
1254 if (year == G_DATE_BAD_YEAR) {
1255 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1259 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1260 GST_FOURCC_ARGS (fourcc), year);
1261 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1265 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1266 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1268 gdouble latitude = -360, longitude = -360, altitude = 0;
1269 gchar *location = NULL;
1270 guint8 *data, *ddata;
1271 gint size = 0, len = 0;
1272 gboolean ret = FALSE;
1274 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1276 ret = gst_tag_list_get_string (list, tag, &location);
1277 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1279 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1281 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1288 len = strlen (location);
1289 size += len + 1 + 2;
1291 /* role + (long, lat, alt) + body + notes */
1292 size += 1 + 3 * 4 + 1 + 1;
1294 data = ddata = g_malloc (size);
1297 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1300 memcpy (data + 2, location, len);
1301 GST_WRITE_UINT8 (data + 2 + len, 0);
1302 data += len + 1 + 2;
1304 GST_WRITE_UINT8 (data, 0);
1305 /* long, lat, alt */
1306 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1307 QT_WRITE_SFP32 (data + 1, longitude);
1308 QT_WRITE_SFP32 (data + 5, latitude);
1309 QT_WRITE_SFP32 (data + 9, altitude);
1310 /* neither astronomical body nor notes */
1311 GST_WRITE_UINT16_BE (data + 13, 0);
1313 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1314 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1319 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1320 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1322 gchar *keywords = NULL;
1323 guint8 *data, *ddata;
1327 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1329 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1332 kwds = g_strsplit (keywords, ",", 0);
1336 for (i = 0; kwds[i]; i++) {
1337 /* size byte + null-terminator */
1338 size += strlen (kwds[i]) + 1 + 1;
1341 /* language tag + count + keywords */
1344 data = ddata = g_malloc (size);
1347 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1349 GST_WRITE_UINT8 (data + 2, i);
1352 for (i = 0; kwds[i]; ++i) {
1353 gint len = strlen (kwds[i]);
1355 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1356 GST_FOURCC_ARGS (fourcc), kwds[i]);
1358 GST_WRITE_UINT8 (data, len + 1);
1359 memcpy (data + 1, kwds[i], len + 1);
1365 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1370 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1371 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1379 size = strlen (input);
1381 if (size < 4 + 3 + 1 + 1 + 1) {
1382 /* at least the minimum xxxx://y/z */
1383 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1388 /* read the fourcc */
1389 memcpy (&fourcc, data, 4);
1393 if (strncmp (data, "://", 3) != 0) {
1399 /* read the table number */
1400 if (sscanf (data, "%d", &table) != 1) {
1404 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1405 ", table numbers should be positive, ignoring tag", table);
1409 /* find the next / */
1410 while (size > 0 && data[0] != '/') {
1417 g_assert (data[0] == '/');
1426 /* read up the rest of the string */
1427 *p_content = g_strdup (data);
1428 *p_table = (guint16) table;
1434 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1435 "input (%s) didn't match the expected entitycode://table/content",
1442 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1443 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1445 gchar *clsf_data = NULL;
1449 gchar *content = NULL;
1452 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1454 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1457 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1458 GST_FOURCC_ARGS (fourcc), clsf_data);
1460 /* parse the string, format is:
1461 * entityfourcc://table/content
1463 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1467 size = strlen (content) + 1;
1469 /* now we have everything, build the atom
1470 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1471 data = g_malloc (4 + 2 + 2 + size);
1472 GST_WRITE_UINT32_LE (data, entity);
1473 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1474 GST_WRITE_UINT16_BE (data + 6, 0);
1475 memcpy (data + 8, content, size);
1478 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1482 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1483 const GstTagList * list, AtomUDTA * udta, const char *tag,
1484 const char *tag2, guint32 fourcc);
1487 * Struct to record mappings from gstreamer tags to fourcc codes
1489 typedef struct _GstTagToFourcc
1492 const gchar *gsttag;
1493 const gchar *gsttag2;
1494 const GstQTMuxAddUdtaTagFunc func;
1497 /* tag list tags to fourcc matching */
1498 static const GstTagToFourcc tag_matches_mp4[] = {
1499 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1500 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1501 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1502 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1503 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1504 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1505 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1506 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1507 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1508 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1509 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1510 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1511 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1512 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1513 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1514 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1515 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1516 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1517 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1518 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1519 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1520 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1521 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1522 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1523 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1524 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1525 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1526 gst_qt_mux_add_mp4_tag},
1527 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1528 gst_qt_mux_add_mp4_tag},
1529 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1530 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1534 static const GstTagToFourcc tag_matches_3gp[] = {
1535 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1536 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1537 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1538 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1539 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1540 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1541 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1542 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1543 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1544 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1545 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1546 gst_qt_mux_add_3gp_classification},
1550 /* qtdemux produces these for atoms it cannot parse */
1551 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1554 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1556 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1557 GstBuffer *xmp = NULL;
1559 /* adobe specs only have 'quicktime' and 'mp4',
1560 * but I guess we can extrapolate to gpp.
1561 * Keep mj2 out for now as we don't add any tags for it yet.
1562 * If you have further info about xmp on these formats, please share */
1563 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1566 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1568 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1569 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1572 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1575 /* for isom/mp4, it is a top level uuid atom */
1576 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1579 ainfo = build_uuid_xmp_atom (xmp);
1581 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1586 gst_buffer_unref (xmp);
1590 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1593 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1596 const gchar *tag, *tag2;
1597 const GstTagToFourcc *tag_matches;
1599 switch (qtmux_klass->format) {
1600 case GST_QT_MUX_FORMAT_3GP:
1601 tag_matches = tag_matches_3gp;
1603 case GST_QT_MUX_FORMAT_MJ2:
1607 /* sort of iTunes style for mp4 and QT (?) */
1608 tag_matches = tag_matches_mp4;
1615 /* Clear existing tags so we don't add them over and over */
1616 atom_udta_clear_tags (udta);
1618 for (i = 0; tag_matches[i].fourcc; i++) {
1619 fourcc = tag_matches[i].fourcc;
1620 tag = tag_matches[i].gsttag;
1621 tag2 = tag_matches[i].gsttag2;
1623 g_assert (tag_matches[i].func);
1624 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1627 /* add unparsed blobs if present */
1628 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1631 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1632 for (i = 0; i < num_tags; ++i) {
1633 GstSample *sample = NULL;
1635 const GstStructure *s;
1637 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1640 buf = gst_sample_get_buffer (sample);
1642 if (buf && (s = gst_sample_get_info (sample))) {
1643 const gchar *style = NULL;
1646 gst_buffer_map (buf, &map, GST_MAP_READ);
1647 GST_DEBUG_OBJECT (qtmux,
1648 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1649 GST_PTR_FORMAT, i, num_tags, map.size, s);
1650 if (s && (style = gst_structure_get_string (s, "style"))) {
1651 /* try to prevent some style tag ending up into another variant
1652 * (todo: make into a list if more cases) */
1653 if ((strcmp (style, "itunes") == 0 &&
1654 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1655 (strcmp (style, "iso") == 0 &&
1656 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1657 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1658 atom_udta_add_blob_tag (udta, map.data, map.size);
1661 gst_buffer_unmap (buf, &map);
1663 gst_sample_unref (sample);
1671 * Gets the tagsetter iface taglist and puts the known tags
1672 * into the output stream
1675 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1677 const GstTagList *tags = NULL;
1680 GST_OBJECT_LOCK (qtmux);
1681 if (qtmux->tags_changed) {
1682 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1683 qtmux->tags_changed = FALSE;
1685 GST_OBJECT_UNLOCK (qtmux);
1687 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1689 if (tags && !gst_tag_list_is_empty (tags)) {
1690 GstTagList *copy = gst_tag_list_copy (tags);
1692 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1693 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1694 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1695 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1697 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1698 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1699 gst_qt_mux_add_xmp_tags (qtmux, copy);
1700 gst_tag_list_unref (copy);
1702 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1705 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1706 GstCollectData *cdata = (GstCollectData *) walk->data;
1707 GstQTPad *qpad = (GstQTPad *) cdata;
1708 GstPad *pad = qpad->collect.pad;
1710 if (qpad->tags_changed && qpad->tags) {
1711 GST_DEBUG_OBJECT (pad, "Adding tags");
1712 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1713 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1714 qpad->tags_changed = FALSE;
1715 GST_DEBUG_OBJECT (pad, "Tags added");
1717 GST_DEBUG_OBJECT (pad, "No new tags received");
1722 static inline GstBuffer *
1723 _gst_buffer_new_take_data (guint8 * data, guint size)
1727 buf = gst_buffer_new ();
1728 gst_buffer_append_memory (buf,
1729 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1734 static GstFlowReturn
1735 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1741 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1743 size = gst_buffer_get_size (buf);
1744 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1746 if (mind_fast && qtmux->fast_start_file) {
1750 GST_LOG_OBJECT (qtmux, "to temporary file");
1751 gst_buffer_map (buf, &map, GST_MAP_READ);
1752 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1753 gst_buffer_unmap (buf, &map);
1754 gst_buffer_unref (buf);
1760 GST_LOG_OBJECT (qtmux, "downstream");
1761 res = gst_pad_push (qtmux->srcpad, buf);
1764 if (G_LIKELY (offset))
1772 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1773 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1774 return GST_FLOW_ERROR;
1779 gst_qt_mux_seek_to_beginning (FILE * f)
1782 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1784 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1785 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1788 if (fseek (f, (long) 0, SEEK_SET) != 0)
1794 static GstFlowReturn
1795 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1797 GstFlowReturn ret = GST_FLOW_OK;
1798 GstBuffer *buf = NULL;
1800 if (fflush (qtmux->fast_start_file))
1803 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1806 /* hm, this could all take a really really long time,
1807 * but there may not be another way to get moov atom first
1808 * (somehow optimize copy?) */
1809 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1810 while (ret == GST_FLOW_OK) {
1811 const int bufsize = 4096;
1815 buf = gst_buffer_new_and_alloc (bufsize);
1816 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1817 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1819 gst_buffer_unmap (buf, &map);
1822 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1823 gst_buffer_unmap (buf, &map);
1824 if (size != bufsize)
1825 gst_buffer_set_size (buf, size);
1826 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1830 gst_buffer_unref (buf);
1832 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1834 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1842 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1843 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1844 ret = GST_FLOW_ERROR;
1849 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1850 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1851 ret = GST_FLOW_ERROR;
1856 /* clear descriptor so we don't remove temp file later on,
1857 * might be possible to recover */
1858 fclose (qtmux->fast_start_file);
1859 qtmux->fast_start_file = NULL;
1865 * Sends the initial mdat atom fields (size fields and fourcc type),
1866 * the subsequent buffers are considered part of it's data.
1867 * As we can't predict the amount of data that we are going to place in mdat
1868 * we need to record the position of the size field in the stream so we can
1869 * seek back to it later and update when the streams have finished.
1871 static GstFlowReturn
1872 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1873 gboolean extended, gboolean fsync_after)
1878 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1879 "size %" G_GUINT64_FORMAT, size);
1881 /* if the qtmux state is EOS, really write the mdat, otherwise
1882 * allow size == 0 for a placeholder atom */
1883 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1887 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1888 /* Always write 16-bytes, but put a free atom first
1889 * if the size is < 4GB. */
1890 buf = gst_buffer_new_and_alloc (16);
1891 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1894 /* Write extended mdat header and large_size field */
1895 GST_WRITE_UINT32_BE (map.data, 1);
1896 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1897 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1899 /* Write an empty free atom, then standard 32-bit mdat */
1900 GST_WRITE_UINT32_BE (map.data, 8);
1901 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1902 GST_WRITE_UINT32_BE (map.data + 8, size);
1903 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1905 gst_buffer_unmap (buf, &map);
1907 buf = gst_buffer_new_and_alloc (8);
1908 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1910 /* Vanilla 32-bit mdat */
1911 GST_WRITE_UINT32_BE (map.data, size);
1912 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1913 gst_buffer_unmap (buf, &map);
1916 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1918 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1920 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1925 * We get the position of the mdat size field, seek back to it
1926 * and overwrite with the real value
1928 static GstFlowReturn
1929 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1930 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1934 /* We must have recorded the mdat position for this to work */
1935 g_assert (mdat_pos != 0);
1937 /* seek and rewrite the header */
1938 gst_segment_init (&segment, GST_FORMAT_BYTES);
1939 segment.start = mdat_pos;
1940 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1942 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1946 static GstFlowReturn
1947 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1950 guint64 size = 0, offset = 0;
1951 guint8 *data = NULL;
1953 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1955 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1956 goto serialize_error;
1958 buf = _gst_buffer_new_take_data (data, offset);
1960 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1961 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1966 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1967 ("Failed to serialize ftyp"));
1968 return GST_FLOW_ERROR;
1973 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1974 GstBuffer ** p_prefix)
1976 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1977 guint32 major, version;
1979 GstBuffer *prefix = NULL;
1980 AtomFTYP *ftyp = NULL;
1982 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1984 /* init and send context and ftyp based on current property state */
1985 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1986 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1987 qtmux->fast_start_file != NULL);
1988 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1995 gst_buffer_unref (prefix);
2000 static GstFlowReturn
2001 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2003 GstFlowReturn ret = GST_FLOW_OK;
2004 GstBuffer *prefix = NULL;
2006 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2008 /* init and send context and ftyp based on current property state */
2010 atom_ftyp_free (qtmux->ftyp);
2013 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2015 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2016 if (ret != GST_FLOW_OK)
2019 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2023 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2025 GstStructure *structure;
2026 GValue array = { 0 };
2027 GValue value = { 0 };
2028 GstCaps *caps, *tcaps;
2030 tcaps = gst_pad_get_current_caps (mux->srcpad);
2031 caps = gst_caps_copy (tcaps);
2032 gst_caps_unref (tcaps);
2034 structure = gst_caps_get_structure (caps, 0);
2036 g_value_init (&array, GST_TYPE_ARRAY);
2038 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2039 g_value_init (&value, GST_TYPE_BUFFER);
2040 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2041 gst_value_array_append_value (&array, &value);
2042 g_value_unset (&value);
2044 gst_structure_set_value (structure, "streamheader", &array);
2045 g_value_unset (&array);
2046 gst_pad_set_caps (mux->srcpad, caps);
2047 gst_caps_unref (caps);
2051 * Write out a free space atom. The offset is adjusted by the full
2052 * size, but a smaller buffer is sent
2054 static GstFlowReturn
2055 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2056 gboolean fsync_after)
2060 guint8 *data = NULL;
2061 guint64 offset = 0, bsize = 0;
2064 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2066 /* We can't make a free space atom smaller than the header */
2070 node_header = g_malloc0 (sizeof (Atom));
2071 node_header->type = FOURCC_free;
2072 node_header->size = size;
2075 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2076 goto serialize_error;
2078 buf = _gst_buffer_new_take_data (data, offset);
2079 g_free (node_header);
2082 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2084 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2085 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2092 /* Make sure downstream position ends up at the end of this free box */
2093 gst_segment_init (&segment, GST_FORMAT_BYTES);
2094 segment.start = *off;
2095 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2103 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2104 ("Not enough free reserved space"));
2105 return GST_FLOW_ERROR;
2109 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2110 ("Failed to serialize mdat"));
2111 g_free (node_header);
2112 return GST_FLOW_ERROR;
2117 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2119 gboolean fragmented = FALSE;
2122 GST_OBJECT_LOCK (qtmux);
2123 timescale = qtmux->timescale;
2124 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2125 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2127 GST_OBJECT_UNLOCK (qtmux);
2129 /* inform lower layers of our property wishes, and determine duration.
2130 * Let moov take care of this using its list of traks;
2131 * so that released pads are also included */
2132 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2134 atom_moov_update_timescale (qtmux->moov, timescale);
2135 atom_moov_set_fragmented (qtmux->moov, fragmented);
2137 atom_moov_update_duration (qtmux->moov);
2140 static GstFlowReturn
2141 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2142 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2144 guint64 offset = 0, size = 0;
2147 GstFlowReturn ret = GST_FLOW_OK;
2149 /* serialize moov */
2152 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2153 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2154 goto serialize_error;
2155 qtmux->last_moov_size = offset;
2157 /* Check we have enough reserved space for this and a Free atom */
2158 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2159 goto too_small_reserved;
2160 buf = _gst_buffer_new_take_data (data, offset);
2161 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2163 /* If at EOS, this is the final moov, put in the streamheader
2164 * (apparently used by a flumotion util) */
2165 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2166 gst_qt_mux_set_header_on_caps (qtmux, buf);
2169 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2170 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2172 /* Write out a free atom if needed */
2173 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2174 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2175 (guint32) (padded_moov_size - offset));
2177 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2184 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2185 ("Not enough free reserved header space"),
2186 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2187 offset, padded_moov_size));
2188 return GST_FLOW_ERROR;
2193 return GST_FLOW_ERROR;
2197 /* either calculates size of extra atoms or pushes them */
2198 static GstFlowReturn
2199 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2203 guint64 loffset = 0, size = 0;
2205 GstFlowReturn ret = GST_FLOW_OK;
2207 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2208 AtomInfo *ainfo = (AtomInfo *) walk->data;
2212 if (!ainfo->copy_data_func (ainfo->atom,
2213 send ? &data : NULL, &size, &loffset))
2214 goto serialize_error;
2219 GST_DEBUG_OBJECT (qtmux,
2220 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2221 GST_FOURCC_ARGS (ainfo->atom->type));
2222 buf = _gst_buffer_new_take_data (data, loffset);
2223 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2224 if (ret != GST_FLOW_OK)
2237 return GST_FLOW_ERROR;
2242 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2244 gboolean seekable = FALSE;
2245 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2247 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2248 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2249 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2251 /* have to assume seeking is not supported if query not handled downstream */
2252 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2255 gst_query_unref (query);
2261 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2264 gboolean fail = FALSE;
2265 AtomFTYP *ftyp = NULL;
2266 GstBuffer *prefix = NULL;
2268 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
2269 qtmux->moov_recov_file_path);
2271 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2272 if (qtmux->moov_recov_file == NULL) {
2273 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2274 qtmux->moov_recov_file_path);
2278 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2280 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2281 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2282 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2286 atom_ftyp_free (ftyp);
2288 gst_buffer_unref (prefix);
2290 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2291 GstCollectData *cdata = (GstCollectData *) walk->data;
2292 GstQTPad *qpad = (GstQTPad *) cdata;
2293 /* write info for each stream */
2294 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2296 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2304 fclose (qtmux->moov_recov_file);
2305 qtmux->moov_recov_file = NULL;
2306 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
2307 "recover file, moov recovery won't work");
2310 static GstFlowReturn
2311 gst_qt_mux_start_file (GstQTMux * qtmux)
2313 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2314 GstFlowReturn ret = GST_FLOW_OK;
2318 GstClockTime reserved_max_duration;
2319 guint reserved_bytes_per_sec_per_trak;
2321 GST_DEBUG_OBJECT (qtmux, "starting file");
2323 GST_OBJECT_LOCK (qtmux);
2324 reserved_max_duration = qtmux->reserved_max_duration;
2325 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2326 GST_OBJECT_UNLOCK (qtmux);
2328 /* stream-start (FIXME: create id based on input ids) */
2329 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2330 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2332 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2333 /* qtmux has structure with and without variant, remove all but the first */
2334 while (gst_caps_get_size (caps) > 1)
2335 gst_caps_remove_structure (caps, 1);
2336 gst_pad_set_caps (qtmux->srcpad, caps);
2337 gst_caps_unref (caps);
2339 /* Default is 'normal' mode */
2340 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2342 /* Require a sensible fragment duration when muxing
2343 * using the ISML muxer */
2344 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2345 qtmux->fragment_duration == 0)
2348 if (qtmux->fragment_duration > 0) {
2349 if (qtmux->streamable)
2350 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2352 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2353 } else if (qtmux->fast_start) {
2354 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2355 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2356 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2359 switch (qtmux->mux_mode) {
2360 case GST_QT_MUX_MODE_MOOV_AT_END:
2361 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2362 /* We have to be able to seek to rewrite the mdat header, or any
2363 * moov atom we write will not be visible in the file, because an
2364 * MDAT with 0 as the size covers the rest of the file. A file
2365 * with no moov is not playable, so error out now. */
2366 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2367 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2368 ("Downstream is not seekable - will not be able to create a playable file"),
2370 return GST_FLOW_ERROR;
2373 case GST_QT_MUX_MODE_FAST_START:
2374 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2375 break; /* Don't need seekability, ignore */
2376 case GST_QT_MUX_MODE_FRAGMENTED:
2377 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2378 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2379 "streamable=false. Will ignore that and create streamable output "
2381 qtmux->streamable = TRUE;
2382 g_object_notify (G_OBJECT (qtmux), "streamable");
2387 /* let downstream know we think in BYTES and expect to do seeking later on */
2388 gst_segment_init (&segment, GST_FORMAT_BYTES);
2389 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2391 /* initialize our moov recovery file */
2392 GST_OBJECT_LOCK (qtmux);
2393 if (qtmux->moov_recov_file_path) {
2394 gst_qt_mux_prepare_moov_recovery (qtmux);
2397 /* Make sure the first time we update the moov, we'll
2398 * include any tagsetter tags */
2399 qtmux->tags_changed = TRUE;
2401 GST_OBJECT_UNLOCK (qtmux);
2404 * send mdat header if already needed, and mark position for later update.
2405 * We don't send ftyp now if we are on fast start mode, because we can
2406 * better fine tune using the information we gather to create the whole moov
2409 switch (qtmux->mux_mode) {
2410 case GST_QT_MUX_MODE_MOOV_AT_END:
2411 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2412 if (ret != GST_FLOW_OK)
2415 /* Store this as the mdat offset for later updating
2416 * when we write the moov */
2417 qtmux->mdat_pos = qtmux->header_size;
2418 /* extended atom in case we go over 4GB while writing and need
2419 * the full 64-bit atom */
2421 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2424 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2426 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2427 if (ret != GST_FLOW_OK)
2430 /* Pad ftyp out to an 8-byte boundary before starting the moov
2431 * ping pong region. It should be well less than 1 disk sector,
2432 * unless there's a bajillion compatible types listed,
2433 * but let's be sure the free atom doesn't cross a sector
2434 * boundary anyway */
2435 if (qtmux->header_size % 8) {
2436 /* Extra 8 bytes for the padding free atom header */
2437 guint padding = (guint) (16 - (qtmux->header_size % 8));
2438 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2440 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2442 if (ret != GST_FLOW_OK)
2446 /* Store this as the moov offset for later updating.
2447 * We record mdat position below */
2448 qtmux->moov_pos = qtmux->header_size;
2450 /* Set up the initial 'ping' state of the ping-pong buffers */
2451 qtmux->reserved_moov_first_active = TRUE;
2453 gst_qt_mux_configure_moov (qtmux);
2454 gst_qt_mux_setup_metadata (qtmux);
2455 /* Empty free atom to begin, starting on an 8-byte boundary */
2456 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2457 if (ret != GST_FLOW_OK)
2459 /* Moov header, not padded yet */
2460 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2461 if (ret != GST_FLOW_OK)
2463 /* The moov we just sent contains the 'base' size of the moov, before
2464 * we put in any time-dependent per-trak data. Use that to make
2465 * a good estimate of how much extra to reserve */
2466 /* Calculate how much space to reserve for our MOOV atom.
2467 * We actually reserve twice that, for ping-pong buffers */
2468 qtmux->base_moov_size = qtmux->last_moov_size;
2469 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2470 qtmux->base_moov_size);
2471 qtmux->reserved_moov_size = qtmux->base_moov_size +
2472 gst_util_uint64_scale (reserved_max_duration,
2473 reserved_bytes_per_sec_per_trak *
2474 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2476 /* Need space for at least 4 atom headers. More really, but
2477 * this as an absolute minimum */
2478 if (qtmux->reserved_moov_size < 4 * 8)
2479 goto reserved_moov_too_small;
2481 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2482 2 * qtmux->reserved_moov_size + 16);
2484 GST_OBJECT_LOCK (qtmux);
2485 qtmux->reserved_duration_remaining =
2486 gst_util_uint64_scale (qtmux->reserved_moov_size -
2487 qtmux->base_moov_size, GST_SECOND,
2488 reserved_bytes_per_sec_per_trak *
2489 atom_moov_get_trak_count (qtmux->moov));
2490 GST_OBJECT_UNLOCK (qtmux);
2492 /* Now that we know how much reserved space is targetted,
2493 * output a free atom to fill the extra reserved */
2494 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2495 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2496 if (ret != GST_FLOW_OK)
2499 /* Then a free atom containing 'pong' buffer, with an
2500 * extra 8 bytes to account for the free atom header itself */
2501 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2502 qtmux->reserved_moov_size + 8, FALSE);
2503 if (ret != GST_FLOW_OK)
2506 /* extra atoms go after the free/moov(s), before the mdat */
2508 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2509 if (ret != GST_FLOW_OK)
2512 qtmux->mdat_pos = qtmux->header_size;
2513 /* extended atom in case we go over 4GB while writing and need
2514 * the full 64-bit atom */
2516 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2519 case GST_QT_MUX_MODE_FAST_START:
2520 GST_OBJECT_LOCK (qtmux);
2521 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2522 if (!qtmux->fast_start_file)
2524 GST_OBJECT_UNLOCK (qtmux);
2525 /* send a dummy buffer for preroll */
2526 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2528 case GST_QT_MUX_MODE_FRAGMENTED:
2529 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2530 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2531 if (ret != GST_FLOW_OK)
2533 /* store the moov pos so we can update the duration later
2534 * in non-streamable mode */
2535 qtmux->moov_pos = qtmux->header_size;
2537 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2538 qtmux->fragment_duration);
2539 /* also used as snapshot marker to indicate fragmented file */
2540 qtmux->fragment_sequence = 1;
2541 /* prepare moov and/or tags */
2542 gst_qt_mux_configure_moov (qtmux);
2543 gst_qt_mux_setup_metadata (qtmux);
2544 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2545 if (ret != GST_FLOW_OK)
2549 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2550 if (ret != GST_FLOW_OK)
2552 /* prepare index if not streamable */
2553 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2554 qtmux->mfra = atom_mfra_new (qtmux->context);
2562 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2563 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2564 return GST_FLOW_ERROR;
2566 reserved_moov_too_small:
2568 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2569 ("Not enough reserved space for creating headers"), (NULL));
2570 return GST_FLOW_ERROR;
2574 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2575 (("Could not open temporary file \"%s\""),
2576 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2577 GST_OBJECT_UNLOCK (qtmux);
2578 return GST_FLOW_ERROR;
2582 static GstFlowReturn
2583 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2585 GstFlowReturn ret = GST_FLOW_OK;
2588 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2589 GstCollectData *cdata = (GstCollectData *) walk->data;
2590 GstQTPad *qtpad = (GstQTPad *) cdata;
2592 /* avoid add_buffer complaining if not negotiated
2593 * in which case no buffers either, so skipping */
2594 if (!qtpad->fourcc) {
2595 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2596 GST_PAD_NAME (qtpad->collect.pad));
2600 /* send last buffer; also flushes possibly queued buffers/ts */
2601 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
2602 GST_PAD_NAME (qtpad->collect.pad));
2603 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
2604 if (ret != GST_FLOW_OK) {
2605 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
2606 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
2607 gst_flow_get_name (ret));
2615 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
2619 /* for setting some subtitles fields */
2620 guint max_width = 0;
2621 guint max_height = 0;
2623 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
2625 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2626 GstCollectData *cdata = (GstCollectData *) walk->data;
2627 GstQTPad *qtpad = (GstQTPad *) cdata;
2629 if (!qtpad->fourcc) {
2630 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2631 GST_PAD_NAME (qtpad->collect.pad));
2635 /* having flushed above, can check for buffers now */
2636 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2637 /* determine max stream duration */
2638 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
2639 || qtpad->last_dts > qtmux->last_dts) {
2640 qtmux->last_dts = qtpad->last_dts;
2642 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
2643 || qtpad->first_ts < qtmux->first_ts) {
2644 qtmux->first_ts = qtpad->first_ts;
2648 /* subtitles need to know the video width/height,
2649 * it is stored shifted 16 bits to the left according to the
2651 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
2652 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
2654 /* update average bitrate of streams if needed */
2656 guint32 avgbitrate = 0;
2657 guint32 maxbitrate = qtpad->max_bitrate;
2659 if (qtpad->avg_bitrate)
2660 avgbitrate = qtpad->avg_bitrate;
2661 else if (qtpad->total_duration > 0)
2662 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
2663 8 * GST_SECOND, qtpad->total_duration);
2665 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
2669 /* need to update values on subtitle traks now that we know the
2670 * max width and height */
2671 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2672 GstCollectData *cdata = (GstCollectData *) walk->data;
2673 GstQTPad *qtpad = (GstQTPad *) cdata;
2675 if (!qtpad->fourcc) {
2676 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2677 GST_PAD_NAME (qtpad->collect.pad));
2681 if (qtpad->fourcc == FOURCC_tx3g) {
2682 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
2687 /* Called after gst_qt_mux_update_global_statistics() updates the
2688 * first_ts tracking, to create/set edit lists for delayed streams */
2690 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
2694 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
2695 GST_TIME_ARGS (qtmux->first_ts));
2696 /* add/update EDTSs for late streams. configure_moov will have
2697 * set the trak durations above by summing the sample tables,
2698 * here we extend that if needing to insert an empty segment */
2699 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2700 GstCollectData *cdata = (GstCollectData *) walk->data;
2701 GstQTPad *qtpad = (GstQTPad *) cdata;
2703 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2704 guint32 lateness = 0;
2705 guint32 duration = qtpad->trak->tkhd.duration;
2709 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
2710 has_shift = (qtpad->dts_adjustment > 0);
2715 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
2716 lateness = gst_util_uint64_scale_round (diff,
2717 qtmux->timescale, GST_SECOND);
2719 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
2720 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (lateness));
2722 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
2723 (guint32) (1 * 65536.0));
2726 if (has_gap || has_shift) {
2728 guint32 media_start;
2730 ctts = qtpad->first_ts - qtpad->first_dts;
2731 media_start = gst_util_uint64_scale_round (ctts,
2732 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
2734 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
2735 (guint32) (1 * 65536.0));
2738 /* need to add the empty time to the trak duration */
2739 duration += lateness;
2741 qtpad->trak->tkhd.duration = duration;
2743 /* And possibly grow the moov duration */
2744 if (duration > qtmux->moov->mvhd.time_info.duration) {
2745 qtmux->moov->mvhd.time_info.duration = duration;
2746 qtmux->moov->mvex.mehd.fragment_duration = duration;
2752 static GstFlowReturn
2753 gst_qt_mux_stop_file (GstQTMux * qtmux)
2755 gboolean ret = GST_FLOW_OK;
2756 guint64 offset = 0, size = 0;
2757 gboolean large_file;
2759 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
2761 /* pushing last buffers for each pad */
2762 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
2765 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2766 /* Streamable mode; no need to write duration or MFRA */
2767 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
2771 gst_qt_mux_update_global_statistics (qtmux);
2773 switch (qtmux->mux_mode) {
2774 case GST_QT_MUX_MODE_FRAGMENTED:{
2776 guint8 *data = NULL;
2780 GST_DEBUG_OBJECT (qtmux, "adding mfra");
2781 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
2782 goto serialize_error;
2783 buf = _gst_buffer_new_take_data (data, offset);
2784 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
2785 if (ret != GST_FLOW_OK)
2788 /* only mvex duration is updated,
2789 * mvhd should be consistent with empty moov
2790 * (but TODO maybe some clients do not handle that well ?) */
2791 qtmux->moov->mvex.mehd.fragment_duration =
2792 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
2793 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
2794 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
2795 /* seek and rewrite the header */
2796 gst_segment_init (&segment, GST_FORMAT_BYTES);
2797 segment.start = qtmux->moov_pos;
2798 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2799 /* no need to seek back */
2800 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2802 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
2803 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
2804 if (G_UNLIKELY (ret != GST_FLOW_OK))
2806 /* Finalise by writing the final size into the mdat. Up until now
2807 * it's been 0, which means 'rest of the file'
2808 * No need to seek back after this, we won't write any more */
2809 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2810 qtmux->mdat_size, NULL, TRUE);
2816 /* Moov-at-end or fast-start mode from here down */
2817 gst_qt_mux_configure_moov (qtmux);
2819 gst_qt_mux_update_edit_lists (qtmux);
2821 /* tags into file metadata */
2822 gst_qt_mux_setup_metadata (qtmux);
2824 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
2826 switch (qtmux->mux_mode) {
2827 case GST_QT_MUX_MODE_FAST_START:{
2828 /* if faststart, update the offset of the atoms in the movie with the offset
2829 * that the movie headers before mdat will cause.
2830 * Also, send the ftyp */
2833 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2834 if (ret != GST_FLOW_OK) {
2837 /* copy into NULL to obtain size */
2838 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
2839 goto serialize_error;
2840 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
2842 offset += qtmux->header_size + (large_file ? 16 : 8);
2844 /* sum up with the extra atoms size */
2845 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
2846 if (ret != GST_FLOW_OK)
2851 offset = qtmux->header_size;
2855 /* Now that we know the size of moov + extra atoms, we can adjust
2856 * the chunk offsets stored into the moov */
2857 atom_moov_chunks_set_offset (qtmux->moov, offset);
2859 /* write out moov and extra atoms */
2860 /* note: as of this point, we no longer care about tracking written data size,
2861 * since there is no more use for it anyway */
2862 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2863 if (ret != GST_FLOW_OK)
2867 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
2868 if (ret != GST_FLOW_OK)
2871 switch (qtmux->mux_mode) {
2872 case GST_QT_MUX_MODE_MOOV_AT_END:
2874 /* mdat needs update iff not using faststart */
2875 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
2876 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2877 qtmux->mdat_size, NULL, FALSE);
2878 /* note; no seeking back to the end of file is done,
2879 * since we no longer write anything anyway */
2882 case GST_QT_MUX_MODE_FAST_START:
2884 /* send mdat atom and move buffered data into it */
2885 /* mdat_size = accumulated (buffered data) */
2886 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
2888 if (ret != GST_FLOW_OK)
2890 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
2891 if (ret != GST_FLOW_OK)
2896 g_assert_not_reached ();
2904 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2905 ("Failed to serialize moov"));
2906 return GST_FLOW_ERROR;
2910 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
2911 return GST_FLOW_ERROR;
2915 static GstFlowReturn
2916 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2917 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2918 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2920 GstFlowReturn ret = GST_FLOW_OK;
2922 /* setup if needed */
2923 if (G_UNLIKELY (!pad->traf || force))
2927 /* flush pad fragment if threshold reached,
2928 * or at new keyframe if we should be minding those in the first place */
2929 if (G_UNLIKELY (force || (sync && pad->sync) ||
2930 pad->fragment_duration < (gint64) delta)) {
2932 guint64 size = 0, offset = 0;
2933 guint8 *data = NULL;
2935 guint i, total_size;
2937 /* now we know where moof ends up, update offset in tfra */
2939 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2941 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2942 /* takes ownership */
2943 atom_moof_add_traf (moof, pad->traf);
2945 atom_moof_copy_data (moof, &data, &size, &offset);
2946 buffer = _gst_buffer_new_take_data (data, offset);
2947 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2948 gst_buffer_get_size (buffer));
2949 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2951 /* and actual data */
2953 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2955 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2958 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2959 atom_array_get_len (&pad->fragment_buffers), total_size);
2960 if (ret == GST_FLOW_OK)
2961 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2963 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2964 if (G_LIKELY (ret == GST_FLOW_OK))
2965 ret = gst_qt_mux_send_buffer (qtmux,
2966 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2969 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2972 atom_array_clear (&pad->fragment_buffers);
2973 atom_moof_free (moof);
2974 qtmux->fragment_sequence++;
2979 if (G_UNLIKELY (!pad->traf)) {
2980 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2981 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2982 atom_array_init (&pad->fragment_buffers, 512);
2983 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2984 atom_trak_get_timescale (pad->trak), 1000);
2986 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2987 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2988 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2992 /* add buffer and metadata */
2993 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2995 atom_array_append (&pad->fragment_buffers, buf, 256);
2996 pad->fragment_duration -= delta;
2999 guint32 sn = atom_traf_get_sample_num (pad->traf);
3001 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3002 atom_tfra_add_entry (pad->tfra, dts, sn);
3005 if (G_UNLIKELY (force))
3011 /* Here's the clever bit of robust recording: Updating the moov
3012 * header is done using a ping-pong scheme inside 2 blocks of size
3013 * 'reserved_moov_size' at the start of the file, in such a way that the
3014 * file on-disk is always valid if interrupted.
3015 * Inside the reserved space, we have 2 pairs of free + moov atoms
3016 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3017 * at offset "reserved_moov_size".
3019 * 1. Free-A has 0 size payload, moov-A immediately after is
3020 * active/current, and is padded with an internal Free atom to
3021 * end at reserved_space/2. Free-B is at reserved_space/2, sized
3022 * to cover the remaining free space (including moov-B).
3023 * 2. We write moov-B (which is invisible inside free-B), and pad it to
3024 * end at the end of free space. Then, we update free-A to size
3025 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
3026 * free-B header, and makes moov-B active.
3027 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
3028 * Change the size of free-A to make moov-A active again.
3029 * 4. Rinse and repeat.
3032 static GstFlowReturn
3033 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
3037 guint64 freeA_offset;
3038 guint32 new_freeA_size;
3039 guint64 new_moov_offset;
3041 /* Update moov info, then seek and rewrite the MOOV atom */
3042 gst_qt_mux_update_global_statistics (qtmux);
3043 gst_qt_mux_configure_moov (qtmux);
3045 gst_qt_mux_update_edit_lists (qtmux);
3047 /* tags into file metadata */
3048 gst_qt_mux_setup_metadata (qtmux);
3050 /* chunks position is set relative to the first byte of the
3051 * MDAT atom payload. Set the overall offset into the file */
3052 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3054 /* Calculate which moov to rewrite. qtmux->moov_pos points to
3055 * the start of the free-A header */
3056 freeA_offset = qtmux->moov_pos;
3057 if (qtmux->reserved_moov_first_active) {
3058 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
3059 /* After this, freeA will include itself, moovA, plus the freeB
3061 new_freeA_size = qtmux->reserved_moov_size + 16;
3063 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
3066 /* the moov we update is after free-A, calculate its offset */
3067 new_moov_offset = freeA_offset + new_freeA_size;
3069 /* Swap ping-pong cadence marker */
3070 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
3072 /* seek and rewrite the MOOV atom */
3073 gst_segment_init (&segment, GST_FORMAT_BYTES);
3074 segment.start = new_moov_offset;
3075 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3078 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3080 if (ret != GST_FLOW_OK)
3083 /* Update the estimated recording space remaining, based on amount used so
3084 * far and duration muxed so far */
3085 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
3086 GstClockTime remain;
3087 GstClockTime time_muxed = qtmux->last_dts;
3090 gst_util_uint64_scale (qtmux->reserved_moov_size -
3091 qtmux->last_moov_size, time_muxed,
3092 qtmux->last_moov_size - qtmux->base_moov_size);
3093 /* Always under-estimate slightly, so users
3094 * have time to stop muxing before we run out */
3095 if (remain < GST_SECOND / 2)
3098 remain -= GST_SECOND / 2;
3100 GST_INFO_OBJECT (qtmux,
3101 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
3102 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
3103 qtmux->reserved_moov_size, qtmux->last_moov_size,
3104 GST_TIME_ARGS (qtmux->last_dts),
3105 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
3107 GST_OBJECT_LOCK (qtmux);
3108 qtmux->reserved_duration_remaining = remain;
3109 qtmux->muxed_since_last_update = 0;
3110 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
3111 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
3112 GST_OBJECT_UNLOCK (qtmux);
3116 /* Now update the moov-A size. Don't pass offset, since we don't need
3117 * send_free_atom() to seek for us - all our callers seek back to
3118 * where they need after this, or they don't need it */
3119 gst_segment_init (&segment, GST_FORMAT_BYTES);
3120 segment.start = freeA_offset;
3121 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3123 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3128 static GstFlowReturn
3129 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3132 GstFlowReturn flow_ret;
3134 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3136 GST_OBJECT_LOCK (qtmux);
3137 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3138 GST_OBJECT_UNLOCK (qtmux);
3142 /* Update if position is > the threshold or there's been no update yet */
3143 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3144 (position <= qtmux->last_moov_update ||
3145 (position - qtmux->last_moov_update) <
3146 qtmux->reserved_moov_update_period)) {
3147 /* Update the offset of how much we've muxed, so the
3148 * report of remaining space keeps counting down */
3149 if (position > qtmux->last_moov_update &&
3150 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3151 GST_LOG_OBJECT (qtmux,
3152 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3153 qtmux->muxed_since_last_update);
3154 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3156 GST_OBJECT_UNLOCK (qtmux);
3157 return GST_FLOW_OK; /* No update needed yet */
3160 qtmux->last_moov_update = position;
3161 GST_OBJECT_UNLOCK (qtmux);
3163 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3164 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3165 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3167 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3168 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3171 /* Seek back to previous position */
3172 gst_segment_init (&segment, GST_FORMAT_BYTES);
3173 segment.start = mdat_offset;
3174 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3179 static GstFlowReturn
3180 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3181 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3182 gint64 last_dts, gint64 scaled_duration, guint sample_size,
3183 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3185 GstFlowReturn ret = GST_FLOW_OK;
3187 /* note that a new chunk is started each time (not fancy but works) */
3188 if (qtmux->moov_recov_file) {
3189 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3190 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3191 do_pts, pts_offset)) {
3192 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3193 "recovery file, disabling recovery");
3194 fclose (qtmux->moov_recov_file);
3195 qtmux->moov_recov_file = NULL;
3199 switch (qtmux->mux_mode) {
3200 case GST_QT_MUX_MODE_MOOV_AT_END:
3201 case GST_QT_MUX_MODE_FAST_START:
3202 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3203 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3204 sample_size, chunk_offset, sync, pts_offset);
3205 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3206 /* Check if it's time to re-write the headers in robust-recording mode */
3207 if (ret == GST_FLOW_OK
3208 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3209 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3211 case GST_QT_MUX_MODE_FRAGMENTED:
3212 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3213 /* ensure that always sync samples are marked as such */
3214 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3215 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3216 sample_size, !pad->sync || sync, pts_offset);
3224 * Here we push the buffer and update the tables in the track atoms
3226 static GstFlowReturn
3227 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
3229 GstBuffer *last_buf = NULL;
3230 GstClockTime duration;
3231 guint nsamples, sample_size;
3232 guint64 chunk_offset;
3233 gint64 last_dts, scaled_duration;
3234 gint64 pts_offset = 0;
3235 gboolean sync = FALSE;
3236 GstFlowReturn ret = GST_FLOW_OK;
3239 goto not_negotiated;
3241 /* if this pad has a prepare function, call it */
3242 if (pad->prepare_buf_func != NULL) {
3243 buf = pad->prepare_buf_func (pad, buf, qtmux);
3246 last_buf = pad->last_buf;
3248 /* DTS delta is used to calculate sample duration.
3249 * If buffer has missing DTS, we take either segment start or
3250 * previous buffer end time, whichever is later.
3251 * This must only be done for non sparse streams, sparse streams
3252 * can have gaps between buffers (which is handled later by adding
3253 * extra empty buffer with duration that fills the gap). */
3254 if (!pad->sparse && buf && !GST_BUFFER_DTS_IS_VALID (buf)) {
3255 GstClockTime last_buf_duration = last_buf
3256 && GST_BUFFER_DURATION_IS_VALID (last_buf) ?
3257 GST_BUFFER_DURATION (last_buf) : 0;
3259 buf = gst_buffer_make_writable (buf);
3260 GST_BUFFER_DTS (buf) = 0; /* running-time 0 */
3263 && (GST_BUFFER_DTS (last_buf) + last_buf_duration) >
3264 GST_BUFFER_DTS (buf)) {
3265 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf) + last_buf_duration;
3269 if (last_buf && !buf && !GST_BUFFER_DURATION_IS_VALID (last_buf)) {
3270 /* this is last buffer; there is no next buffer so we need valid number as duration */
3271 last_buf = gst_buffer_make_writable (last_buf);
3272 GST_BUFFER_DURATION (last_buf) = 0;
3275 if (last_buf == NULL) {
3276 #ifndef GST_DISABLE_GST_DEBUG
3278 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
3279 "received NULL buffer, doing nothing",
3280 GST_PAD_NAME (pad->collect.pad));
3282 GST_LOG_OBJECT (qtmux,
3283 "Pad %s has no previous buffer stored, storing now",
3284 GST_PAD_NAME (pad->collect.pad));
3287 pad->last_buf = buf;
3290 gst_buffer_ref (last_buf);
3292 /* if this is the first buffer, store the timestamp */
3293 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
3294 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3295 pad->first_ts = GST_BUFFER_PTS (last_buf);
3296 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3297 pad->first_ts = GST_BUFFER_DTS (last_buf);
3300 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3301 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
3302 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3303 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
3306 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
3307 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
3309 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
3310 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
3311 pad->first_ts = pad->first_dts = 0;
3313 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
3314 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
3315 GST_TIME_ARGS (pad->first_ts));
3318 if (last_buf && buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
3319 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
3320 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
3321 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
3322 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
3323 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
3324 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
3327 /* duration actually means time delta between samples, so we calculate
3328 * the duration based on the difference in DTS or PTS, falling back
3329 * to DURATION if the other two don't exist, such as with the last
3330 * sample before EOS. */
3331 duration = GST_BUFFER_DURATION (last_buf);
3333 if (last_buf && buf && GST_BUFFER_DTS_IS_VALID (buf)
3334 && GST_BUFFER_DTS_IS_VALID (last_buf))
3335 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
3336 else if (last_buf && buf && GST_BUFFER_PTS_IS_VALID (buf)
3337 && GST_BUFFER_PTS_IS_VALID (last_buf))
3338 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
3341 gst_buffer_replace (&pad->last_buf, buf);
3343 /* for computing the avg bitrate */
3344 if (G_LIKELY (last_buf)) {
3345 pad->total_bytes += gst_buffer_get_size (last_buf);
3346 pad->total_duration += duration;
3349 last_dts = gst_util_uint64_scale_round (pad->last_dts,
3350 atom_trak_get_timescale (pad->trak), GST_SECOND);
3352 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
3353 if (pad->sample_size && !qtmux->fragment_sequence) {
3354 /* Constant size packets: usually raw audio (with many samples per
3355 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
3357 sample_size = pad->sample_size;
3358 if (gst_buffer_get_size (last_buf) % sample_size != 0)
3359 goto fragmented_sample;
3360 /* note: qt raw audio storage warps it implicitly into a timewise
3361 * perfect stream, discarding buffer times */
3362 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
3363 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
3364 atom_trak_get_timescale (pad->trak), GST_SECOND);
3366 nsamples = gst_buffer_get_size (last_buf) / sample_size;
3369 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
3373 /* timescale = samplerate */
3374 scaled_duration = 1;
3375 pad->last_dts += duration * nsamples;
3378 sample_size = gst_buffer_get_size (last_buf);
3379 if ((pad->last_buf && GST_BUFFER_DTS_IS_VALID (pad->last_buf))
3380 || GST_BUFFER_DTS_IS_VALID (last_buf)) {
3382 if (pad->last_buf && GST_BUFFER_DTS_IS_VALID (pad->last_buf)) {
3383 pad->last_dts = GST_BUFFER_DTS (pad->last_buf);
3385 pad->last_dts = GST_BUFFER_DTS (last_buf) +
3386 GST_BUFFER_DURATION (last_buf);
3388 if ((gint64) (pad->last_dts) < 0) {
3389 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
3390 atom_trak_get_timescale (pad->trak), GST_SECOND);
3392 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
3393 atom_trak_get_timescale (pad->trak), GST_SECOND);
3395 scaled_duration = scaled_dts - last_dts;
3396 last_dts = scaled_dts;
3398 /* first convert intended timestamp (in GstClockTime resolution) to
3399 * trak timescale, then derive delta;
3400 * this ensures sums of (scale)delta add up to converted timestamp,
3401 * which only deviates at most 1/scale from timestamp itself */
3402 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
3403 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
3404 pad->last_dts += duration;
3407 chunk_offset = qtmux->mdat_size;
3409 GST_LOG_OBJECT (qtmux,
3410 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
3411 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
3412 GST_LOG_OBJECT (qtmux,
3413 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
3414 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
3415 nsamples, scaled_duration, sample_size, chunk_offset);
3417 /* might be a sync sample */
3419 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
3420 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
3421 GST_PAD_NAME (pad->collect.pad));
3425 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf))) {
3426 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
3427 atom_trak_get_timescale (pad->trak), GST_SECOND);
3429 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3430 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
3434 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3435 atom_trak_get_timescale (pad->trak), GST_SECOND);
3437 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
3438 " timebase_dts: %d pts_offset: %d",
3439 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
3440 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
3441 (int) (last_dts), (int) (pts_offset));
3444 * Each buffer starts a new chunk, so we can assume the buffer
3445 * duration is the chunk duration
3447 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
3448 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
3449 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
3450 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
3451 qtmux->longest_chunk = duration;
3454 /* now we go and register this buffer/sample all over */
3455 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
3456 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
3457 chunk_offset, sync, TRUE, pts_offset);
3459 /* if this is sparse and we have a next buffer, check if there is any gap
3460 * between them to insert an empty sample */
3461 if (pad->sparse && buf) {
3462 if (pad->create_empty_buffer) {
3463 GstBuffer *empty_buf;
3464 gint64 empty_duration =
3465 GST_BUFFER_TIMESTAMP (buf) - (GST_BUFFER_TIMESTAMP (last_buf) +
3467 gint64 empty_duration_scaled;
3469 empty_buf = pad->create_empty_buffer (pad, empty_duration);
3471 empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
3472 atom_trak_get_timescale (pad->trak), GST_SECOND);
3474 pad->total_bytes += gst_buffer_get_size (empty_buf);
3475 pad->total_duration += duration;
3478 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
3479 last_dts + scaled_duration, empty_duration_scaled,
3480 gst_buffer_get_size (empty_buf), qtmux->mdat_size, sync, TRUE, 0);
3482 /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
3483 g_assert_not_reached ();
3484 GST_WARNING_OBJECT (qtmux,
3485 "no empty buffer creation function found for pad %s",
3486 GST_PAD_NAME (pad->collect.pad));
3490 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
3491 gst_qt_mux_update_expected_trailer_size(qtmux, pad);
3492 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
3495 gst_buffer_unref (buf);
3505 gst_buffer_unref (buf);
3506 gst_buffer_unref (last_buf);
3507 return GST_FLOW_ERROR;
3511 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3512 ("Audio buffer contains fragmented sample."));
3517 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
3518 ("format wasn't negotiated before buffer flow on pad %s",
3519 GST_PAD_NAME (pad->collect.pad)));
3521 gst_buffer_unref (buf);
3522 return GST_FLOW_NOT_NEGOTIATED;
3527 * DTS running time can be negative. There is no way to represent that in
3528 * MP4 however, thus we need to offset DTS so that it starts from 0.
3531 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
3532 GstCollectData * cdata, GstBuffer ** buf)
3537 pts = GST_BUFFER_PTS (*buf);
3538 dts = GST_COLLECT_PADS_DTS (cdata);
3540 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
3541 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
3542 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
3544 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
3545 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
3546 pad->dts_adjustment = -dts;
3548 pad->dts_adjustment = 0;
3551 if (pad->dts_adjustment > 0) {
3552 *buf = gst_buffer_make_writable (*buf);
3554 dts += pad->dts_adjustment;
3556 if (GST_CLOCK_TIME_IS_VALID (pts))
3557 pts += pad->dts_adjustment;
3559 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
3560 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
3565 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
3569 GST_BUFFER_PTS (*buf) = pts;
3570 GST_BUFFER_DTS (*buf) = dts;
3572 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
3573 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
3577 static GstFlowReturn
3578 gst_qt_mux_handle_buffer (GstCollectPads * pads, GstCollectData * cdata,
3579 GstBuffer * buf, gpointer user_data)
3581 GstFlowReturn ret = GST_FLOW_OK;
3582 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
3583 GstQTPad *best_pad = NULL;
3585 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
3586 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
3589 qtmux->state = GST_QT_MUX_STATE_DATA;
3592 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
3593 return GST_FLOW_EOS;
3595 best_pad = (GstQTPad *) cdata;
3597 /* clipping already converted to running time */
3598 if (best_pad != NULL) {
3600 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad, cdata, &buf);
3601 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
3603 qtmux->state = GST_QT_MUX_STATE_EOS;
3604 ret = gst_qt_mux_stop_file (qtmux);
3605 if (ret == GST_FLOW_OK) {
3606 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
3607 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
3610 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
3611 gst_flow_get_name (ret));
3619 check_field (GQuark field_id, const GValue * value, gpointer user_data)
3621 GstStructure *structure = (GstStructure *) user_data;
3622 const GValue *other = gst_structure_id_get_value (structure, field_id);
3625 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
3629 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
3632 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
3633 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
3635 return gst_structure_foreach (sub_s, check_field, sup_s);
3639 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3641 GstPad *pad = qtpad->collect.pad;
3642 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3643 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3644 GstStructure *structure;
3645 const gchar *mimetype;
3646 gint rate, channels;
3647 const GValue *value = NULL;
3648 const GstBuffer *codec_data = NULL;
3649 GstQTMuxFormat format;
3650 AudioSampleEntry entry = { 0, };
3651 AtomInfo *ext_atom = NULL;
3652 gint constant_size = 0;
3653 const gchar *stream_format;
3655 qtpad->prepare_buf_func = NULL;
3657 /* does not go well to renegotiate stream mid-way, unless
3658 * the old caps are a subset of the new one (this means upstream
3659 * added more info to the caps, as both should be 'fixed' caps) */
3660 if (qtpad->fourcc) {
3661 GstCaps *current_caps;
3663 current_caps = gst_pad_get_current_caps (pad);
3664 g_assert (caps != NULL);
3666 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3667 gst_caps_unref (current_caps);
3668 goto refuse_renegotiation;
3670 GST_DEBUG_OBJECT (qtmux,
3671 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
3672 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
3673 gst_caps_unref (current_caps);
3676 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
3677 GST_DEBUG_PAD_NAME (pad), caps);
3679 format = qtmux_klass->format;
3680 structure = gst_caps_get_structure (caps, 0);
3681 mimetype = gst_structure_get_name (structure);
3684 if (!gst_structure_get_int (structure, "channels", &channels) ||
3685 !gst_structure_get_int (structure, "rate", &rate)) {
3690 value = gst_structure_get_value (structure, "codec_data");
3692 codec_data = gst_value_get_buffer (value);
3694 qtpad->is_out_of_order = FALSE;
3696 /* set common properties */
3697 entry.sample_rate = rate;
3698 entry.channels = channels;
3700 entry.sample_size = 16;
3701 /* this is the typical compressed case */
3702 if (format == GST_QT_MUX_FORMAT_QT) {
3704 entry.compression_id = -2;
3707 /* now map onto a fourcc, and some extra properties */
3708 if (strcmp (mimetype, "audio/mpeg") == 0) {
3709 gint mpegversion = 0;
3712 gst_structure_get_int (structure, "mpegversion", &mpegversion);
3713 switch (mpegversion) {
3715 gst_structure_get_int (structure, "layer", &layer);
3719 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
3720 if (format == GST_QT_MUX_FORMAT_QT)
3721 entry.fourcc = FOURCC__mp3;
3723 entry.fourcc = FOURCC_mp4a;
3725 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
3726 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3727 qtpad->max_bitrate);
3729 entry.samples_per_packet = 1152;
3730 entry.bytes_per_sample = 2;
3736 /* check stream-format */
3737 stream_format = gst_structure_get_string (structure, "stream-format");
3738 if (stream_format) {
3739 if (strcmp (stream_format, "raw") != 0) {
3740 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
3741 "please use 'raw'", stream_format);
3745 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
3749 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2)
3750 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
3754 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
3755 /* warn if not Low Complexity profile */
3758 GST_WARNING_OBJECT (qtmux,
3759 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
3763 entry.fourcc = FOURCC_mp4a;
3765 if (format == GST_QT_MUX_FORMAT_QT)
3766 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
3767 qtpad->avg_bitrate, qtpad->max_bitrate);
3770 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
3771 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3772 qtpad->max_bitrate);
3777 } else if (strcmp (mimetype, "audio/AMR") == 0) {
3778 entry.fourcc = FOURCC_samr;
3779 entry.sample_size = 16;
3780 entry.samples_per_packet = 160;
3781 entry.bytes_per_sample = 2;
3782 ext_atom = build_amr_extension ();
3783 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
3784 entry.fourcc = FOURCC_sawb;
3785 entry.sample_size = 16;
3786 entry.samples_per_packet = 320;
3787 entry.bytes_per_sample = 2;
3788 ext_atom = build_amr_extension ();
3789 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
3792 gst_audio_info_init (&info);
3793 if (!gst_audio_info_from_caps (&info, caps))
3796 /* spec has no place for a distinction in these */
3797 if (info.finfo->width != info.finfo->depth) {
3798 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
3802 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
3803 if (info.finfo->endianness == G_LITTLE_ENDIAN)
3804 entry.fourcc = FOURCC_sowt;
3805 else if (info.finfo->endianness == G_BIG_ENDIAN)
3806 entry.fourcc = FOURCC_twos;
3808 entry.fourcc = FOURCC_sowt;
3809 /* maximum backward compatibility; only new version for > 16 bit */
3810 if (info.finfo->depth <= 16)
3812 /* not compressed in any case */
3813 entry.compression_id = 0;
3814 /* QT spec says: max at 16 bit even if sample size were actually larger,
3815 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
3816 entry.sample_size = info.finfo->depth;
3817 entry.bytes_per_sample = info.finfo->depth / 8;
3818 entry.samples_per_packet = 1;
3819 entry.bytes_per_packet = info.finfo->depth / 8;
3820 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
3822 if (info.finfo->width == 8 && info.finfo->depth == 8) {
3823 /* fall back to old 8-bit version */
3824 entry.fourcc = FOURCC_raw_;
3826 entry.compression_id = 0;
3827 entry.sample_size = 8;
3829 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
3833 constant_size = (info.finfo->depth / 8) * info.channels;
3834 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
3835 entry.fourcc = FOURCC_alaw;
3836 entry.samples_per_packet = 1023;
3837 entry.bytes_per_sample = 2;
3838 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
3839 entry.fourcc = FOURCC_ulaw;
3840 entry.samples_per_packet = 1023;
3841 entry.bytes_per_sample = 2;
3842 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
3844 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
3845 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
3848 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
3850 entry.fourcc = MS_WAVE_FOURCC (0x11);
3851 /* 4 byte header per channel (including one sample). 2 samples per byte
3852 remaining. Simplifying gives the following (samples per block per
3854 entry.samples_per_packet = 2 * blocksize / channels - 7;
3855 entry.bytes_per_sample = 2;
3857 entry.bytes_per_frame = blocksize;
3858 entry.bytes_per_packet = blocksize / channels;
3859 /* ADPCM has constant size packets */
3861 /* TODO: I don't really understand why this helps, but it does! Constant
3862 * size and compression_id of -2 seem to be incompatible, and other files
3863 * in the wild use this too. */
3864 entry.compression_id = -1;
3866 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
3867 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
3868 GstBuffer *codec_config;
3872 entry.fourcc = FOURCC_alac;
3873 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
3874 /* let's check if codec data already comes with 'alac' atom prefix */
3875 if (!codec_data || (len = map.size) < 28) {
3876 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
3877 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3880 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
3883 gst_buffer_copy_region ((GstBuffer *) codec_data,
3884 GST_BUFFER_COPY_MEMORY, 8, len);
3886 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
3888 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3890 /* does not look good, but perhaps some trailing unneeded stuff */
3891 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
3893 if (format == GST_QT_MUX_FORMAT_QT)
3894 ext_atom = build_mov_alac_extension (qtpad->trak, codec_config);
3896 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
3897 /* set some more info */
3898 gst_buffer_map (codec_config, &map, GST_MAP_READ);
3899 entry.bytes_per_sample = 2;
3900 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
3901 gst_buffer_unmap (codec_config, &map);
3902 gst_buffer_unref (codec_config);
3903 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
3904 entry.fourcc = FOURCC_ac_3;
3906 /* Fixed values according to TS 102 366 but it also mentions that
3907 * they should be ignored */
3909 entry.sample_size = 16;
3911 /* AC-3 needs an extension atom but its data can only be obtained from
3912 * the stream itself. Abuse the prepare_buf_func so we parse a frame
3913 * and get the needed data */
3914 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
3920 /* ok, set the pad info accordingly */
3921 qtpad->fourcc = entry.fourcc;
3922 qtpad->sample_size = constant_size;
3924 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
3925 qtmux->context, &entry,
3926 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
3927 ext_atom, constant_size);
3929 gst_object_unref (qtmux);
3935 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3936 GST_PAD_NAME (pad), caps);
3937 gst_object_unref (qtmux);
3940 refuse_renegotiation:
3942 GST_WARNING_OBJECT (qtmux,
3943 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
3944 GST_PAD_NAME (pad), caps);
3945 gst_object_unref (qtmux);
3950 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
3952 adjust_rate (guint64 rate)
3957 while (rate >= 10000)
3963 return (guint32) rate;
3967 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3969 GstPad *pad = qtpad->collect.pad;
3970 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3971 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3972 GstStructure *structure;
3973 const gchar *mimetype;
3974 gint width, height, depth = -1;
3975 gint framerate_num, framerate_den;
3977 const GValue *value = NULL;
3978 const GstBuffer *codec_data = NULL;
3979 VisualSampleEntry entry = { 0, };
3980 GstQTMuxFormat format;
3981 AtomInfo *ext_atom = NULL;
3982 GList *ext_atom_list = NULL;
3983 gboolean sync = FALSE;
3984 int par_num, par_den;
3986 qtpad->prepare_buf_func = NULL;
3988 /* does not go well to renegotiate stream mid-way, unless
3989 * the old caps are a subset of the new one (this means upstream
3990 * added more info to the caps, as both should be 'fixed' caps) */
3991 if (qtpad->fourcc) {
3992 GstCaps *current_caps;
3994 current_caps = gst_pad_get_current_caps (pad);
3995 g_assert (caps != NULL);
3997 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3998 gst_caps_unref (current_caps);
3999 goto refuse_renegotiation;
4001 GST_DEBUG_OBJECT (qtmux,
4002 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4003 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4004 gst_caps_unref (current_caps);
4007 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4008 GST_DEBUG_PAD_NAME (pad), caps);
4010 format = qtmux_klass->format;
4011 structure = gst_caps_get_structure (caps, 0);
4012 mimetype = gst_structure_get_name (structure);
4014 /* required parts */
4015 if (!gst_structure_get_int (structure, "width", &width) ||
4016 !gst_structure_get_int (structure, "height", &height))
4021 /* works as a default timebase */
4022 framerate_num = 10000;
4024 gst_structure_get_fraction (structure, "framerate", &framerate_num,
4026 gst_structure_get_int (structure, "depth", &depth);
4027 value = gst_structure_get_value (structure, "codec_data");
4029 codec_data = gst_value_get_buffer (value);
4033 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
4036 qtpad->is_out_of_order = FALSE;
4038 /* bring frame numerator into a range that ensures both reasonable resolution
4039 * as well as a fair duration */
4040 rate = qtmux->trak_timescale ?
4041 qtmux->trak_timescale : adjust_rate (framerate_num);
4042 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
4045 /* set common properties */
4046 entry.width = width;
4047 entry.height = height;
4048 entry.par_n = par_num;
4049 entry.par_d = par_den;
4050 /* should be OK according to qt and iso spec, override if really needed */
4051 entry.color_table_id = -1;
4052 entry.frame_count = 1;
4055 /* sync entries by default */
4058 /* now map onto a fourcc, and some extra properties */
4059 if (strcmp (mimetype, "video/x-raw") == 0) {
4060 const gchar *format;
4062 const GstVideoFormatInfo *vinfo;
4064 format = gst_structure_get_string (structure, "format");
4065 fmt = gst_video_format_from_string (format);
4066 vinfo = gst_video_format_get_info (fmt);
4069 case GST_VIDEO_FORMAT_UYVY:
4072 entry.fourcc = FOURCC_2vuy;
4073 entry.depth = depth;
4076 case GST_VIDEO_FORMAT_v210:
4079 entry.fourcc = FOURCC_v210;
4080 entry.depth = depth;
4084 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
4085 entry.fourcc = FOURCC_raw_;
4086 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
4091 } else if (strcmp (mimetype, "video/x-h263") == 0) {
4093 if (format == GST_QT_MUX_FORMAT_QT)
4094 entry.fourcc = FOURCC_h263;
4096 entry.fourcc = FOURCC_s263;
4097 ext_atom = build_h263_extension ();
4098 if (ext_atom != NULL)
4099 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4100 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
4101 strcmp (mimetype, "video/mpeg") == 0) {
4104 if (strcmp (mimetype, "video/x-divx") == 0) {
4105 gst_structure_get_int (structure, "divxversion", &version);
4106 version = version == 5 ? 1 : 0;
4108 gst_structure_get_int (structure, "mpegversion", &version);
4109 version = version == 4 ? 1 : 0;
4112 entry.fourcc = FOURCC_mp4v;
4114 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
4115 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
4116 qtpad->max_bitrate);
4117 if (ext_atom != NULL)
4118 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4120 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
4121 "output might not play in Apple QuickTime (try global-headers?)");
4123 } else if (strcmp (mimetype, "video/x-h264") == 0) {
4124 /* check if we accept these caps */
4125 if (gst_structure_has_field (structure, "stream-format")) {
4126 const gchar *format;
4127 const gchar *alignment;
4129 format = gst_structure_get_string (structure, "stream-format");
4130 alignment = gst_structure_get_string (structure, "alignment");
4132 if (strcmp (format, "avc") != 0 || alignment == NULL ||
4133 strcmp (alignment, "au") != 0) {
4134 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
4135 "avc format with AU aligned samples");
4139 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
4144 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
4148 entry.fourcc = FOURCC_avc1;
4149 if (qtpad->avg_bitrate == 0) {
4150 gint avg_bitrate = 0;
4151 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
4152 qtpad->avg_bitrate = avg_bitrate;
4154 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4155 if (ext_atom != NULL)
4156 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4157 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
4158 if (ext_atom != NULL)
4159 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4160 } else if (strcmp (mimetype, "video/x-svq") == 0) {
4162 const GstBuffer *seqh = NULL;
4163 const GValue *seqh_value;
4166 gst_structure_get_int (structure, "svqversion", &version);
4168 entry.fourcc = FOURCC_SVQ3;
4172 seqh_value = gst_structure_get_value (structure, "seqh");
4174 seqh = gst_value_get_buffer (seqh_value);
4175 ext_atom = build_SMI_atom (seqh);
4177 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4180 /* we need to add the gamma anyway because quicktime might crash
4181 * when it doesn't find it */
4182 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
4183 /* it seems that using 0 here makes it ignored */
4186 ext_atom = build_gama_atom (gamma);
4188 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4190 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
4191 "a bug at http://bugzilla.gnome.org", version);
4193 } else if (strcmp (mimetype, "video/x-dv") == 0) {
4195 gboolean pal = TRUE;
4198 if (framerate_num != 25 || framerate_den != 1)
4200 gst_structure_get_int (structure, "dvversion", &version);
4201 /* fall back to typical one */
4207 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', 'p');
4209 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', 'c', ' ');
4213 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'p');
4215 entry.fourcc = GST_MAKE_FOURCC ('d', 'v', '5', 'n');
4218 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
4221 } else if (strcmp (mimetype, "image/jpeg") == 0) {
4222 entry.fourcc = FOURCC_jpeg;
4224 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
4225 strcmp (mimetype, "image/x-jpc") == 0) {
4226 const gchar *colorspace;
4227 const GValue *cmap_array;
4228 const GValue *cdef_array;
4232 if (strcmp (mimetype, "image/x-jpc") == 0) {
4233 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
4236 gst_structure_get_int (structure, "num-components", &ncomp);
4237 gst_structure_get_int (structure, "fields", &fields);
4238 cmap_array = gst_structure_get_value (structure, "component-map");
4239 cdef_array = gst_structure_get_value (structure, "channel-definitions");
4242 entry.fourcc = FOURCC_mjp2;
4245 colorspace = gst_structure_get_string (structure, "colorspace");
4248 build_jp2h_extension (qtpad->trak, width, height, colorspace, ncomp,
4249 cmap_array, cdef_array)) != NULL) {
4250 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4252 ext_atom = build_fiel_extension (fields);
4254 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4256 ext_atom = build_jp2x_extension (codec_data);
4258 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4260 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
4263 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
4264 entry.fourcc = FOURCC_VP80;
4266 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
4267 entry.fourcc = FOURCC_drac;
4268 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
4271 gst_structure_get_uint (structure, "format", &fourcc);
4272 entry.fourcc = fourcc;
4273 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
4276 gst_structure_get_uint (structure, "format", &fourcc);
4277 entry.fourcc = fourcc;
4278 } else if (strcmp (mimetype, "video/x-prores") == 0) {
4279 const gchar *variant;
4281 variant = gst_structure_get_string (structure, "format");
4282 if (!variant || !g_strcmp0 (variant, "standard"))
4283 entry.fourcc = GST_MAKE_FOURCC ('a', 'p', 'c', 'n');
4284 else if (!g_strcmp0 (variant, "lt"))
4285 entry.fourcc = GST_MAKE_FOURCC ('a', 'p', 'c', 's');
4286 else if (!g_strcmp0 (variant, "hq"))
4287 entry.fourcc = GST_MAKE_FOURCC ('a', 'p', 'c', 'h');
4288 else if (!g_strcmp0 (variant, "proxy"))
4289 entry.fourcc = GST_MAKE_FOURCC ('a', 'p', '4', 'h');
4295 /* ok, set the pad info accordingly */
4296 qtpad->fourcc = entry.fourcc;
4299 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
4300 qtmux->context, &entry, rate, ext_atom_list);
4302 gst_object_unref (qtmux);
4308 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4309 GST_PAD_NAME (pad), caps);
4310 gst_object_unref (qtmux);
4313 refuse_renegotiation:
4315 GST_WARNING_OBJECT (qtmux,
4316 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4318 gst_object_unref (qtmux);
4324 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4326 GstPad *pad = qtpad->collect.pad;
4327 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4328 GstStructure *structure;
4329 SubtitleSampleEntry entry = { 0, };
4331 /* does not go well to renegotiate stream mid-way, unless
4332 * the old caps are a subset of the new one (this means upstream
4333 * added more info to the caps, as both should be 'fixed' caps) */
4334 if (qtpad->fourcc) {
4335 GstCaps *current_caps;
4337 current_caps = gst_pad_get_current_caps (pad);
4338 g_assert (caps != NULL);
4340 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4341 gst_caps_unref (current_caps);
4342 goto refuse_renegotiation;
4344 GST_DEBUG_OBJECT (qtmux,
4345 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4346 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4347 gst_caps_unref (current_caps);
4350 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4351 GST_DEBUG_PAD_NAME (pad), caps);
4353 /* subtitles default */
4354 subtitle_sample_entry_init (&entry);
4355 qtpad->is_out_of_order = FALSE;
4356 qtpad->sync = FALSE;
4357 qtpad->sparse = TRUE;
4358 qtpad->prepare_buf_func = NULL;
4360 structure = gst_caps_get_structure (caps, 0);
4362 if (gst_structure_has_name (structure, "text/x-raw")) {
4363 const gchar *format = gst_structure_get_string (structure, "format");
4364 if (format && strcmp (format, "utf8") == 0) {
4365 entry.fourcc = FOURCC_tx3g;
4366 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
4367 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
4374 qtpad->fourcc = entry.fourcc;
4376 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
4377 qtmux->context, &entry);
4379 gst_object_unref (qtmux);
4385 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4386 GST_PAD_NAME (pad), caps);
4387 gst_object_unref (qtmux);
4390 refuse_renegotiation:
4392 GST_WARNING_OBJECT (qtmux,
4393 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4395 gst_object_unref (qtmux);
4401 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
4402 GstEvent * event, gpointer user_data)
4405 guint32 avg_bitrate = 0, max_bitrate = 0;
4406 GstPad *pad = data->pad;
4407 gboolean ret = TRUE;
4409 qtmux = GST_QT_MUX_CAST (user_data);
4410 switch (GST_EVENT_TYPE (event)) {
4411 case GST_EVENT_CAPS:
4414 GstQTPad *collect_pad;
4416 gst_event_parse_caps (event, &caps);
4418 /* find stream data */
4419 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4420 g_assert (collect_pad);
4421 g_assert (collect_pad->set_caps);
4423 ret = collect_pad->set_caps (collect_pad, caps);
4424 gst_event_unref (event);
4428 case GST_EVENT_TAG:{
4430 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
4431 GstTagMergeMode mode;
4433 GstQTPad *collect_pad;
4435 GST_OBJECT_LOCK (qtmux);
4436 mode = gst_tag_setter_get_tag_merge_mode (setter);
4437 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4439 gst_event_parse_tag (event, &list);
4440 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
4441 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
4443 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
4444 gst_tag_setter_merge_tags (setter, list, mode);
4445 qtmux->tags_changed = TRUE;
4447 if (!collect_pad->tags)
4448 collect_pad->tags = gst_tag_list_new_empty ();
4449 gst_tag_list_insert (collect_pad->tags, list, mode);
4450 collect_pad->tags_changed = TRUE;
4452 GST_OBJECT_UNLOCK (qtmux);
4454 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
4455 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
4456 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4459 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
4460 qtpad->avg_bitrate = avg_bitrate;
4461 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
4462 qtpad->max_bitrate = max_bitrate;
4465 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
4466 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
4468 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4471 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
4472 qtpad->trak->mdia.mdhd.language_code =
4473 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
4474 (iso_code[2] - 0x60);
4480 gst_event_unref (event);
4490 return gst_collect_pads_event_default (pads, data, event, FALSE);
4496 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
4498 GstQTMux *mux = GST_QT_MUX_CAST (element);
4501 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
4503 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
4504 GstQTPad *qtpad = (GstQTPad *) walk->data;
4505 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
4506 if (qtpad->collect.pad == pad) {
4507 /* this is it, remove */
4508 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
4509 gst_element_remove_pad (element, pad);
4514 gst_collect_pads_remove_pad (mux->collect, pad);
4518 gst_qt_mux_request_new_pad (GstElement * element,
4519 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
4521 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
4522 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4523 GstQTPad *collect_pad;
4525 GstQTPadSetCapsFunc setcaps_func;
4528 gboolean lock = TRUE;
4530 if (templ->direction != GST_PAD_SINK)
4531 goto wrong_direction;
4533 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
4536 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
4537 setcaps_func = gst_qt_mux_audio_sink_set_caps;
4538 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
4539 name = g_strdup (req_name);
4541 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
4543 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
4544 setcaps_func = gst_qt_mux_video_sink_set_caps;
4545 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
4546 name = g_strdup (req_name);
4548 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
4550 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
4551 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
4552 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
4553 name = g_strdup (req_name);
4555 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
4559 goto wrong_template;
4561 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
4563 /* create pad and add to collections */
4564 newpad = gst_pad_new_from_template (templ, name);
4566 collect_pad = (GstQTPad *)
4567 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
4568 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
4570 gst_qt_mux_pad_reset (collect_pad);
4571 collect_pad->trak = atom_trak_new (qtmux->context);
4572 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
4574 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
4576 /* set up pad functions */
4577 collect_pad->set_caps = setcaps_func;
4579 gst_pad_set_active (newpad, TRUE);
4580 gst_element_add_pad (element, newpad);
4587 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
4592 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
4597 GST_WARNING_OBJECT (qtmux, "This is not our template!");
4603 gst_qt_mux_get_property (GObject * object,
4604 guint prop_id, GValue * value, GParamSpec * pspec)
4606 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4608 GST_OBJECT_LOCK (qtmux);
4610 case PROP_MOVIE_TIMESCALE:
4611 g_value_set_uint (value, qtmux->timescale);
4613 case PROP_TRAK_TIMESCALE:
4614 g_value_set_uint (value, qtmux->trak_timescale);
4617 g_value_set_boolean (value, qtmux->guess_pts);
4619 #ifndef GST_REMOVE_DEPRECATED
4620 case PROP_DTS_METHOD:
4621 g_value_set_enum (value, qtmux->dts_method);
4624 case PROP_FAST_START:
4625 g_value_set_boolean (value, qtmux->fast_start);
4627 case PROP_FAST_START_TEMP_FILE:
4628 g_value_set_string (value, qtmux->fast_start_file_path);
4630 case PROP_MOOV_RECOV_FILE:
4631 g_value_set_string (value, qtmux->moov_recov_file_path);
4633 case PROP_FRAGMENT_DURATION:
4634 g_value_set_uint (value, qtmux->fragment_duration);
4636 case PROP_STREAMABLE:
4637 g_value_set_boolean (value, qtmux->streamable);
4639 case PROP_RESERVED_MAX_DURATION:
4640 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4642 case PROP_RESERVED_DURATION_REMAINING:
4643 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
4644 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4646 GstClockTime remaining = qtmux->reserved_duration_remaining;
4648 /* Report the remaining space as the calculated remaining, minus
4649 * however much we've muxed since the last update */
4650 if (remaining > qtmux->muxed_since_last_update)
4651 remaining -= qtmux->muxed_since_last_update;
4654 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
4655 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
4656 remaining, qtmux->reserved_duration_remaining,
4657 qtmux->muxed_since_last_update);
4658 g_value_set_uint64 (value, remaining);
4661 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4662 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
4664 case PROP_RESERVED_BYTES_PER_SEC:
4665 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
4667 #ifdef TIZEN_FEATURE_GST_MUX_ENHANCEMENT
4668 case PROP_EXPECTED_TRAILER_SIZE:
4669 g_value_set_uint(value, qtmux->expected_trailer_size);
4671 #endif /* TIZEN_FEATURE_GST_MUX_ENHANCEMENT */
4673 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4676 GST_OBJECT_UNLOCK (qtmux);
4680 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
4684 g_free (qtmux->fast_start_file_path);
4685 qtmux->fast_start_file_path = NULL;
4687 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
4688 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
4693 gst_qt_mux_set_property (GObject * object,
4694 guint prop_id, const GValue * value, GParamSpec * pspec)
4696 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4698 GST_OBJECT_LOCK (qtmux);
4700 case PROP_MOVIE_TIMESCALE:
4701 qtmux->timescale = g_value_get_uint (value);
4703 case PROP_TRAK_TIMESCALE:
4704 qtmux->trak_timescale = g_value_get_uint (value);
4707 qtmux->guess_pts = g_value_get_boolean (value);
4709 #ifndef GST_REMOVE_DEPRECATED
4710 case PROP_DTS_METHOD:
4711 qtmux->dts_method = g_value_get_enum (value);
4714 case PROP_FAST_START:
4715 qtmux->fast_start = g_value_get_boolean (value);
4717 case PROP_FAST_START_TEMP_FILE:
4718 g_free (qtmux->fast_start_file_path);
4719 qtmux->fast_start_file_path = g_value_dup_string (value);
4720 /* NULL means to generate a random one */
4721 if (!qtmux->fast_start_file_path) {
4722 gst_qt_mux_generate_fast_start_file_path (qtmux);
4725 case PROP_MOOV_RECOV_FILE:
4726 g_free (qtmux->moov_recov_file_path);
4727 qtmux->moov_recov_file_path = g_value_dup_string (value);
4729 case PROP_FRAGMENT_DURATION:
4730 qtmux->fragment_duration = g_value_get_uint (value);
4732 case PROP_STREAMABLE:{
4733 GstQTMuxClass *qtmux_klass =
4734 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4735 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
4736 qtmux->streamable = g_value_get_boolean (value);
4740 case PROP_RESERVED_MAX_DURATION:
4741 qtmux->reserved_max_duration = g_value_get_uint64 (value);
4743 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4744 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
4746 case PROP_RESERVED_BYTES_PER_SEC:
4747 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
4750 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4753 GST_OBJECT_UNLOCK (qtmux);
4756 static GstStateChangeReturn
4757 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
4759 GstStateChangeReturn ret;
4760 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4762 switch (transition) {
4763 case GST_STATE_CHANGE_NULL_TO_READY:
4765 case GST_STATE_CHANGE_READY_TO_PAUSED:
4766 gst_collect_pads_start (qtmux->collect);
4767 qtmux->state = GST_QT_MUX_STATE_STARTED;
4769 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4771 case GST_STATE_CHANGE_PAUSED_TO_READY:
4772 gst_collect_pads_stop (qtmux->collect);
4778 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4780 switch (transition) {
4781 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4783 case GST_STATE_CHANGE_PAUSED_TO_READY:
4784 gst_qt_mux_reset (qtmux, TRUE);
4786 case GST_STATE_CHANGE_READY_TO_NULL:
4796 gst_qt_mux_register (GstPlugin * plugin)
4798 GTypeInfo typeinfo = {
4799 sizeof (GstQTMuxClass),
4800 (GBaseInitFunc) gst_qt_mux_base_init,
4802 (GClassInitFunc) gst_qt_mux_class_init,
4807 (GInstanceInitFunc) gst_qt_mux_init,
4809 static const GInterfaceInfo tag_setter_info = {
4812 static const GInterfaceInfo tag_xmp_writer_info = {
4816 GstQTMuxFormat format;
4817 GstQTMuxClassParams *params;
4820 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
4822 GST_LOG ("Registering muxers");
4825 GstQTMuxFormatProp *prop;
4826 GstCaps *subtitle_caps;
4828 prop = &gst_qt_mux_format_list[i];
4829 format = prop->format;
4830 if (format == GST_QT_MUX_FORMAT_NONE)
4833 /* create a cache for these properties */
4834 params = g_new0 (GstQTMuxClassParams, 1);
4835 params->prop = prop;
4836 params->src_caps = gst_static_caps_get (&prop->src_caps);
4837 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
4838 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
4839 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
4840 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
4841 params->subtitle_sink_caps = subtitle_caps;
4843 gst_caps_unref (subtitle_caps);
4846 /* create the type now */
4847 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
4849 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
4850 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
4851 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
4852 &tag_xmp_writer_info);
4854 if (!gst_element_register (plugin, prop->name, prop->rank, type))
4860 GST_LOG ("Finished registering muxers");
4862 /* FIXME: ideally classification tag should be added and
4863 registered in gstreamer core gsttaglist
4866 GST_LOG ("Registering tags");
4868 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
4869 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
4870 gst_tag_merge_use_first);
4872 GST_LOG ("Finished registering tags");