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>
125 #include <gst/pbutils/pbutils.h>
127 #include <sys/types.h>
129 #include <io.h> /* lseek, open, close, read */
131 #define lseek _lseeki64
133 #define off_t guint64
137 #define ftruncate g_win32_ftruncate
144 #include "gstqtmux.h"
146 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
147 #define GST_CAT_DEFAULT gst_qt_mux_debug
151 * The basic building blocks of MP4 files are:
152 * - an 'ftyp' box at the very start
153 * - an 'mdat' box which contains the raw audio/video/subtitle data;
154 * this is just a bunch of bytes, completely unframed and possibly
155 * unordered with no additional meta-information
156 * - a 'moov' box that contains information about the different streams
157 * and what they contain, as well as sample tables for each stream
158 * that tell the demuxer where in the mdat box each buffer/sample is
159 * and what its duration/timestamp etc. is, and whether it's a
161 * Additionally, fragmented MP4 works by writing chunks of data in
162 * pairs of 'moof' and 'mdat' boxes:
163 * - 'moof' boxes, header preceding each mdat fragment describing the
164 * contents, like a moov but only for that fragment.
165 * - a 'mfra' box for Fragmented MP4, which is written at the end and
166 * contains a summary of all fragments and seek tables.
168 * Currently mp4mux can work in 4 different modes / generate 4 types
169 * of output files/streams:
171 * - Normal mp4: mp4mux will write a little ftyp identifier at the
172 * beginning, then start an mdat box into which it will write all the
173 * sample data. At EOS it will then write the moov header with track
174 * headers and sample tables at the end of the file, and rewrite the
175 * start of the file to fix up the mdat box size at the beginning.
176 * It has to wait for EOS to write the moov (which includes the
177 * sample tables) because it doesn't know how much space those
178 * tables will be. The output downstream must be seekable to rewrite
179 * the mdat box at EOS.
181 * - Fragmented mp4: moov header with track headers at start
182 * but no sample table, followed by N fragments, each containing
183 * track headers with sample tables followed by some data. Downstream
184 * does not need to be seekable if the 'streamable' flag is TRUE,
185 * as the final mfra and total duration will be omitted.
187 * - Fast-start mp4: the goal here is to create a file where the moov
188 * headers are at the beginning; what mp4mux will do is write all
189 * sample data into a temp file and build moov header plus sample
190 * tables in memory and then when EOS comes, it will push out the
191 * moov header plus sample tables at the beginning, followed by the
192 * mdat sample data at the end which is read in from the temp file
193 * Files created in this mode are better for streaming over the
194 * network, since the client doesn't have to seek to the end of the
195 * file to get the headers, but it requires copying all sample data
196 * out of the temp file at EOS, which can be expensive. Downstream does
197 * not need to be seekable, because of the use of the temp file.
199 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
200 * and reserved-moov-update-period properties to reserve free space
201 * at the start of the file and periodically write the MOOV atom out
202 * to it. That means that killing the muxing at any point still
203 * results in a playable file, at the cost of wasting some amount of
204 * free space at the start of file. The approximate recording duration
205 * has to be known in advance to estimate how much free space to reserve
206 * for the moov, and the downstream must be seekable.
207 * If the moov header grows larger than the reserved space, an error
208 * is generated - so it's better to over-estimate the amount of space
209 * to reserve. To ensure the file is playable at any point, the moov
210 * is updated using a 'ping-pong' strategy, so the output is never in
214 #ifndef GST_REMOVE_DEPRECATED
223 gst_qt_mux_dts_method_get_type (void)
225 static GType gst_qt_mux_dts_method = 0;
227 if (!gst_qt_mux_dts_method) {
228 static const GEnumValue dts_methods[] = {
229 {DTS_METHOD_DD, "delta/duration", "dd"},
230 {DTS_METHOD_REORDER, "reorder", "reorder"},
231 {DTS_METHOD_ASC, "ascending", "asc"},
235 gst_qt_mux_dts_method =
236 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
239 return gst_qt_mux_dts_method;
242 #define GST_TYPE_QT_MUX_DTS_METHOD \
243 (gst_qt_mux_dts_method_get_type ())
246 /* QTMux signals and args */
256 PROP_MOVIE_TIMESCALE,
259 PROP_FAST_START_TEMP_FILE,
260 PROP_MOOV_RECOV_FILE,
261 PROP_FRAGMENT_DURATION,
263 PROP_RESERVED_MAX_DURATION,
264 PROP_RESERVED_DURATION_REMAINING,
265 PROP_RESERVED_MOOV_UPDATE_PERIOD,
266 PROP_RESERVED_BYTES_PER_SEC,
267 #ifndef GST_REMOVE_DEPRECATED
271 PROP_INTERLEAVE_BYTES,
272 PROP_INTERLEAVE_TIME,
275 /* some spare for header size as well */
276 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
278 #define DEFAULT_MOVIE_TIMESCALE 0
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
292 #define DEFAULT_INTERLEAVE_BYTES 0
293 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
295 static void gst_qt_mux_finalize (GObject * object);
297 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
298 GstStateChange transition);
300 /* property functions */
301 static void gst_qt_mux_set_property (GObject * object,
302 guint prop_id, const GValue * value, GParamSpec * pspec);
303 static void gst_qt_mux_get_property (GObject * object,
304 guint prop_id, GValue * value, GParamSpec * pspec);
307 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
308 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
309 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
312 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
313 GstCollectData * data, GstEvent * event, gpointer user_data);
315 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
317 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
321 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
323 static GstElementClass *parent_class = NULL;
326 gst_qt_mux_base_init (gpointer g_class)
328 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
329 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
330 GstQTMuxClassParams *params;
331 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
332 GstPadTemplate *srctempl;
333 gchar *longname, *description;
336 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
337 GST_QT_MUX_PARAMS_QDATA);
338 g_assert (params != NULL);
340 /* construct the element details struct */
341 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
342 description = g_strdup_printf ("Multiplex audio and video into a %s file",
343 params->prop->long_name);
344 gst_element_class_set_static_metadata (element_class, longname,
345 "Codec/Muxer", description,
346 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
348 g_free (description);
351 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
352 GST_PAD_ALWAYS, params->src_caps);
353 gst_element_class_add_pad_template (element_class, srctempl);
355 if (params->audio_sink_caps) {
356 audiosinktempl = gst_pad_template_new ("audio_%u",
357 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
358 gst_element_class_add_pad_template (element_class, audiosinktempl);
361 if (params->video_sink_caps) {
362 videosinktempl = gst_pad_template_new ("video_%u",
363 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
364 gst_element_class_add_pad_template (element_class, videosinktempl);
367 if (params->subtitle_sink_caps) {
368 subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
369 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
370 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
373 klass->format = params->prop->format;
377 gst_qt_mux_class_init (GstQTMuxClass * klass)
379 GObjectClass *gobject_class;
380 GstElementClass *gstelement_class;
381 GParamFlags streamable_flags;
382 const gchar *streamable_desc;
384 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
385 "be streamed and hence no indexes written or duration written."
387 gobject_class = (GObjectClass *) klass;
388 gstelement_class = (GstElementClass *) klass;
390 parent_class = g_type_class_peek_parent (klass);
392 gobject_class->finalize = gst_qt_mux_finalize;
393 gobject_class->get_property = gst_qt_mux_get_property;
394 gobject_class->set_property = gst_qt_mux_set_property;
396 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
397 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
398 streamable_desc = STREAMABLE_DESC;
399 streamable = DEFAULT_STREAMABLE;
402 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
403 streamable_flags |= G_PARAM_DEPRECATED;
407 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
408 g_param_spec_uint ("movie-timescale", "Movie timescale",
409 "Timescale to use in the movie (units per second, 0 == default)",
410 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
411 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
412 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
413 g_param_spec_uint ("trak-timescale", "Track timescale",
414 "Timescale to use for the tracks (units per second, 0 is automatic)",
415 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
416 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
417 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
418 g_param_spec_boolean ("presentation-time",
419 "Include presentation-time info",
420 "Calculate and include presentation/composition time "
421 "(in addition to decoding time)", DEFAULT_DO_CTTS,
422 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
423 #ifndef GST_REMOVE_DEPRECATED
424 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
425 g_param_spec_enum ("dts-method", "dts-method",
426 "Method to determine DTS time (DEPRECATED)",
427 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
428 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
429 G_PARAM_STATIC_STRINGS));
431 g_object_class_install_property (gobject_class, PROP_FAST_START,
432 g_param_spec_boolean ("faststart", "Format file to faststart",
433 "If the file should be formatted for faststart (headers first)",
434 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
436 g_param_spec_string ("faststart-file", "File to use for storing buffers",
437 "File that will be used temporarily to store data from the stream "
438 "when creating a faststart file. If null a filepath will be "
439 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
440 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
441 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
442 g_param_spec_string ("moov-recovery-file",
443 "File to store data for posterior moov atom recovery",
444 "File to be used to store "
445 "data for moov atom making movie file recovery possible in case "
446 "of a crash during muxing. Null for disabled. (Experimental)",
447 DEFAULT_MOOV_RECOV_FILE,
448 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
449 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
450 g_param_spec_uint ("fragment-duration", "Fragment duration",
451 "Fragment durations in ms (produce a fragmented file if > 0)",
452 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
453 2000 : DEFAULT_FRAGMENT_DURATION,
454 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
455 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
456 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
457 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
458 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
459 g_param_spec_uint64 ("reserved-max-duration",
460 "Reserved maximum file duration (ns)",
461 "When set to a value > 0, reserves space for index tables at the "
462 "beginning of the file.",
463 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
464 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
465 g_object_class_install_property (gobject_class,
466 PROP_RESERVED_DURATION_REMAINING,
467 g_param_spec_uint64 ("reserved-duration-remaining",
468 "Report the approximate amount of remaining recording space (ns)",
469 "Reports the approximate amount of remaining moov header space "
470 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
471 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
472 g_object_class_install_property (gobject_class,
473 PROP_RESERVED_MOOV_UPDATE_PERIOD,
474 g_param_spec_uint64 ("reserved-moov-update-period",
475 "Interval at which to update index tables (ns)",
476 "When used with reserved-max-duration, periodically updates the "
477 "index tables with information muxed so far.", 0, G_MAXUINT64,
478 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
479 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
480 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
481 g_param_spec_uint ("reserved-bytes-per-sec",
482 "Reserved MOOV bytes per second, per track",
483 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
484 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
485 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
486 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
487 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
488 "Interleave between streams in bytes",
489 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
490 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
492 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
493 "Interleave between streams in nanoseconds",
494 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
495 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
497 gstelement_class->request_new_pad =
498 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
499 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
500 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
504 gst_qt_mux_pad_reset (GstQTPad * qtpad)
507 qtpad->is_out_of_order = FALSE;
508 qtpad->sample_size = 0;
511 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
512 qtpad->first_ts = GST_CLOCK_TIME_NONE;
513 qtpad->first_dts = GST_CLOCK_TIME_NONE;
514 qtpad->prepare_buf_func = NULL;
515 qtpad->create_empty_buffer = NULL;
516 qtpad->avg_bitrate = 0;
517 qtpad->max_bitrate = 0;
518 qtpad->total_duration = 0;
519 qtpad->total_bytes = 0;
520 qtpad->sparse = FALSE;
525 gst_buffer_replace (&qtpad->last_buf, NULL);
528 gst_tag_list_unref (qtpad->tags);
532 /* reference owned elsewhere */
534 qtpad->tc_trak = NULL;
537 atom_traf_free (qtpad->traf);
540 atom_array_clear (&qtpad->fragment_buffers);
542 /* reference owned elsewhere */
547 * Takes GstQTMux back to its initial state
550 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
554 qtmux->state = GST_QT_MUX_STATE_NONE;
555 qtmux->header_size = 0;
556 qtmux->mdat_size = 0;
559 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
560 qtmux->fragment_sequence = 0;
563 atom_ftyp_free (qtmux->ftyp);
567 atom_moov_free (qtmux->moov);
571 atom_mfra_free (qtmux->mfra);
574 if (qtmux->fast_start_file) {
575 fclose (qtmux->fast_start_file);
576 g_remove (qtmux->fast_start_file_path);
577 qtmux->fast_start_file = NULL;
579 if (qtmux->moov_recov_file) {
580 fclose (qtmux->moov_recov_file);
581 qtmux->moov_recov_file = NULL;
583 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
584 AtomInfo *ainfo = (AtomInfo *) walk->data;
585 ainfo->free_func (ainfo->atom);
588 g_slist_free (qtmux->extra_atoms);
589 qtmux->extra_atoms = NULL;
591 GST_OBJECT_LOCK (qtmux);
592 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
593 GST_OBJECT_UNLOCK (qtmux);
596 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
597 GstQTPad *qtpad = (GstQTPad *) walk->data;
598 gst_qt_mux_pad_reset (qtpad);
600 /* hm, moov_free above yanked the traks away from us,
601 * so do not free, but do clear */
606 qtmux->moov = atom_moov_new (qtmux->context);
607 /* ensure all is as nice and fresh as request_new_pad would provide it */
608 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
609 GstQTPad *qtpad = (GstQTPad *) walk->data;
611 qtpad->trak = atom_trak_new (qtmux->context);
612 atom_moov_add_trak (qtmux->moov, qtpad->trak);
616 qtmux->current_pad = NULL;
617 qtmux->current_chunk_size = 0;
618 qtmux->current_chunk_duration = 0;
619 qtmux->current_chunk_offset = -1;
621 qtmux->reserved_moov_size = 0;
622 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
623 qtmux->muxed_since_last_update = 0;
624 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
625 qtmux->first_pts = GST_CLOCK_TIME_NONE;
628 gst_video_time_code_free (qtmux->first_tc);
629 qtmux->first_tc = NULL;
633 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
635 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
636 GstPadTemplate *templ;
638 templ = gst_element_class_get_pad_template (klass, "src");
639 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
640 gst_pad_use_fixed_caps (qtmux->srcpad);
641 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
643 qtmux->sinkpads = NULL;
644 qtmux->collect = gst_collect_pads_new ();
645 gst_collect_pads_set_event_function (qtmux->collect,
646 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
647 gst_collect_pads_set_clip_function (qtmux->collect,
648 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
649 gst_collect_pads_set_function (qtmux->collect,
650 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
652 /* properties set to default upon construction */
654 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
655 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
656 qtmux->reserved_bytes_per_sec_per_trak =
657 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
658 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
659 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
661 /* always need this */
663 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
665 /* internals to initial state */
666 gst_qt_mux_reset (qtmux, TRUE);
671 gst_qt_mux_finalize (GObject * object)
673 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
675 gst_qt_mux_reset (qtmux, FALSE);
677 g_free (qtmux->fast_start_file_path);
678 g_free (qtmux->moov_recov_file_path);
680 atoms_context_free (qtmux->context);
681 gst_object_unref (qtmux->collect);
683 g_slist_free (qtmux->sinkpads);
685 G_OBJECT_CLASS (parent_class)->finalize (object);
689 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
696 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
701 size = gst_buffer_get_size (buf);
702 newbuf = gst_buffer_new_and_alloc (size + 8);
703 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
705 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
706 GST_WRITE_UINT32_BE (map.data, map.size);
707 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
709 gst_buffer_unmap (buf, &map);
710 gst_buffer_unref (buf);
716 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
723 const guint8 *dataend;
725 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
730 gst_buffer_map (buf, &frommap, GST_MAP_READ);
732 dataend = memchr (frommap.data, 0, frommap.size);
733 size = dataend ? dataend - frommap.data : frommap.size;
734 newbuf = gst_buffer_new_and_alloc (size + 2);
736 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
738 GST_WRITE_UINT16_BE (tomap.data, size);
739 memcpy (tomap.data + 2, frommap.data, size);
741 gst_buffer_unmap (newbuf, &tomap);
742 gst_buffer_unmap (buf, &frommap);
744 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
746 /* gst_buffer_copy_into is trying to be too clever and
747 * won't copy duration when size is different */
748 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
750 gst_buffer_unref (buf);
756 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
757 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
762 g_return_if_fail (qtpad->trak_ste);
764 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
766 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
770 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
774 GstByteReader reader;
777 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
778 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
782 if (G_UNLIKELY (map.size < 8))
785 gst_byte_reader_init (&reader, map.data, map.size);
786 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
791 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
793 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
796 gst_bit_reader_init (&bits, map.data, map.size);
798 /* off + sync + crc */
799 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
801 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
802 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
803 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
804 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
805 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
807 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
808 gst_bit_reader_skip_unchecked (&bits, 2);
809 if ((acmod & 0x4)) /* if a surround channel exists */
810 gst_bit_reader_skip_unchecked (&bits, 2);
811 if (acmod == 0x2) /* if in 2/0 mode */
812 gst_bit_reader_skip_unchecked (&bits, 2);
814 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
816 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
817 bsmod, acmod, lfe_on);
819 /* AC-3 spec says that those values should be constant for the
820 * whole stream when muxed in mp4. We trust the input follows it */
821 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
822 "prepare buffer function");
823 qtpad->prepare_buf_func = NULL;
827 gst_buffer_unmap (buf, &map);
832 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
837 GST_WRITE_UINT16_BE (data, 0);
839 return gst_buffer_new_wrapped (data, 2);
843 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
844 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
846 switch (gst_tag_get_type (tag)) {
852 if (!gst_tag_list_get_string (list, tag, &str) || !str)
854 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
855 GST_FOURCC_ARGS (fourcc), str);
856 atom_udta_add_str_tag (udta, fourcc, str);
865 if (!gst_tag_list_get_double (list, tag, &value))
867 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
868 GST_FOURCC_ARGS (fourcc), (gint) value);
869 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
876 /* paired unsigned integers */
880 got_tag = gst_tag_list_get_uint (list, tag, &value);
881 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
884 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
885 GST_FOURCC_ARGS (fourcc), value, count);
886 atom_udta_add_uint_tag (udta, fourcc, 0,
887 value << 16 | (count & 0xFFFF));
889 /* unpaired unsigned integers */
890 if (!gst_tag_list_get_uint (list, tag, &value))
892 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
893 GST_FOURCC_ARGS (fourcc), value);
894 atom_udta_add_uint_tag (udta, fourcc, 1, value);
899 g_assert_not_reached ();
905 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
906 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
914 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
916 if (!gst_tag_list_get_date (list, tag, &date) || !date)
919 year = g_date_get_year (date);
920 month = g_date_get_month (date);
921 day = g_date_get_day (date);
925 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
926 day == G_DATE_BAD_DAY) {
927 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
931 str = g_strdup_printf ("%u-%u-%u", year, month, day);
932 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
933 GST_FOURCC_ARGS (fourcc), str);
934 atom_udta_add_str_tag (udta, fourcc, str);
939 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
940 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
942 GValue value = { 0, };
946 GstStructure *structure;
950 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
952 if (!gst_tag_list_copy_value (&value, list, tag))
955 sample = gst_value_get_sample (&value);
960 buf = gst_sample_get_buffer (sample);
964 caps = gst_sample_get_caps (sample);
966 GST_WARNING_OBJECT (qtmux, "preview image without caps");
970 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
972 structure = gst_caps_get_structure (caps, 0);
973 if (gst_structure_has_name (structure, "image/jpeg"))
975 else if (gst_structure_has_name (structure, "image/png"))
979 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
983 gst_buffer_map (buf, &map, GST_MAP_READ);
984 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
985 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
986 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
987 gst_buffer_unmap (buf, &map);
989 g_value_unset (&value);
993 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
994 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
999 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1000 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1002 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1006 if (!gst_tag_list_get_uint (list, tag2, &number))
1010 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1011 GST_FOURCC_ARGS (fourcc), str);
1012 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1014 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1015 GST_FOURCC_ARGS (fourcc), str, number);
1016 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1023 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1024 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1029 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1031 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1034 year = g_date_get_year (date);
1037 if (year == G_DATE_BAD_YEAR) {
1038 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1042 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1043 GST_FOURCC_ARGS (fourcc), year);
1044 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1048 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1049 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1051 gdouble latitude = -360, longitude = -360, altitude = 0;
1052 gchar *location = NULL;
1053 guint8 *data, *ddata;
1054 gint size = 0, len = 0;
1055 gboolean ret = FALSE;
1057 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1059 ret = gst_tag_list_get_string (list, tag, &location);
1060 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1062 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1064 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1071 len = strlen (location);
1072 size += len + 1 + 2;
1074 /* role + (long, lat, alt) + body + notes */
1075 size += 1 + 3 * 4 + 1 + 1;
1077 data = ddata = g_malloc (size);
1080 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1083 memcpy (data + 2, location, len);
1084 GST_WRITE_UINT8 (data + 2 + len, 0);
1085 data += len + 1 + 2;
1087 GST_WRITE_UINT8 (data, 0);
1088 /* long, lat, alt */
1089 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1090 QT_WRITE_SFP32 (data + 1, longitude);
1091 QT_WRITE_SFP32 (data + 5, latitude);
1092 QT_WRITE_SFP32 (data + 9, altitude);
1093 /* neither astronomical body nor notes */
1094 GST_WRITE_UINT16_BE (data + 13, 0);
1096 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1097 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1102 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1103 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1105 gchar *keywords = NULL;
1106 guint8 *data, *ddata;
1110 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1112 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1115 kwds = g_strsplit (keywords, ",", 0);
1119 for (i = 0; kwds[i]; i++) {
1120 /* size byte + null-terminator */
1121 size += strlen (kwds[i]) + 1 + 1;
1124 /* language tag + count + keywords */
1127 data = ddata = g_malloc (size);
1130 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1132 GST_WRITE_UINT8 (data + 2, i);
1135 for (i = 0; kwds[i]; ++i) {
1136 gint len = strlen (kwds[i]);
1138 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1139 GST_FOURCC_ARGS (fourcc), kwds[i]);
1141 GST_WRITE_UINT8 (data, len + 1);
1142 memcpy (data + 1, kwds[i], len + 1);
1148 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1153 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1154 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1162 size = strlen (input);
1164 if (size < 4 + 3 + 1 + 1 + 1) {
1165 /* at least the minimum xxxx://y/z */
1166 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1171 /* read the fourcc */
1172 memcpy (&fourcc, data, 4);
1176 if (strncmp (data, "://", 3) != 0) {
1182 /* read the table number */
1183 if (sscanf (data, "%d", &table) != 1) {
1187 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1188 ", table numbers should be positive, ignoring tag", table);
1192 /* find the next / */
1193 while (size > 0 && data[0] != '/') {
1200 g_assert (data[0] == '/');
1209 /* read up the rest of the string */
1210 *p_content = g_strdup (data);
1211 *p_table = (guint16) table;
1217 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1218 "input (%s) didn't match the expected entitycode://table/content",
1225 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1226 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1228 gchar *clsf_data = NULL;
1232 gchar *content = NULL;
1235 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1237 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1240 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1241 GST_FOURCC_ARGS (fourcc), clsf_data);
1243 /* parse the string, format is:
1244 * entityfourcc://table/content
1246 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1250 size = strlen (content) + 1;
1252 /* now we have everything, build the atom
1253 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1254 data = g_malloc (4 + 2 + 2 + size);
1255 GST_WRITE_UINT32_LE (data, entity);
1256 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1257 GST_WRITE_UINT16_BE (data + 6, 0);
1258 memcpy (data + 8, content, size);
1261 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1265 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1266 const GstTagList * list, AtomUDTA * udta, const char *tag,
1267 const char *tag2, guint32 fourcc);
1270 * Struct to record mappings from gstreamer tags to fourcc codes
1272 typedef struct _GstTagToFourcc
1275 const gchar *gsttag;
1276 const gchar *gsttag2;
1277 const GstQTMuxAddUdtaTagFunc func;
1280 /* tag list tags to fourcc matching */
1281 static const GstTagToFourcc tag_matches_mp4[] = {
1282 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1283 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1284 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1285 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1286 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1287 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1288 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1289 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1290 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1291 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1292 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1293 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1294 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1295 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1296 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1297 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1298 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1299 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1300 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1301 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1302 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1303 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1304 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1305 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1306 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1307 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1308 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1309 gst_qt_mux_add_mp4_tag},
1310 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1311 gst_qt_mux_add_mp4_tag},
1312 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1313 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1317 static const GstTagToFourcc tag_matches_3gp[] = {
1318 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1319 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1320 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1321 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1322 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1323 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1324 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1325 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1326 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1327 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1328 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1329 gst_qt_mux_add_3gp_classification},
1333 /* qtdemux produces these for atoms it cannot parse */
1334 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1337 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1339 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1340 GstBuffer *xmp = NULL;
1342 /* adobe specs only have 'quicktime' and 'mp4',
1343 * but I guess we can extrapolate to gpp.
1344 * Keep mj2 out for now as we don't add any tags for it yet.
1345 * If you have further info about xmp on these formats, please share */
1346 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1349 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1351 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1352 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1355 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1358 /* for isom/mp4, it is a top level uuid atom */
1359 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1362 ainfo = build_uuid_xmp_atom (xmp);
1364 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1369 gst_buffer_unref (xmp);
1373 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1376 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1379 const gchar *tag, *tag2;
1380 const GstTagToFourcc *tag_matches;
1382 switch (qtmux_klass->format) {
1383 case GST_QT_MUX_FORMAT_3GP:
1384 tag_matches = tag_matches_3gp;
1386 case GST_QT_MUX_FORMAT_MJ2:
1390 /* sort of iTunes style for mp4 and QT (?) */
1391 tag_matches = tag_matches_mp4;
1398 /* Clear existing tags so we don't add them over and over */
1399 atom_udta_clear_tags (udta);
1401 for (i = 0; tag_matches[i].fourcc; i++) {
1402 fourcc = tag_matches[i].fourcc;
1403 tag = tag_matches[i].gsttag;
1404 tag2 = tag_matches[i].gsttag2;
1406 g_assert (tag_matches[i].func);
1407 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1410 /* add unparsed blobs if present */
1411 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1414 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1415 for (i = 0; i < num_tags; ++i) {
1416 GstSample *sample = NULL;
1418 const GstStructure *s;
1420 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1423 buf = gst_sample_get_buffer (sample);
1425 if (buf && (s = gst_sample_get_info (sample))) {
1426 const gchar *style = NULL;
1429 gst_buffer_map (buf, &map, GST_MAP_READ);
1430 GST_DEBUG_OBJECT (qtmux,
1431 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1432 GST_PTR_FORMAT, i, num_tags, map.size, s);
1433 if (s && (style = gst_structure_get_string (s, "style"))) {
1434 /* try to prevent some style tag ending up into another variant
1435 * (todo: make into a list if more cases) */
1436 if ((strcmp (style, "itunes") == 0 &&
1437 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1438 (strcmp (style, "iso") == 0 &&
1439 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1440 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1441 atom_udta_add_blob_tag (udta, map.data, map.size);
1444 gst_buffer_unmap (buf, &map);
1446 gst_sample_unref (sample);
1454 * Gets the tagsetter iface taglist and puts the known tags
1455 * into the output stream
1458 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1460 const GstTagList *tags = NULL;
1463 GST_OBJECT_LOCK (qtmux);
1464 if (qtmux->tags_changed) {
1465 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1466 qtmux->tags_changed = FALSE;
1468 GST_OBJECT_UNLOCK (qtmux);
1470 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1472 if (tags && !gst_tag_list_is_empty (tags)) {
1473 GstTagList *copy = gst_tag_list_copy (tags);
1475 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1476 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1477 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1478 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1480 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1481 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1482 gst_qt_mux_add_xmp_tags (qtmux, copy);
1483 gst_tag_list_unref (copy);
1485 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1488 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1489 GstCollectData *cdata = (GstCollectData *) walk->data;
1490 GstQTPad *qpad = (GstQTPad *) cdata;
1491 GstPad *pad = qpad->collect.pad;
1493 if (qpad->tags_changed && qpad->tags) {
1494 GST_DEBUG_OBJECT (pad, "Adding tags");
1495 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1496 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1497 qpad->tags_changed = FALSE;
1498 GST_DEBUG_OBJECT (pad, "Tags added");
1500 GST_DEBUG_OBJECT (pad, "No new tags received");
1505 static inline GstBuffer *
1506 _gst_buffer_new_take_data (guint8 * data, guint size)
1510 buf = gst_buffer_new ();
1511 gst_buffer_append_memory (buf,
1512 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1517 static GstFlowReturn
1518 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1524 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1526 size = gst_buffer_get_size (buf);
1527 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1529 if (mind_fast && qtmux->fast_start_file) {
1533 GST_LOG_OBJECT (qtmux, "to temporary file");
1534 gst_buffer_map (buf, &map, GST_MAP_READ);
1535 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1536 gst_buffer_unmap (buf, &map);
1537 gst_buffer_unref (buf);
1543 GST_LOG_OBJECT (qtmux, "downstream");
1544 res = gst_pad_push (qtmux->srcpad, buf);
1547 if (G_LIKELY (offset))
1555 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1556 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1557 return GST_FLOW_ERROR;
1562 gst_qt_mux_seek_to_beginning (FILE * f)
1565 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1567 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1568 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1571 if (fseek (f, (long) 0, SEEK_SET) != 0)
1577 static GstFlowReturn
1578 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1580 GstFlowReturn ret = GST_FLOW_OK;
1581 GstBuffer *buf = NULL;
1583 if (fflush (qtmux->fast_start_file))
1586 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1589 /* hm, this could all take a really really long time,
1590 * but there may not be another way to get moov atom first
1591 * (somehow optimize copy?) */
1592 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1593 while (ret == GST_FLOW_OK) {
1594 const int bufsize = 4096;
1598 buf = gst_buffer_new_and_alloc (bufsize);
1599 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1600 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1602 gst_buffer_unmap (buf, &map);
1605 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1606 gst_buffer_unmap (buf, &map);
1607 if (size != bufsize)
1608 gst_buffer_set_size (buf, size);
1609 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1613 gst_buffer_unref (buf);
1615 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1617 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1625 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1626 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1627 ret = GST_FLOW_ERROR;
1632 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1633 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1634 ret = GST_FLOW_ERROR;
1639 /* clear descriptor so we don't remove temp file later on,
1640 * might be possible to recover */
1641 fclose (qtmux->fast_start_file);
1642 qtmux->fast_start_file = NULL;
1648 * Sends the initial mdat atom fields (size fields and fourcc type),
1649 * the subsequent buffers are considered part of it's data.
1650 * As we can't predict the amount of data that we are going to place in mdat
1651 * we need to record the position of the size field in the stream so we can
1652 * seek back to it later and update when the streams have finished.
1654 static GstFlowReturn
1655 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1656 gboolean extended, gboolean fsync_after)
1661 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1662 "size %" G_GUINT64_FORMAT, size);
1664 /* if the qtmux state is EOS, really write the mdat, otherwise
1665 * allow size == 0 for a placeholder atom */
1666 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1670 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1671 /* Always write 16-bytes, but put a free atom first
1672 * if the size is < 4GB. */
1673 buf = gst_buffer_new_and_alloc (16);
1674 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1677 /* Write extended mdat header and large_size field */
1678 GST_WRITE_UINT32_BE (map.data, 1);
1679 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1680 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1682 /* Write an empty free atom, then standard 32-bit mdat */
1683 GST_WRITE_UINT32_BE (map.data, 8);
1684 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1685 GST_WRITE_UINT32_BE (map.data + 8, size);
1686 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1688 gst_buffer_unmap (buf, &map);
1690 buf = gst_buffer_new_and_alloc (8);
1691 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1693 /* Vanilla 32-bit mdat */
1694 GST_WRITE_UINT32_BE (map.data, size);
1695 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1696 gst_buffer_unmap (buf, &map);
1699 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1701 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1703 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1708 * We get the position of the mdat size field, seek back to it
1709 * and overwrite with the real value
1711 static GstFlowReturn
1712 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1713 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1717 /* We must have recorded the mdat position for this to work */
1718 g_assert (mdat_pos != 0);
1720 /* seek and rewrite the header */
1721 gst_segment_init (&segment, GST_FORMAT_BYTES);
1722 segment.start = mdat_pos;
1723 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1725 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1729 static GstFlowReturn
1730 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1733 guint64 size = 0, offset = 0;
1734 guint8 *data = NULL;
1736 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1738 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1739 goto serialize_error;
1741 buf = _gst_buffer_new_take_data (data, offset);
1743 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1744 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1749 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1750 ("Failed to serialize ftyp"));
1751 return GST_FLOW_ERROR;
1756 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1757 GstBuffer ** p_prefix)
1759 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1760 guint32 major, version;
1762 GstBuffer *prefix = NULL;
1763 AtomFTYP *ftyp = NULL;
1765 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1767 /* init and send context and ftyp based on current property state */
1768 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1769 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1770 qtmux->fast_start_file != NULL);
1771 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1778 gst_buffer_unref (prefix);
1783 static GstFlowReturn
1784 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1786 GstFlowReturn ret = GST_FLOW_OK;
1787 GstBuffer *prefix = NULL;
1789 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1791 /* init and send context and ftyp based on current property state */
1793 atom_ftyp_free (qtmux->ftyp);
1796 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1798 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1799 if (ret != GST_FLOW_OK)
1802 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1806 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1808 GstStructure *structure;
1809 GValue array = { 0 };
1810 GValue value = { 0 };
1811 GstCaps *caps, *tcaps;
1813 tcaps = gst_pad_get_current_caps (mux->srcpad);
1814 caps = gst_caps_copy (tcaps);
1815 gst_caps_unref (tcaps);
1817 structure = gst_caps_get_structure (caps, 0);
1819 g_value_init (&array, GST_TYPE_ARRAY);
1821 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1822 g_value_init (&value, GST_TYPE_BUFFER);
1823 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1824 gst_value_array_append_value (&array, &value);
1825 g_value_unset (&value);
1827 gst_structure_set_value (structure, "streamheader", &array);
1828 g_value_unset (&array);
1829 gst_pad_set_caps (mux->srcpad, caps);
1830 gst_caps_unref (caps);
1834 * Write out a free space atom. The offset is adjusted by the full
1835 * size, but a smaller buffer is sent
1837 static GstFlowReturn
1838 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1839 gboolean fsync_after)
1843 guint8 *data = NULL;
1844 guint64 offset = 0, bsize = 0;
1847 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1849 /* We can't make a free space atom smaller than the header */
1853 node_header = g_malloc0 (sizeof (Atom));
1854 node_header->type = FOURCC_free;
1855 node_header->size = size;
1858 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
1859 goto serialize_error;
1861 buf = _gst_buffer_new_take_data (data, offset);
1862 g_free (node_header);
1865 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1867 GST_LOG_OBJECT (qtmux, "Pushing free atom");
1868 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1875 /* Make sure downstream position ends up at the end of this free box */
1876 gst_segment_init (&segment, GST_FORMAT_BYTES);
1877 segment.start = *off;
1878 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1886 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1887 ("Not enough free reserved space"));
1888 return GST_FLOW_ERROR;
1892 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1893 ("Failed to serialize mdat"));
1894 g_free (node_header);
1895 return GST_FLOW_ERROR;
1900 gst_qt_mux_configure_moov (GstQTMux * qtmux)
1902 gboolean fragmented = FALSE;
1905 GST_OBJECT_LOCK (qtmux);
1906 timescale = qtmux->timescale;
1907 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
1908 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
1910 GST_OBJECT_UNLOCK (qtmux);
1912 /* inform lower layers of our property wishes, and determine duration.
1913 * Let moov take care of this using its list of traks;
1914 * so that released pads are also included */
1915 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1917 atom_moov_update_timescale (qtmux->moov, timescale);
1918 atom_moov_set_fragmented (qtmux->moov, fragmented);
1920 atom_moov_update_duration (qtmux->moov);
1923 static GstFlowReturn
1924 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
1925 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
1927 guint64 offset = 0, size = 0;
1930 GstFlowReturn ret = GST_FLOW_OK;
1932 guint64 current_time = atoms_get_current_qt_time ();
1934 /* update modification times */
1935 qtmux->moov->mvhd.time_info.modification_time = current_time;
1936 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1937 GstCollectData *cdata = (GstCollectData *) walk->data;
1938 GstQTPad *qtpad = (GstQTPad *) cdata;
1940 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
1941 qtpad->trak->tkhd.modification_time = current_time;
1944 /* serialize moov */
1947 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1948 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1949 goto serialize_error;
1950 qtmux->last_moov_size = offset;
1952 /* Check we have enough reserved space for this and a Free atom */
1953 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
1954 goto too_small_reserved;
1955 buf = _gst_buffer_new_take_data (data, offset);
1956 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1958 /* If at EOS, this is the final moov, put in the streamheader
1959 * (apparently used by a flumotion util) */
1960 if (qtmux->state == GST_QT_MUX_STATE_EOS)
1961 gst_qt_mux_set_header_on_caps (qtmux, buf);
1964 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1965 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1967 /* Write out a free atom if needed */
1968 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
1969 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
1970 (guint32) (padded_moov_size - offset));
1972 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
1979 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
1980 ("Not enough free reserved header space"),
1981 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
1982 offset, padded_moov_size));
1983 return GST_FLOW_ERROR;
1988 return GST_FLOW_ERROR;
1992 /* either calculates size of extra atoms or pushes them */
1993 static GstFlowReturn
1994 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1998 guint64 loffset = 0, size = 0;
2000 GstFlowReturn ret = GST_FLOW_OK;
2002 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2003 AtomInfo *ainfo = (AtomInfo *) walk->data;
2007 if (!ainfo->copy_data_func (ainfo->atom,
2008 send ? &data : NULL, &size, &loffset))
2009 goto serialize_error;
2014 GST_DEBUG_OBJECT (qtmux,
2015 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2016 GST_FOURCC_ARGS (ainfo->atom->type));
2017 buf = _gst_buffer_new_take_data (data, loffset);
2018 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2019 if (ret != GST_FLOW_OK)
2032 return GST_FLOW_ERROR;
2037 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2039 gboolean seekable = FALSE;
2040 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2042 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2043 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2044 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2046 /* have to assume seeking is not supported if query not handled downstream */
2047 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2050 gst_query_unref (query);
2056 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2059 gboolean fail = FALSE;
2060 AtomFTYP *ftyp = NULL;
2061 GstBuffer *prefix = NULL;
2063 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2064 qtmux->moov_recov_file_path);
2066 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2067 if (qtmux->moov_recov_file == NULL) {
2068 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2069 qtmux->moov_recov_file_path);
2073 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2075 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2076 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2077 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2081 atom_ftyp_free (ftyp);
2083 gst_buffer_unref (prefix);
2085 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2086 GstCollectData *cdata = (GstCollectData *) walk->data;
2087 GstQTPad *qpad = (GstQTPad *) cdata;
2088 /* write info for each stream */
2089 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2091 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2099 fclose (qtmux->moov_recov_file);
2100 qtmux->moov_recov_file = NULL;
2103 static GstFlowReturn
2104 gst_qt_mux_start_file (GstQTMux * qtmux)
2106 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2107 GstFlowReturn ret = GST_FLOW_OK;
2111 GstClockTime reserved_max_duration;
2112 guint reserved_bytes_per_sec_per_trak;
2114 GST_DEBUG_OBJECT (qtmux, "starting file");
2116 GST_OBJECT_LOCK (qtmux);
2117 reserved_max_duration = qtmux->reserved_max_duration;
2118 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2119 GST_OBJECT_UNLOCK (qtmux);
2121 /* stream-start (FIXME: create id based on input ids) */
2122 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2123 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2125 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2126 /* qtmux has structure with and without variant, remove all but the first */
2127 while (gst_caps_get_size (caps) > 1)
2128 gst_caps_remove_structure (caps, 1);
2129 gst_pad_set_caps (qtmux->srcpad, caps);
2130 gst_caps_unref (caps);
2132 /* Default is 'normal' mode */
2133 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2135 /* Require a sensible fragment duration when muxing
2136 * using the ISML muxer */
2137 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2138 qtmux->fragment_duration == 0)
2141 if (qtmux->fragment_duration > 0) {
2142 if (qtmux->streamable)
2143 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2145 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2146 } else if (qtmux->fast_start) {
2147 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2148 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2149 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2152 switch (qtmux->mux_mode) {
2153 case GST_QT_MUX_MODE_MOOV_AT_END:
2154 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2155 /* We have to be able to seek to rewrite the mdat header, or any
2156 * moov atom we write will not be visible in the file, because an
2157 * MDAT with 0 as the size covers the rest of the file. A file
2158 * with no moov is not playable, so error out now. */
2159 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2160 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2161 ("Downstream is not seekable - will not be able to create a playable file"),
2163 return GST_FLOW_ERROR;
2166 case GST_QT_MUX_MODE_FAST_START:
2167 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2168 break; /* Don't need seekability, ignore */
2169 case GST_QT_MUX_MODE_FRAGMENTED:
2170 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2171 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2172 "streamable=false. Will ignore that and create streamable output "
2174 qtmux->streamable = TRUE;
2175 g_object_notify (G_OBJECT (qtmux), "streamable");
2180 /* let downstream know we think in BYTES and expect to do seeking later on */
2181 gst_segment_init (&segment, GST_FORMAT_BYTES);
2182 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2184 GST_OBJECT_LOCK (qtmux);
2186 if (qtmux->timescale == 0) {
2187 guint32 suggested_timescale = 0;
2190 /* Calculate a reasonable timescale for the moov:
2191 * If there is video, it is the biggest video track timescale or an even
2192 * multiple of it if it's smaller than 1800.
2193 * Otherwise it is 1800 */
2194 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2195 GstCollectData *cdata = (GstCollectData *) walk->data;
2196 GstQTPad *qpad = (GstQTPad *) cdata;
2202 if (!qpad->trak->mdia.minf.vmhd)
2205 suggested_timescale =
2206 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
2209 if (suggested_timescale == 0)
2210 suggested_timescale = 1800;
2212 while (suggested_timescale < 1800)
2213 suggested_timescale *= 2;
2215 qtmux->timescale = suggested_timescale;
2218 /* initialize our moov recovery file */
2219 if (qtmux->moov_recov_file_path) {
2220 gst_qt_mux_prepare_moov_recovery (qtmux);
2223 /* Make sure the first time we update the moov, we'll
2224 * include any tagsetter tags */
2225 qtmux->tags_changed = TRUE;
2227 GST_OBJECT_UNLOCK (qtmux);
2230 * send mdat header if already needed, and mark position for later update.
2231 * We don't send ftyp now if we are on fast start mode, because we can
2232 * better fine tune using the information we gather to create the whole moov
2235 switch (qtmux->mux_mode) {
2236 case GST_QT_MUX_MODE_MOOV_AT_END:
2237 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2238 if (ret != GST_FLOW_OK)
2241 /* Store this as the mdat offset for later updating
2242 * when we write the moov */
2243 qtmux->mdat_pos = qtmux->header_size;
2244 /* extended atom in case we go over 4GB while writing and need
2245 * the full 64-bit atom */
2247 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2250 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2252 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2253 if (ret != GST_FLOW_OK)
2256 /* Pad ftyp out to an 8-byte boundary before starting the moov
2257 * ping pong region. It should be well less than 1 disk sector,
2258 * unless there's a bajillion compatible types listed,
2259 * but let's be sure the free atom doesn't cross a sector
2260 * boundary anyway */
2261 if (qtmux->header_size % 8) {
2262 /* Extra 8 bytes for the padding free atom header */
2263 guint padding = (guint) (16 - (qtmux->header_size % 8));
2264 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2266 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2268 if (ret != GST_FLOW_OK)
2272 /* Store this as the moov offset for later updating.
2273 * We record mdat position below */
2274 qtmux->moov_pos = qtmux->header_size;
2276 /* Set up the initial 'ping' state of the ping-pong buffers */
2277 qtmux->reserved_moov_first_active = TRUE;
2279 gst_qt_mux_configure_moov (qtmux);
2280 gst_qt_mux_setup_metadata (qtmux);
2281 /* Empty free atom to begin, starting on an 8-byte boundary */
2282 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2283 if (ret != GST_FLOW_OK)
2285 /* Moov header, not padded yet */
2286 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2287 if (ret != GST_FLOW_OK)
2289 /* The moov we just sent contains the 'base' size of the moov, before
2290 * we put in any time-dependent per-trak data. Use that to make
2291 * a good estimate of how much extra to reserve */
2292 /* Calculate how much space to reserve for our MOOV atom.
2293 * We actually reserve twice that, for ping-pong buffers */
2294 qtmux->base_moov_size = qtmux->last_moov_size;
2295 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2296 qtmux->base_moov_size);
2297 qtmux->reserved_moov_size = qtmux->base_moov_size +
2298 gst_util_uint64_scale (reserved_max_duration,
2299 reserved_bytes_per_sec_per_trak *
2300 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2302 /* Need space for at least 4 atom headers. More really, but
2303 * this as an absolute minimum */
2304 if (qtmux->reserved_moov_size < 4 * 8)
2305 goto reserved_moov_too_small;
2307 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2308 2 * qtmux->reserved_moov_size + 16);
2310 GST_OBJECT_LOCK (qtmux);
2311 qtmux->reserved_duration_remaining =
2312 gst_util_uint64_scale (qtmux->reserved_moov_size -
2313 qtmux->base_moov_size, GST_SECOND,
2314 reserved_bytes_per_sec_per_trak *
2315 atom_moov_get_trak_count (qtmux->moov));
2316 GST_OBJECT_UNLOCK (qtmux);
2318 /* Now that we know how much reserved space is targetted,
2319 * output a free atom to fill the extra reserved */
2320 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2321 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2322 if (ret != GST_FLOW_OK)
2325 /* Then a free atom containing 'pong' buffer, with an
2326 * extra 8 bytes to account for the free atom header itself */
2327 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2328 qtmux->reserved_moov_size + 8, FALSE);
2329 if (ret != GST_FLOW_OK)
2332 /* extra atoms go after the free/moov(s), before the mdat */
2334 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2335 if (ret != GST_FLOW_OK)
2338 qtmux->mdat_pos = qtmux->header_size;
2339 /* extended atom in case we go over 4GB while writing and need
2340 * the full 64-bit atom */
2342 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2345 case GST_QT_MUX_MODE_FAST_START:
2346 GST_OBJECT_LOCK (qtmux);
2347 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2348 if (!qtmux->fast_start_file)
2350 GST_OBJECT_UNLOCK (qtmux);
2351 /* send a dummy buffer for preroll */
2352 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2354 case GST_QT_MUX_MODE_FRAGMENTED:
2355 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2356 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2357 if (ret != GST_FLOW_OK)
2359 /* store the moov pos so we can update the duration later
2360 * in non-streamable mode */
2361 qtmux->moov_pos = qtmux->header_size;
2363 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2364 qtmux->fragment_duration);
2365 /* also used as snapshot marker to indicate fragmented file */
2366 qtmux->fragment_sequence = 1;
2367 /* prepare moov and/or tags */
2368 gst_qt_mux_configure_moov (qtmux);
2369 gst_qt_mux_setup_metadata (qtmux);
2370 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2371 if (ret != GST_FLOW_OK)
2375 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2376 if (ret != GST_FLOW_OK)
2378 /* prepare index if not streamable */
2379 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2380 qtmux->mfra = atom_mfra_new (qtmux->context);
2388 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2389 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2390 return GST_FLOW_ERROR;
2392 reserved_moov_too_small:
2394 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2395 ("Not enough reserved space for creating headers"), (NULL));
2396 return GST_FLOW_ERROR;
2400 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2401 (("Could not open temporary file \"%s\""),
2402 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2403 GST_OBJECT_UNLOCK (qtmux);
2404 return GST_FLOW_ERROR;
2408 static GstFlowReturn
2409 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2411 GstFlowReturn ret = GST_FLOW_OK;
2414 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2415 GstCollectData *cdata = (GstCollectData *) walk->data;
2416 GstQTPad *qtpad = (GstQTPad *) cdata;
2418 /* avoid add_buffer complaining if not negotiated
2419 * in which case no buffers either, so skipping */
2420 if (!qtpad->fourcc) {
2421 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2422 GST_PAD_NAME (qtpad->collect.pad));
2426 /* send last buffer; also flushes possibly queued buffers/ts */
2427 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
2428 GST_PAD_NAME (qtpad->collect.pad));
2429 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
2430 if (ret != GST_FLOW_OK) {
2431 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
2432 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
2433 gst_flow_get_name (ret));
2441 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
2445 /* for setting some subtitles fields */
2446 guint max_width = 0;
2447 guint max_height = 0;
2449 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
2451 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2452 GstCollectData *cdata = (GstCollectData *) walk->data;
2453 GstQTPad *qtpad = (GstQTPad *) cdata;
2455 if (!qtpad->fourcc) {
2456 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2457 GST_PAD_NAME (qtpad->collect.pad));
2461 /* having flushed above, can check for buffers now */
2462 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2463 /* determine max stream duration */
2464 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
2465 || qtpad->last_dts > qtmux->last_dts) {
2466 qtmux->last_dts = qtpad->last_dts;
2468 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
2469 || qtpad->first_ts < qtmux->first_ts) {
2470 qtmux->first_ts = qtpad->first_ts;
2474 /* subtitles need to know the video width/height,
2475 * it is stored shifted 16 bits to the left according to the
2477 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
2478 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
2480 /* update average bitrate of streams if needed */
2482 guint32 avgbitrate = 0;
2483 guint32 maxbitrate = qtpad->max_bitrate;
2485 if (qtpad->avg_bitrate)
2486 avgbitrate = qtpad->avg_bitrate;
2487 else if (qtpad->total_duration > 0)
2488 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
2489 8 * GST_SECOND, qtpad->total_duration);
2491 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
2495 /* need to update values on subtitle traks now that we know the
2496 * max width and height */
2497 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2498 GstCollectData *cdata = (GstCollectData *) walk->data;
2499 GstQTPad *qtpad = (GstQTPad *) cdata;
2501 if (!qtpad->fourcc) {
2502 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2503 GST_PAD_NAME (qtpad->collect.pad));
2507 if (qtpad->fourcc == FOURCC_tx3g) {
2508 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
2513 /* Called after gst_qt_mux_update_global_statistics() updates the
2514 * first_ts tracking, to create/set edit lists for delayed streams */
2516 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
2520 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
2521 GST_TIME_ARGS (qtmux->first_ts));
2522 /* add/update EDTSs for late streams. configure_moov will have
2523 * set the trak durations above by summing the sample tables,
2524 * here we extend that if needing to insert an empty segment */
2525 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2526 GstCollectData *cdata = (GstCollectData *) walk->data;
2527 GstQTPad *qtpad = (GstQTPad *) cdata;
2529 atom_trak_edts_clear (qtpad->trak);
2531 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2532 guint32 lateness = 0;
2533 guint32 duration = qtpad->trak->tkhd.duration;
2536 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
2541 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
2542 lateness = gst_util_uint64_scale_round (diff,
2543 qtmux->timescale, GST_SECOND);
2546 GST_DEBUG_OBJECT (qtmux,
2547 "Pad %s is a late stream by %" GST_TIME_FORMAT,
2548 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (lateness));
2550 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
2551 (guint32) (1 * 65536.0));
2555 /* Always write an edit list for the whole track. In general this is not
2556 * necessary except for the case of having a gap or DTS adjustment but
2557 * it allows to give the whole track's duration in the usually more
2558 * accurate media timescale
2561 GstClockTime ctts = 0;
2562 guint32 media_start;
2564 if (qtpad->first_ts > qtpad->first_dts)
2565 ctts = qtpad->first_ts - qtpad->first_dts;
2567 media_start = gst_util_uint64_scale_round (ctts,
2568 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
2570 /* atom_trak_set_elst_entry() has a quirk - if the edit list
2571 * is empty because there's no gap added above, this call
2572 * will not replace index 1, it will create the entry at index 0.
2573 * Luckily, that's exactly what we want here */
2574 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
2575 (guint32) (1 * 65536.0));
2578 /* need to add the empty time to the trak duration */
2579 duration += lateness;
2580 qtpad->trak->tkhd.duration = duration;
2581 if (qtpad->tc_trak) {
2582 qtpad->tc_trak->tkhd.duration = duration;
2583 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
2586 /* And possibly grow the moov duration */
2587 if (duration > qtmux->moov->mvhd.time_info.duration) {
2588 qtmux->moov->mvhd.time_info.duration = duration;
2589 qtmux->moov->mvex.mehd.fragment_duration = duration;
2595 static GstFlowReturn
2596 gst_qt_mux_update_timecode (GstQTMux * qtmux)
2601 guint64 offset = qtmux->tc_pos;
2603 g_assert (qtmux->tc_pos != -1);
2605 gst_segment_init (&segment, GST_FORMAT_BYTES);
2606 segment.start = offset;
2607 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2609 buf = gst_buffer_new_and_alloc (4);
2610 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2612 GST_WRITE_UINT32_BE (map.data,
2613 gst_video_time_code_frames_since_daily_jam (qtmux->first_tc));
2614 gst_buffer_unmap (buf, &map);
2616 /* Reset this value, so the timecode won't be re-rewritten */
2619 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
2622 static GstFlowReturn
2623 gst_qt_mux_stop_file (GstQTMux * qtmux)
2625 gboolean ret = GST_FLOW_OK;
2626 guint64 offset = 0, size = 0;
2627 gboolean large_file;
2629 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
2631 /* pushing last buffers for each pad */
2632 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
2635 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2636 /* Streamable mode; no need to write duration or MFRA */
2637 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
2641 gst_qt_mux_update_global_statistics (qtmux);
2642 if (qtmux->tc_pos != -1) {
2643 /* File is being stopped and timecode hasn't been updated. Update it now
2644 * with whatever we have */
2645 ret = gst_qt_mux_update_timecode (qtmux);
2646 if (ret != GST_FLOW_OK)
2650 switch (qtmux->mux_mode) {
2651 case GST_QT_MUX_MODE_FRAGMENTED:{
2653 guint8 *data = NULL;
2657 GST_DEBUG_OBJECT (qtmux, "adding mfra");
2658 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
2659 goto serialize_error;
2660 buf = _gst_buffer_new_take_data (data, offset);
2661 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
2662 if (ret != GST_FLOW_OK)
2665 /* only mvex duration is updated,
2666 * mvhd should be consistent with empty moov
2667 * (but TODO maybe some clients do not handle that well ?) */
2668 qtmux->moov->mvex.mehd.fragment_duration =
2669 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
2670 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
2671 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
2672 /* seek and rewrite the header */
2673 gst_segment_init (&segment, GST_FORMAT_BYTES);
2674 segment.start = qtmux->moov_pos;
2675 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2676 /* no need to seek back */
2677 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2679 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
2680 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
2681 if (G_UNLIKELY (ret != GST_FLOW_OK))
2683 /* Finalise by writing the final size into the mdat. Up until now
2684 * it's been 0, which means 'rest of the file'
2685 * No need to seek back after this, we won't write any more */
2686 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2687 qtmux->mdat_size, NULL, TRUE);
2693 /* Moov-at-end or fast-start mode from here down */
2694 gst_qt_mux_configure_moov (qtmux);
2696 gst_qt_mux_update_edit_lists (qtmux);
2698 /* tags into file metadata */
2699 gst_qt_mux_setup_metadata (qtmux);
2701 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
2703 switch (qtmux->mux_mode) {
2704 case GST_QT_MUX_MODE_FAST_START:{
2705 /* if faststart, update the offset of the atoms in the movie with the offset
2706 * that the movie headers before mdat will cause.
2707 * Also, send the ftyp */
2710 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2711 if (ret != GST_FLOW_OK) {
2714 /* copy into NULL to obtain size */
2715 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
2716 goto serialize_error;
2717 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
2719 offset += qtmux->header_size + (large_file ? 16 : 8);
2721 /* sum up with the extra atoms size */
2722 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
2723 if (ret != GST_FLOW_OK)
2728 offset = qtmux->header_size;
2732 /* Now that we know the size of moov + extra atoms, we can adjust
2733 * the chunk offsets stored into the moov */
2734 atom_moov_chunks_set_offset (qtmux->moov, offset);
2736 /* write out moov and extra atoms */
2737 /* note: as of this point, we no longer care about tracking written data size,
2738 * since there is no more use for it anyway */
2739 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2740 if (ret != GST_FLOW_OK)
2744 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
2745 if (ret != GST_FLOW_OK)
2748 switch (qtmux->mux_mode) {
2749 case GST_QT_MUX_MODE_MOOV_AT_END:
2751 /* mdat needs update iff not using faststart */
2752 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
2753 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2754 qtmux->mdat_size, NULL, FALSE);
2755 /* note; no seeking back to the end of file is done,
2756 * since we no longer write anything anyway */
2759 case GST_QT_MUX_MODE_FAST_START:
2761 /* send mdat atom and move buffered data into it */
2762 /* mdat_size = accumulated (buffered data) */
2763 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
2765 if (ret != GST_FLOW_OK)
2767 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
2768 if (ret != GST_FLOW_OK)
2773 g_assert_not_reached ();
2781 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2782 ("Failed to serialize moov"));
2783 return GST_FLOW_ERROR;
2787 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
2788 return GST_FLOW_ERROR;
2792 static GstFlowReturn
2793 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2794 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2795 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2797 GstFlowReturn ret = GST_FLOW_OK;
2799 /* setup if needed */
2800 if (G_UNLIKELY (!pad->traf || force))
2804 /* flush pad fragment if threshold reached,
2805 * or at new keyframe if we should be minding those in the first place */
2806 if (G_UNLIKELY (force || (sync && pad->sync) ||
2807 pad->fragment_duration < (gint64) delta)) {
2809 guint64 size = 0, offset = 0;
2810 guint8 *data = NULL;
2812 guint i, total_size;
2814 /* now we know where moof ends up, update offset in tfra */
2816 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2818 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2819 /* takes ownership */
2820 atom_moof_add_traf (moof, pad->traf);
2822 atom_moof_copy_data (moof, &data, &size, &offset);
2823 buffer = _gst_buffer_new_take_data (data, offset);
2824 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2825 gst_buffer_get_size (buffer));
2826 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2828 /* and actual data */
2830 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2832 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2835 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2836 atom_array_get_len (&pad->fragment_buffers), total_size);
2837 if (ret == GST_FLOW_OK)
2838 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2840 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2841 if (G_LIKELY (ret == GST_FLOW_OK))
2842 ret = gst_qt_mux_send_buffer (qtmux,
2843 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2846 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2849 atom_array_clear (&pad->fragment_buffers);
2850 atom_moof_free (moof);
2851 qtmux->fragment_sequence++;
2856 if (G_UNLIKELY (!pad->traf)) {
2857 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2858 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2859 atom_array_init (&pad->fragment_buffers, 512);
2860 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2861 atom_trak_get_timescale (pad->trak), 1000);
2863 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2864 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2865 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2867 atom_traf_set_base_decode_time (pad->traf, dts);
2870 /* add buffer and metadata */
2871 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2873 atom_array_append (&pad->fragment_buffers, buf, 256);
2874 pad->fragment_duration -= delta;
2877 guint32 sn = atom_traf_get_sample_num (pad->traf);
2879 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2880 atom_tfra_add_entry (pad->tfra, dts, sn);
2883 if (G_UNLIKELY (force))
2889 /* Here's the clever bit of robust recording: Updating the moov
2890 * header is done using a ping-pong scheme inside 2 blocks of size
2891 * 'reserved_moov_size' at the start of the file, in such a way that the
2892 * file on-disk is always valid if interrupted.
2893 * Inside the reserved space, we have 2 pairs of free + moov atoms
2894 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
2895 * at offset "reserved_moov_size".
2897 * 1. Free-A has 0 size payload, moov-A immediately after is
2898 * active/current, and is padded with an internal Free atom to
2899 * end at reserved_space/2. Free-B is at reserved_space/2, sized
2900 * to cover the remaining free space (including moov-B).
2901 * 2. We write moov-B (which is invisible inside free-B), and pad it to
2902 * end at the end of free space. Then, we update free-A to size
2903 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
2904 * free-B header, and makes moov-B active.
2905 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
2906 * Change the size of free-A to make moov-A active again.
2907 * 4. Rinse and repeat.
2910 static GstFlowReturn
2911 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
2915 guint64 freeA_offset;
2916 guint32 new_freeA_size;
2917 guint64 new_moov_offset;
2919 /* Update moov info, then seek and rewrite the MOOV atom */
2920 gst_qt_mux_update_global_statistics (qtmux);
2921 gst_qt_mux_configure_moov (qtmux);
2923 gst_qt_mux_update_edit_lists (qtmux);
2925 /* tags into file metadata */
2926 gst_qt_mux_setup_metadata (qtmux);
2928 /* chunks position is set relative to the first byte of the
2929 * MDAT atom payload. Set the overall offset into the file */
2930 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
2932 /* Calculate which moov to rewrite. qtmux->moov_pos points to
2933 * the start of the free-A header */
2934 freeA_offset = qtmux->moov_pos;
2935 if (qtmux->reserved_moov_first_active) {
2936 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
2937 /* After this, freeA will include itself, moovA, plus the freeB
2939 new_freeA_size = qtmux->reserved_moov_size + 16;
2941 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
2944 /* the moov we update is after free-A, calculate its offset */
2945 new_moov_offset = freeA_offset + new_freeA_size;
2947 /* Swap ping-pong cadence marker */
2948 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
2950 /* seek and rewrite the MOOV atom */
2951 gst_segment_init (&segment, GST_FORMAT_BYTES);
2952 segment.start = new_moov_offset;
2953 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2956 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
2958 if (ret != GST_FLOW_OK)
2961 /* Update the estimated recording space remaining, based on amount used so
2962 * far and duration muxed so far */
2963 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
2964 GstClockTime remain;
2965 GstClockTime time_muxed = qtmux->last_dts;
2968 gst_util_uint64_scale (qtmux->reserved_moov_size -
2969 qtmux->last_moov_size, time_muxed,
2970 qtmux->last_moov_size - qtmux->base_moov_size);
2971 /* Always under-estimate slightly, so users
2972 * have time to stop muxing before we run out */
2973 if (remain < GST_SECOND / 2)
2976 remain -= GST_SECOND / 2;
2978 GST_INFO_OBJECT (qtmux,
2979 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
2980 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
2981 qtmux->reserved_moov_size, qtmux->last_moov_size,
2982 GST_TIME_ARGS (qtmux->last_dts),
2983 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
2985 GST_OBJECT_LOCK (qtmux);
2986 qtmux->reserved_duration_remaining = remain;
2987 qtmux->muxed_since_last_update = 0;
2988 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
2989 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
2990 GST_OBJECT_UNLOCK (qtmux);
2994 /* Now update the moov-A size. Don't pass offset, since we don't need
2995 * send_free_atom() to seek for us - all our callers seek back to
2996 * where they need after this, or they don't need it */
2997 gst_segment_init (&segment, GST_FORMAT_BYTES);
2998 segment.start = freeA_offset;
2999 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3001 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3006 static GstFlowReturn
3007 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3010 GstFlowReturn flow_ret;
3012 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3014 GST_OBJECT_LOCK (qtmux);
3015 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3016 GST_OBJECT_UNLOCK (qtmux);
3020 /* Update if position is > the threshold or there's been no update yet */
3021 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3022 (position <= qtmux->last_moov_update ||
3023 (position - qtmux->last_moov_update) <
3024 qtmux->reserved_moov_update_period)) {
3025 /* Update the offset of how much we've muxed, so the
3026 * report of remaining space keeps counting down */
3027 if (position > qtmux->last_moov_update &&
3028 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3029 GST_LOG_OBJECT (qtmux,
3030 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3031 qtmux->muxed_since_last_update);
3032 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3034 GST_OBJECT_UNLOCK (qtmux);
3035 return GST_FLOW_OK; /* No update needed yet */
3038 qtmux->last_moov_update = position;
3039 GST_OBJECT_UNLOCK (qtmux);
3041 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3042 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3043 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3045 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3046 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3049 /* Seek back to previous position */
3050 gst_segment_init (&segment, GST_FORMAT_BYTES);
3051 segment.start = mdat_offset;
3052 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3057 static GstFlowReturn
3058 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3059 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3060 gint64 last_dts, gint64 scaled_duration, guint sample_size,
3061 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3063 GstFlowReturn ret = GST_FLOW_OK;
3065 /* note that a new chunk is started each time (not fancy but works) */
3066 if (qtmux->moov_recov_file) {
3067 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3068 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3069 do_pts, pts_offset)) {
3070 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3071 "recovery file, disabling recovery");
3072 fclose (qtmux->moov_recov_file);
3073 qtmux->moov_recov_file = NULL;
3077 switch (qtmux->mux_mode) {
3078 case GST_QT_MUX_MODE_MOOV_AT_END:
3079 case GST_QT_MUX_MODE_FAST_START:
3080 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3081 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3082 sample_size, chunk_offset, sync, pts_offset);
3083 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3084 /* Check if it's time to re-write the headers in robust-recording mode */
3085 if (ret == GST_FLOW_OK
3086 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3087 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3089 case GST_QT_MUX_MODE_FRAGMENTED:
3090 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3091 /* ensure that always sync samples are marked as such */
3092 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3093 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3094 sample_size, !pad->sync || sync, pts_offset);
3101 static GstFlowReturn
3102 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
3103 GstBuffer * buf, GstFlowReturn ret)
3105 if (buf != NULL && (pad->tc_trak == NULL || qtmux->tc_pos != -1)) {
3106 GstVideoTimeCodeMeta *tc_meta = gst_buffer_get_video_time_code_meta (buf);
3108 GstVideoTimeCode *tc = &tc_meta->tc;
3111 guint32 frames_since_daily_jam;
3113 /* This means we never got a timecode before */
3114 if (qtmux->first_tc == NULL) {
3115 #ifndef GST_DISABLE_GST_DEBUG
3116 gchar *tc_str = gst_video_time_code_to_string (tc);
3117 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
3120 g_assert (pad->tc_trak == NULL);
3121 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3122 qtmux->first_tc = gst_video_time_code_copy (tc);
3123 /* If frames are out of order, the frame we're currently getting might
3124 * not be the first one. Just write a 0 timecode for now and wait
3125 * until we receive a timecode that's lower than the current one */
3126 if (pad->is_out_of_order) {
3127 qtmux->first_pts = GST_BUFFER_PTS (buf);
3128 frames_since_daily_jam = 0;
3129 /* Position to rewrite */
3130 qtmux->tc_pos = qtmux->mdat_size;
3132 frames_since_daily_jam =
3133 gst_video_time_code_frames_since_daily_jam (qtmux->first_tc);
3134 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3136 /* Write the timecode trak now */
3137 pad->tc_trak = atom_trak_new (qtmux->context);
3138 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
3140 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
3141 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
3143 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
3146 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3147 g_assert (szret == 4);
3149 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE,
3151 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3152 } else if (pad->is_out_of_order) {
3153 /* Check for a lower timecode than the one stored */
3154 g_assert (pad->tc_trak != NULL);
3155 if (GST_BUFFER_DTS (buf) <= qtmux->first_pts) {
3156 if (gst_video_time_code_compare (tc, qtmux->first_tc) == -1) {
3157 gst_video_time_code_free (qtmux->first_tc);
3158 qtmux->first_tc = gst_video_time_code_copy (tc);
3161 guint64 bk_size = qtmux->mdat_size;
3163 /* If this frame's DTS is after the first PTS received, it means
3164 * we've already received the first frame to be presented. Otherwise
3165 * the decoder would need to go back in time */
3166 gst_qt_mux_update_timecode (qtmux);
3168 /* Reset writing position */
3169 gst_segment_init (&segment, GST_FORMAT_BYTES);
3170 segment.start = bk_size;
3171 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3180 * Here we push the buffer and update the tables in the track atoms
3182 static GstFlowReturn
3183 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
3185 GstBuffer *last_buf = NULL;
3186 GstClockTime duration;
3187 guint nsamples, sample_size;
3188 guint64 chunk_offset;
3189 gint64 last_dts, scaled_duration;
3190 gint64 pts_offset = 0;
3191 gboolean sync = FALSE;
3192 GstFlowReturn ret = GST_FLOW_OK;
3195 goto not_negotiated;
3197 /* if this pad has a prepare function, call it */
3198 if (pad->prepare_buf_func != NULL) {
3199 buf = pad->prepare_buf_func (pad, buf, qtmux);
3202 last_buf = pad->last_buf;
3204 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
3206 if (last_buf == NULL) {
3207 #ifndef GST_DISABLE_GST_DEBUG
3209 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
3210 "received NULL buffer, doing nothing",
3211 GST_PAD_NAME (pad->collect.pad));
3213 GST_LOG_OBJECT (qtmux,
3214 "Pad %s has no previous buffer stored, storing now",
3215 GST_PAD_NAME (pad->collect.pad));
3218 pad->last_buf = buf;
3221 gst_buffer_ref (last_buf);
3224 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
3227 /* if this is the first buffer, store the timestamp */
3228 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
3229 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3230 pad->first_ts = GST_BUFFER_PTS (last_buf);
3231 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3232 pad->first_ts = GST_BUFFER_DTS (last_buf);
3235 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3236 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
3237 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3238 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
3241 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
3242 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
3244 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
3245 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
3246 pad->first_ts = pad->first_dts = 0;
3248 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
3249 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
3250 GST_TIME_ARGS (pad->first_ts));
3253 if (last_buf && buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
3254 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
3255 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
3256 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
3257 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
3258 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
3259 buf = gst_buffer_make_writable (buf);
3260 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
3263 /* duration actually means time delta between samples, so we calculate
3264 * the duration based on the difference in DTS or PTS, falling back
3265 * to DURATION if the other two don't exist, such as with the last
3266 * sample before EOS. Or use 0 if nothing else is available */
3267 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
3268 duration = GST_BUFFER_DURATION (last_buf);
3272 if (last_buf && buf && GST_BUFFER_DTS_IS_VALID (buf)
3273 && GST_BUFFER_DTS_IS_VALID (last_buf))
3274 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
3275 else if (last_buf && buf && GST_BUFFER_PTS_IS_VALID (buf)
3276 && GST_BUFFER_PTS_IS_VALID (last_buf))
3277 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
3280 gst_buffer_replace (&pad->last_buf, buf);
3282 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
3283 GST_DEBUG_OBJECT (qtmux,
3284 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
3285 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
3286 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
3287 qtmux->current_chunk_size,
3288 GST_TIME_ARGS (qtmux->current_chunk_duration));
3289 qtmux->current_pad = pad;
3290 if (qtmux->current_chunk_offset == -1)
3291 qtmux->current_chunk_offset = qtmux->mdat_size;
3293 qtmux->current_chunk_offset += qtmux->current_chunk_size;
3294 qtmux->current_chunk_size = 0;
3295 qtmux->current_chunk_duration = 0;
3298 last_dts = gst_util_uint64_scale_round (pad->last_dts,
3299 atom_trak_get_timescale (pad->trak), GST_SECOND);
3301 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
3302 if (pad->sample_size && !qtmux->fragment_sequence) {
3303 /* Constant size packets: usually raw audio (with many samples per
3304 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
3306 sample_size = pad->sample_size;
3307 if (gst_buffer_get_size (last_buf) % sample_size != 0)
3308 goto fragmented_sample;
3309 /* note: qt raw audio storage warps it implicitly into a timewise
3310 * perfect stream, discarding buffer times */
3311 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
3312 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
3313 atom_trak_get_timescale (pad->trak), GST_SECOND);
3314 duration = GST_BUFFER_DURATION (last_buf);
3316 nsamples = gst_buffer_get_size (last_buf) / sample_size;
3318 gst_util_uint64_scale_round (nsamples, GST_SECOND,
3319 atom_trak_get_timescale (pad->trak));
3322 /* timescale = samplerate */
3323 scaled_duration = 1;
3324 pad->last_dts += duration * nsamples;
3327 sample_size = gst_buffer_get_size (last_buf);
3328 if ((buf && GST_BUFFER_DTS_IS_VALID (buf))
3329 || GST_BUFFER_DTS_IS_VALID (last_buf)) {
3331 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
3332 pad->last_dts = GST_BUFFER_DTS (buf);
3334 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
3336 if ((gint64) (pad->last_dts) < 0) {
3337 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
3338 atom_trak_get_timescale (pad->trak), GST_SECOND);
3340 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
3341 atom_trak_get_timescale (pad->trak), GST_SECOND);
3343 scaled_duration = scaled_dts - last_dts;
3344 last_dts = scaled_dts;
3346 /* first convert intended timestamp (in GstClockTime resolution) to
3347 * trak timescale, then derive delta;
3348 * this ensures sums of (scale)delta add up to converted timestamp,
3349 * which only deviates at most 1/scale from timestamp itself */
3350 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
3351 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
3352 pad->last_dts += duration;
3356 /* for computing the avg bitrate */
3357 if (G_LIKELY (last_buf)) {
3358 pad->total_bytes += gst_buffer_get_size (last_buf);
3359 pad->total_duration += duration;
3361 qtmux->current_chunk_size += gst_buffer_get_size (last_buf);
3362 qtmux->current_chunk_duration += duration;
3364 chunk_offset = qtmux->current_chunk_offset;
3366 GST_LOG_OBJECT (qtmux,
3367 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
3368 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
3369 GST_LOG_OBJECT (qtmux,
3370 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
3371 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
3372 nsamples, scaled_duration, sample_size, chunk_offset);
3374 /* might be a sync sample */
3376 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
3377 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
3378 GST_PAD_NAME (pad->collect.pad));
3382 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3383 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
3384 atom_trak_get_timescale (pad->trak), GST_SECOND);
3386 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3387 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
3390 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3391 atom_trak_get_timescale (pad->trak), GST_SECOND);
3393 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
3394 " timebase_dts: %d pts_offset: %d",
3395 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
3396 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
3397 (int) (last_dts), (int) (pts_offset));
3399 if (GST_CLOCK_TIME_IS_VALID (duration)
3400 && (qtmux->current_chunk_duration > qtmux->longest_chunk
3401 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
3402 GST_DEBUG_OBJECT (qtmux,
3403 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
3404 GST_TIME_ARGS (qtmux->current_chunk_duration),
3405 GST_PAD_NAME (pad->collect.pad));
3406 qtmux->longest_chunk = qtmux->current_chunk_duration;
3409 /* now we go and register this buffer/sample all over */
3410 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
3411 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
3412 chunk_offset, sync, TRUE, pts_offset);
3414 /* if this is sparse and we have a next buffer, check if there is any gap
3415 * between them to insert an empty sample */
3416 if (pad->sparse && buf) {
3417 if (pad->create_empty_buffer) {
3418 GstBuffer *empty_buf;
3419 gint64 empty_duration =
3420 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
3421 gint64 empty_duration_scaled;
3423 empty_buf = pad->create_empty_buffer (pad, empty_duration);
3425 empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
3426 atom_trak_get_timescale (pad->trak), GST_SECOND);
3428 pad->total_bytes += gst_buffer_get_size (empty_buf);
3429 pad->total_duration += duration;
3432 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
3433 last_dts + scaled_duration, empty_duration_scaled,
3434 gst_buffer_get_size (empty_buf), chunk_offset, sync, TRUE, 0);
3436 /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
3437 g_assert_not_reached ();
3438 GST_WARNING_OBJECT (qtmux,
3439 "no empty buffer creation function found for pad %s",
3440 GST_PAD_NAME (pad->collect.pad));
3445 gst_buffer_unref (buf);
3455 gst_buffer_unref (buf);
3456 gst_buffer_unref (last_buf);
3457 return GST_FLOW_ERROR;
3461 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3462 ("Audio buffer contains fragmented sample."));
3467 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
3472 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
3473 ("format wasn't negotiated before buffer flow on pad %s",
3474 GST_PAD_NAME (pad->collect.pad)));
3476 gst_buffer_unref (buf);
3477 return GST_FLOW_NOT_NEGOTIATED;
3482 * DTS running time can be negative. There is no way to represent that in
3483 * MP4 however, thus we need to offset DTS so that it starts from 0.
3486 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
3487 GstCollectData * cdata, GstBuffer ** buf)
3492 pts = GST_BUFFER_PTS (*buf);
3493 dts = GST_COLLECT_PADS_DTS (cdata);
3495 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
3496 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
3497 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
3499 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
3500 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
3501 pad->dts_adjustment = -dts;
3503 pad->dts_adjustment = 0;
3506 if (pad->dts_adjustment > 0) {
3507 *buf = gst_buffer_make_writable (*buf);
3509 dts += pad->dts_adjustment;
3511 if (GST_CLOCK_TIME_IS_VALID (pts))
3512 pts += pad->dts_adjustment;
3514 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
3515 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
3520 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
3524 GST_BUFFER_PTS (*buf) = pts;
3525 GST_BUFFER_DTS (*buf) = dts;
3527 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
3528 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
3533 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
3536 GstQTPad *best_pad = NULL;
3538 if (qtmux->current_pad &&
3539 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
3540 (qtmux->interleave_bytes == 0
3541 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
3542 && (qtmux->interleave_time == 0
3543 || qtmux->current_chunk_duration <= qtmux->interleave_time)
3544 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
3545 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3546 GstBuffer *tmp_buf =
3547 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
3549 if (tmp_buf || qtmux->current_pad->last_buf) {
3550 best_pad = qtmux->current_pad;
3552 gst_buffer_unref (tmp_buf);
3553 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
3554 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
3556 } else if (qtmux->collect->data->next) {
3557 /* Only switch pads if we have more than one, otherwise
3558 * we can just put everything into a single chunk and save
3559 * a few bytes of offsets
3561 if (qtmux->current_pad)
3562 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
3563 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
3564 best_pad = qtmux->current_pad = NULL;
3568 GstClockTime best_time = GST_CLOCK_TIME_NONE;
3570 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3571 GstCollectData *cdata = (GstCollectData *) walk->data;
3572 GstQTPad *qtpad = (GstQTPad *) cdata;
3574 GstClockTime timestamp;
3576 tmp_buf = gst_collect_pads_peek (pads, cdata);
3578 /* This one is newly EOS now, finish it for real */
3579 if (qtpad->last_buf) {
3580 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
3585 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
3588 if (best_pad == NULL ||
3589 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
3591 best_time = timestamp;
3595 gst_buffer_unref (tmp_buf);
3599 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
3600 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
3602 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
3609 static GstFlowReturn
3610 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
3612 GstFlowReturn ret = GST_FLOW_OK;
3613 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
3614 GstQTPad *best_pad = NULL;
3616 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
3617 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
3620 qtmux->state = GST_QT_MUX_STATE_DATA;
3623 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
3624 return GST_FLOW_EOS;
3626 best_pad = find_best_pad (qtmux, pads);
3628 /* clipping already converted to running time */
3629 if (best_pad != NULL) {
3630 GstBuffer *buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
3632 g_assert (buf || best_pad->last_buf);
3634 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
3635 (GstCollectData *) best_pad, &buf);
3637 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
3639 qtmux->state = GST_QT_MUX_STATE_EOS;
3640 ret = gst_qt_mux_stop_file (qtmux);
3641 if (ret == GST_FLOW_OK) {
3642 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
3643 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
3646 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
3647 gst_flow_get_name (ret));
3655 check_field (GQuark field_id, const GValue * value, gpointer user_data)
3657 GstStructure *structure = (GstStructure *) user_data;
3658 const GValue *other = gst_structure_id_get_value (structure, field_id);
3661 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
3665 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
3668 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
3669 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
3671 return gst_structure_foreach (sub_s, check_field, sup_s);
3675 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3677 GstPad *pad = qtpad->collect.pad;
3678 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3679 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3680 GstStructure *structure;
3681 const gchar *mimetype;
3682 gint rate, channels;
3683 const GValue *value = NULL;
3684 const GstBuffer *codec_data = NULL;
3685 GstQTMuxFormat format;
3686 AudioSampleEntry entry = { 0, };
3687 AtomInfo *ext_atom = NULL;
3688 gint constant_size = 0;
3689 const gchar *stream_format;
3691 qtpad->prepare_buf_func = NULL;
3693 /* does not go well to renegotiate stream mid-way, unless
3694 * the old caps are a subset of the new one (this means upstream
3695 * added more info to the caps, as both should be 'fixed' caps) */
3696 if (qtpad->fourcc) {
3697 GstCaps *current_caps;
3699 current_caps = gst_pad_get_current_caps (pad);
3700 g_assert (caps != NULL);
3702 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3703 gst_caps_unref (current_caps);
3704 goto refuse_renegotiation;
3706 GST_DEBUG_OBJECT (qtmux,
3707 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
3708 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
3709 gst_caps_unref (current_caps);
3712 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
3713 GST_DEBUG_PAD_NAME (pad), caps);
3715 format = qtmux_klass->format;
3716 structure = gst_caps_get_structure (caps, 0);
3717 mimetype = gst_structure_get_name (structure);
3720 if (!gst_structure_get_int (structure, "channels", &channels) ||
3721 !gst_structure_get_int (structure, "rate", &rate)) {
3726 value = gst_structure_get_value (structure, "codec_data");
3728 codec_data = gst_value_get_buffer (value);
3730 qtpad->is_out_of_order = FALSE;
3732 /* set common properties */
3733 entry.sample_rate = rate;
3734 entry.channels = channels;
3736 entry.sample_size = 16;
3737 /* this is the typical compressed case */
3738 if (format == GST_QT_MUX_FORMAT_QT) {
3740 entry.compression_id = -2;
3743 /* now map onto a fourcc, and some extra properties */
3744 if (strcmp (mimetype, "audio/mpeg") == 0) {
3745 gint mpegversion = 0, mpegaudioversion = 0;
3748 gst_structure_get_int (structure, "mpegversion", &mpegversion);
3749 switch (mpegversion) {
3751 gst_structure_get_int (structure, "layer", &layer);
3752 gst_structure_get_int (structure, "mpegaudioversion",
3756 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
3757 if (format == GST_QT_MUX_FORMAT_QT)
3758 entry.fourcc = FOURCC__mp3;
3760 entry.fourcc = FOURCC_mp4a;
3762 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
3763 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3764 qtpad->max_bitrate);
3767 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3768 entry.samples_per_packet = 384;
3769 } else if (layer == 2) {
3770 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3771 entry.samples_per_packet = 1152;
3773 g_warn_if_fail (layer == 3);
3774 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
3776 entry.bytes_per_sample = 2;
3780 /* check stream-format */
3781 stream_format = gst_structure_get_string (structure, "stream-format");
3782 if (stream_format) {
3783 if (strcmp (stream_format, "raw") != 0) {
3784 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
3785 "please use 'raw'", stream_format);
3789 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
3793 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
3794 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
3799 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
3800 /* warn if not Low Complexity profile */
3803 GST_WARNING_OBJECT (qtmux,
3804 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
3808 entry.fourcc = FOURCC_mp4a;
3810 if (format == GST_QT_MUX_FORMAT_QT)
3811 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
3812 qtpad->avg_bitrate, qtpad->max_bitrate);
3815 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
3816 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3817 qtpad->max_bitrate);
3822 } else if (strcmp (mimetype, "audio/AMR") == 0) {
3823 entry.fourcc = FOURCC_samr;
3824 entry.sample_size = 16;
3825 entry.samples_per_packet = 160;
3826 entry.bytes_per_sample = 2;
3827 ext_atom = build_amr_extension ();
3828 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
3829 entry.fourcc = FOURCC_sawb;
3830 entry.sample_size = 16;
3831 entry.samples_per_packet = 320;
3832 entry.bytes_per_sample = 2;
3833 ext_atom = build_amr_extension ();
3834 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
3837 gst_audio_info_init (&info);
3838 if (!gst_audio_info_from_caps (&info, caps))
3841 /* spec has no place for a distinction in these */
3842 if (info.finfo->width != info.finfo->depth) {
3843 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
3847 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
3848 if (info.finfo->endianness == G_LITTLE_ENDIAN)
3849 entry.fourcc = FOURCC_sowt;
3850 else if (info.finfo->endianness == G_BIG_ENDIAN)
3851 entry.fourcc = FOURCC_twos;
3853 entry.fourcc = FOURCC_sowt;
3854 /* maximum backward compatibility; only new version for > 16 bit */
3855 if (info.finfo->depth <= 16)
3857 /* not compressed in any case */
3858 entry.compression_id = 0;
3859 /* QT spec says: max at 16 bit even if sample size were actually larger,
3860 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
3861 entry.sample_size = info.finfo->depth;
3862 entry.bytes_per_sample = info.finfo->depth / 8;
3863 entry.samples_per_packet = 1;
3864 entry.bytes_per_packet = info.finfo->depth / 8;
3865 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
3867 if (info.finfo->width == 8 && info.finfo->depth == 8) {
3868 /* fall back to old 8-bit version */
3869 entry.fourcc = FOURCC_raw_;
3871 entry.compression_id = 0;
3872 entry.sample_size = 8;
3874 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
3878 constant_size = (info.finfo->depth / 8) * info.channels;
3879 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
3880 entry.fourcc = FOURCC_alaw;
3881 entry.samples_per_packet = 1023;
3882 entry.bytes_per_sample = 2;
3883 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
3884 entry.fourcc = FOURCC_ulaw;
3885 entry.samples_per_packet = 1023;
3886 entry.bytes_per_sample = 2;
3887 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
3889 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
3890 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
3893 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
3895 entry.fourcc = MS_WAVE_FOURCC (0x11);
3896 /* 4 byte header per channel (including one sample). 2 samples per byte
3897 remaining. Simplifying gives the following (samples per block per
3899 entry.samples_per_packet = 2 * blocksize / channels - 7;
3900 entry.bytes_per_sample = 2;
3902 entry.bytes_per_frame = blocksize;
3903 entry.bytes_per_packet = blocksize / channels;
3904 /* ADPCM has constant size packets */
3906 /* TODO: I don't really understand why this helps, but it does! Constant
3907 * size and compression_id of -2 seem to be incompatible, and other files
3908 * in the wild use this too. */
3909 entry.compression_id = -1;
3911 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
3912 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
3913 GstBuffer *codec_config;
3917 entry.fourcc = FOURCC_alac;
3918 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
3919 /* let's check if codec data already comes with 'alac' atom prefix */
3920 if (!codec_data || (len = map.size) < 28) {
3921 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
3922 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3925 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
3928 gst_buffer_copy_region ((GstBuffer *) codec_data,
3929 GST_BUFFER_COPY_MEMORY, 8, len);
3931 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
3933 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3935 /* does not look good, but perhaps some trailing unneeded stuff */
3936 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
3938 if (format == GST_QT_MUX_FORMAT_QT)
3939 ext_atom = build_mov_alac_extension (codec_config);
3941 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
3942 /* set some more info */
3943 gst_buffer_map (codec_config, &map, GST_MAP_READ);
3944 entry.bytes_per_sample = 2;
3945 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
3946 gst_buffer_unmap (codec_config, &map);
3947 gst_buffer_unref (codec_config);
3948 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
3949 entry.fourcc = FOURCC_ac_3;
3951 /* Fixed values according to TS 102 366 but it also mentions that
3952 * they should be ignored */
3954 entry.sample_size = 16;
3956 /* AC-3 needs an extension atom but its data can only be obtained from
3957 * the stream itself. Abuse the prepare_buf_func so we parse a frame
3958 * and get the needed data */
3959 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
3960 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
3961 /* Based on the specification defined in:
3962 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
3963 guint8 channels, mapping_family, stream_count, coupled_count;
3967 guint8 channel_mapping[256];
3968 const GValue *streamheader;
3969 const GValue *first_element;
3972 entry.fourcc = FOURCC_opus;
3973 entry.sample_size = 16;
3975 streamheader = gst_structure_get_value (structure, "streamheader");
3976 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
3977 gst_value_array_get_size (streamheader) != 0) {
3978 first_element = gst_value_array_get_value (streamheader, 0);
3979 header = gst_value_get_buffer (first_element);
3980 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
3981 &mapping_family, &stream_count, &coupled_count, channel_mapping,
3982 &pre_skip, &output_gain)) {
3983 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
3987 GST_WARNING_OBJECT (qtmux,
3988 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
3990 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
3991 &mapping_family, &stream_count, &coupled_count,
3993 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
4000 entry.channels = channels;
4001 ext_atom = build_opus_extension (rate, channels, mapping_family,
4002 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
4008 /* ok, set the pad info accordingly */
4009 qtpad->fourcc = entry.fourcc;
4010 qtpad->sample_size = constant_size;
4012 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
4013 qtmux->context, &entry,
4014 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
4015 ext_atom, constant_size);
4017 gst_object_unref (qtmux);
4023 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4024 GST_PAD_NAME (pad), caps);
4025 gst_object_unref (qtmux);
4028 refuse_renegotiation:
4030 GST_WARNING_OBJECT (qtmux,
4031 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
4032 GST_PAD_NAME (pad), caps);
4033 gst_object_unref (qtmux);
4038 /* return number of centiframes per second */
4040 adjust_rate (gint n, gint d)
4045 if (d != 1 && d != 1001) {
4046 /* otherwise there are probably rounding errors and we should rather guess
4047 * if it's close enough to a well known framerate */
4048 gst_video_guess_framerate (gst_util_uint64_scale (d, GST_SECOND, n), &n,
4052 return gst_util_uint64_scale (n, 100, d);
4056 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4058 GstPad *pad = qtpad->collect.pad;
4059 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4060 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4061 GstStructure *structure;
4062 const gchar *mimetype;
4063 gint width, height, depth = -1;
4064 gint framerate_num, framerate_den;
4066 const GValue *value = NULL;
4067 const GstBuffer *codec_data = NULL;
4068 VisualSampleEntry entry = { 0, };
4069 GstQTMuxFormat format;
4070 AtomInfo *ext_atom = NULL;
4071 GList *ext_atom_list = NULL;
4072 gboolean sync = FALSE;
4073 int par_num, par_den;
4075 qtpad->prepare_buf_func = NULL;
4077 /* does not go well to renegotiate stream mid-way, unless
4078 * the old caps are a subset of the new one (this means upstream
4079 * added more info to the caps, as both should be 'fixed' caps) */
4080 if (qtpad->fourcc) {
4081 GstCaps *current_caps;
4083 current_caps = gst_pad_get_current_caps (pad);
4084 g_assert (caps != NULL);
4086 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4087 gst_caps_unref (current_caps);
4088 goto refuse_renegotiation;
4090 GST_DEBUG_OBJECT (qtmux,
4091 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4092 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4093 gst_caps_unref (current_caps);
4096 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4097 GST_DEBUG_PAD_NAME (pad), caps);
4099 format = qtmux_klass->format;
4100 structure = gst_caps_get_structure (caps, 0);
4101 mimetype = gst_structure_get_name (structure);
4103 /* required parts */
4104 if (!gst_structure_get_int (structure, "width", &width) ||
4105 !gst_structure_get_int (structure, "height", &height))
4110 /* works as a default timebase */
4111 framerate_num = 10000;
4113 gst_structure_get_fraction (structure, "framerate", &framerate_num,
4115 gst_structure_get_int (structure, "depth", &depth);
4116 value = gst_structure_get_value (structure, "codec_data");
4118 codec_data = gst_value_get_buffer (value);
4122 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
4125 qtpad->is_out_of_order = FALSE;
4127 /* bring frame numerator into a range that ensures both reasonable resolution
4128 * as well as a fair duration */
4129 rate = qtmux->trak_timescale ?
4130 qtmux->trak_timescale : adjust_rate (framerate_num, framerate_den);
4131 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
4134 /* set common properties */
4135 entry.width = width;
4136 entry.height = height;
4137 entry.par_n = par_num;
4138 entry.par_d = par_den;
4139 /* should be OK according to qt and iso spec, override if really needed */
4140 entry.color_table_id = -1;
4141 entry.frame_count = 1;
4144 /* sync entries by default */
4147 /* now map onto a fourcc, and some extra properties */
4148 if (strcmp (mimetype, "video/x-raw") == 0) {
4149 const gchar *format;
4151 const GstVideoFormatInfo *vinfo;
4153 format = gst_structure_get_string (structure, "format");
4154 fmt = gst_video_format_from_string (format);
4155 vinfo = gst_video_format_get_info (fmt);
4158 case GST_VIDEO_FORMAT_UYVY:
4161 entry.fourcc = FOURCC_2vuy;
4162 entry.depth = depth;
4165 case GST_VIDEO_FORMAT_v210:
4168 entry.fourcc = FOURCC_v210;
4169 entry.depth = depth;
4173 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
4174 entry.fourcc = FOURCC_raw_;
4175 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
4180 } else if (strcmp (mimetype, "video/x-h263") == 0) {
4182 if (format == GST_QT_MUX_FORMAT_QT)
4183 entry.fourcc = FOURCC_h263;
4185 entry.fourcc = FOURCC_s263;
4186 ext_atom = build_h263_extension ();
4187 if (ext_atom != NULL)
4188 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4189 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
4190 strcmp (mimetype, "video/mpeg") == 0) {
4193 if (strcmp (mimetype, "video/x-divx") == 0) {
4194 gst_structure_get_int (structure, "divxversion", &version);
4195 version = version == 5 ? 1 : 0;
4197 gst_structure_get_int (structure, "mpegversion", &version);
4198 version = version == 4 ? 1 : 0;
4201 entry.fourcc = FOURCC_mp4v;
4203 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
4204 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
4205 qtpad->max_bitrate);
4206 if (ext_atom != NULL)
4207 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4209 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
4210 "output might not play in Apple QuickTime (try global-headers?)");
4212 } else if (strcmp (mimetype, "video/x-h264") == 0) {
4214 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
4218 entry.fourcc = FOURCC_avc1;
4220 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4221 if (ext_atom != NULL)
4222 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4223 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
4224 if (ext_atom != NULL)
4225 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4226 } else if (strcmp (mimetype, "video/x-h265") == 0) {
4227 const gchar *format;
4230 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
4234 format = gst_structure_get_string (structure, "stream-format");
4235 if (strcmp (format, "hvc1") == 0)
4236 entry.fourcc = FOURCC_hvc1;
4237 else if (strcmp (format, "hev1") == 0)
4238 entry.fourcc = FOURCC_hev1;
4240 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4241 if (ext_atom != NULL)
4242 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4244 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
4245 if (ext_atom != NULL)
4246 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4248 } else if (strcmp (mimetype, "video/x-svq") == 0) {
4250 const GstBuffer *seqh = NULL;
4251 const GValue *seqh_value;
4254 gst_structure_get_int (structure, "svqversion", &version);
4256 entry.fourcc = FOURCC_SVQ3;
4260 seqh_value = gst_structure_get_value (structure, "seqh");
4262 seqh = gst_value_get_buffer (seqh_value);
4263 ext_atom = build_SMI_atom (seqh);
4265 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4268 /* we need to add the gamma anyway because quicktime might crash
4269 * when it doesn't find it */
4270 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
4271 /* it seems that using 0 here makes it ignored */
4274 ext_atom = build_gama_atom (gamma);
4276 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4278 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
4279 "a bug at http://bugzilla.gnome.org", version);
4281 } else if (strcmp (mimetype, "video/x-dv") == 0) {
4283 gboolean pal = TRUE;
4286 if (framerate_num != 25 || framerate_den != 1)
4288 gst_structure_get_int (structure, "dvversion", &version);
4289 /* fall back to typical one */
4295 entry.fourcc = FOURCC_dvcp;
4297 entry.fourcc = FOURCC_dvc_;
4301 entry.fourcc = FOURCC_dv5p;
4303 entry.fourcc = FOURCC_dv5n;
4306 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
4309 } else if (strcmp (mimetype, "image/jpeg") == 0) {
4310 entry.fourcc = FOURCC_jpeg;
4312 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
4313 strcmp (mimetype, "image/x-jpc") == 0) {
4314 const gchar *colorspace;
4315 const GValue *cmap_array;
4316 const GValue *cdef_array;
4319 if (strcmp (mimetype, "image/x-jpc") == 0) {
4320 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
4323 gst_structure_get_int (structure, "num-components", &ncomp);
4324 cmap_array = gst_structure_get_value (structure, "component-map");
4325 cdef_array = gst_structure_get_value (structure, "channel-definitions");
4328 entry.fourcc = FOURCC_mjp2;
4331 colorspace = gst_structure_get_string (structure, "colorspace");
4334 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
4335 cdef_array)) != NULL) {
4336 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4338 ext_atom = build_jp2x_extension (codec_data);
4340 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4342 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
4345 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
4346 entry.fourcc = FOURCC_VP80;
4348 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
4349 entry.fourcc = FOURCC_drac;
4350 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
4353 gst_structure_get_uint (structure, "format", &fourcc);
4354 entry.fourcc = fourcc;
4355 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
4358 gst_structure_get_uint (structure, "format", &fourcc);
4359 entry.fourcc = fourcc;
4360 } else if (strcmp (mimetype, "video/x-prores") == 0) {
4361 const gchar *variant;
4363 variant = gst_structure_get_string (structure, "variant");
4364 if (!variant || !g_strcmp0 (variant, "standard"))
4365 entry.fourcc = FOURCC_apcn;
4366 else if (!g_strcmp0 (variant, "lt"))
4367 entry.fourcc = FOURCC_apcs;
4368 else if (!g_strcmp0 (variant, "hq"))
4369 entry.fourcc = FOURCC_apch;
4370 else if (!g_strcmp0 (variant, "proxy"))
4371 entry.fourcc = FOURCC_apco;
4372 else if (!g_strcmp0 (variant, "4444"))
4373 entry.fourcc = FOURCC_ap4h;
4374 else if (!g_strcmp0 (variant, "4444xq"))
4375 entry.fourcc = FOURCC_ap4x;
4379 if (!qtmux->interleave_time_set)
4380 qtmux->interleave_time = 500 * GST_MSECOND;
4381 if (!qtmux->interleave_bytes_set)
4382 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
4388 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
4389 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
4391 GstVideoColorimetry colorimetry;
4393 s = gst_structure_get_string (structure, "colorimetry");
4394 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
4396 build_colr_extension (&colorimetry,
4397 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
4399 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4403 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
4404 || strcmp (mimetype, "image/x-j2c") == 0
4405 || strcmp (mimetype, "image/x-jpc") == 0) {
4407 GstVideoInterlaceMode interlace_mode;
4408 GstVideoFieldOrder field_order;
4411 if (strcmp (mimetype, "image/x-j2c") == 0 ||
4412 strcmp (mimetype, "image/x-jpc") == 0) {
4415 gst_structure_get_int (structure, "fields", &fields);
4418 s = gst_structure_get_string (structure, "interlace-mode");
4420 interlace_mode = gst_video_interlace_mode_from_string (s);
4424 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
4425 GST_VIDEO_INTERLACE_MODE_MIXED;
4427 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
4428 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
4429 s = gst_structure_get_string (structure, "field-order");
4431 field_order = gst_video_field_order_from_string (s);
4434 ext_atom = build_fiel_extension (interlace_mode, field_order);
4436 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4440 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
4441 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
4442 /* The 'clap' extension is also defined for MP4 but inventing values in
4443 * general seems a bit tricky for this one. We only write it for
4444 * SD resolution in MOV, where it is a requirement.
4445 * The same goes for the 'tapt' extension, just that it is not defined for
4446 * MP4 and only for MOV
4448 gint dar_num, dar_den;
4449 gint clef_width, clef_height, prof_width;
4450 gint clap_width_n, clap_width_d, clap_height;
4454 /* First, guess display aspect ratio based on pixel aspect ratio,
4455 * width and height. We assume that display aspect ratio is either
4458 approx_dar = (gdouble) (width * par_num) / (height * par_den);
4459 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
4462 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
4466 dar_num = width * par_num;
4467 dar_den = height * par_den;
4468 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
4473 /* Then, calculate clean-aperture values (clap and clef)
4474 * using the guessed DAR.
4476 clef_height = clap_height = (height == 486 ? 480 : height);
4477 clef_width = gst_util_uint64_scale (clef_height,
4478 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
4479 prof_width = gst_util_uint64_scale (width,
4480 par_num * G_GUINT64_CONSTANT (65536), par_den);
4481 clap_width_n = clap_height * dar_num * par_den;
4482 clap_width_d = dar_den * par_num;
4483 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
4484 clap_width_n /= cdiv;
4485 clap_width_d /= cdiv;
4487 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
4488 height << 16, width << 16, height << 16);
4489 qtpad->trak->tapt = ext_atom;
4491 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
4492 clap_height, 1, 0, 1, 0, 1);
4494 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4497 /* ok, set the pad info accordingly */
4498 qtpad->fourcc = entry.fourcc;
4501 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
4502 qtmux->context, &entry, rate, ext_atom_list);
4503 if (strcmp (mimetype, "video/x-prores") == 0) {
4504 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
4505 const gchar *compressor = NULL;
4506 mp4v->spatial_quality = 0x3FF;
4507 mp4v->temporal_quality = 0;
4508 mp4v->vendor = FOURCC_appl;
4509 mp4v->horizontal_resolution = 72 << 16;
4510 mp4v->vertical_resolution = 72 << 16;
4511 mp4v->depth = (entry.fourcc == FOURCC_ap4h
4512 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
4514 /* Set compressor name, required by some software */
4515 switch (entry.fourcc) {
4517 compressor = "Apple ProRes 422";
4520 compressor = "Apple ProRes 422 LT";
4523 compressor = "Apple ProRes 422 HQ";
4526 compressor = "Apple ProRes 422 Proxy";
4529 compressor = "Apple ProRes 4444";
4532 compressor = "Apple ProRes 4444 XQ";
4536 strcpy ((gchar *) mp4v->compressor + 1, compressor);
4537 mp4v->compressor[0] = strlen (compressor);
4541 gst_object_unref (qtmux);
4547 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4548 GST_PAD_NAME (pad), caps);
4549 gst_object_unref (qtmux);
4552 refuse_renegotiation:
4554 GST_WARNING_OBJECT (qtmux,
4555 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4557 gst_object_unref (qtmux);
4563 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4565 GstPad *pad = qtpad->collect.pad;
4566 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4567 GstStructure *structure;
4568 SubtitleSampleEntry entry = { 0, };
4570 /* does not go well to renegotiate stream mid-way, unless
4571 * the old caps are a subset of the new one (this means upstream
4572 * added more info to the caps, as both should be 'fixed' caps) */
4573 if (qtpad->fourcc) {
4574 GstCaps *current_caps;
4576 current_caps = gst_pad_get_current_caps (pad);
4577 g_assert (caps != NULL);
4579 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4580 gst_caps_unref (current_caps);
4581 goto refuse_renegotiation;
4583 GST_DEBUG_OBJECT (qtmux,
4584 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4585 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4586 gst_caps_unref (current_caps);
4589 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4590 GST_DEBUG_PAD_NAME (pad), caps);
4592 /* subtitles default */
4593 subtitle_sample_entry_init (&entry);
4594 qtpad->is_out_of_order = FALSE;
4595 qtpad->sync = FALSE;
4596 qtpad->sparse = TRUE;
4597 qtpad->prepare_buf_func = NULL;
4599 structure = gst_caps_get_structure (caps, 0);
4601 if (gst_structure_has_name (structure, "text/x-raw")) {
4602 const gchar *format = gst_structure_get_string (structure, "format");
4603 if (format && strcmp (format, "utf8") == 0) {
4604 entry.fourcc = FOURCC_tx3g;
4605 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
4606 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
4613 qtpad->fourcc = entry.fourcc;
4615 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
4616 qtmux->context, &entry);
4618 gst_object_unref (qtmux);
4624 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4625 GST_PAD_NAME (pad), caps);
4626 gst_object_unref (qtmux);
4629 refuse_renegotiation:
4631 GST_WARNING_OBJECT (qtmux,
4632 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4634 gst_object_unref (qtmux);
4640 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
4641 GstEvent * event, gpointer user_data)
4644 guint32 avg_bitrate = 0, max_bitrate = 0;
4645 GstPad *pad = data->pad;
4646 gboolean ret = TRUE;
4648 qtmux = GST_QT_MUX_CAST (user_data);
4649 switch (GST_EVENT_TYPE (event)) {
4650 case GST_EVENT_CAPS:
4653 GstQTPad *collect_pad;
4655 gst_event_parse_caps (event, &caps);
4657 /* find stream data */
4658 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4659 g_assert (collect_pad);
4660 g_assert (collect_pad->set_caps);
4662 ret = collect_pad->set_caps (collect_pad, caps);
4663 gst_event_unref (event);
4667 case GST_EVENT_TAG:{
4669 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
4670 GstTagMergeMode mode;
4672 GstQTPad *collect_pad;
4674 GST_OBJECT_LOCK (qtmux);
4675 mode = gst_tag_setter_get_tag_merge_mode (setter);
4676 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4678 gst_event_parse_tag (event, &list);
4679 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
4680 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
4682 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
4683 gst_tag_setter_merge_tags (setter, list, mode);
4684 qtmux->tags_changed = TRUE;
4686 if (!collect_pad->tags)
4687 collect_pad->tags = gst_tag_list_new_empty ();
4688 gst_tag_list_insert (collect_pad->tags, list, mode);
4689 collect_pad->tags_changed = TRUE;
4691 GST_OBJECT_UNLOCK (qtmux);
4693 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
4694 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
4695 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4698 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
4699 qtpad->avg_bitrate = avg_bitrate;
4700 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
4701 qtpad->max_bitrate = max_bitrate;
4704 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
4705 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
4707 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4710 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
4711 qtpad->trak->mdia.mdhd.language_code =
4712 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
4713 (iso_code[2] - 0x60);
4719 gst_event_unref (event);
4729 return gst_collect_pads_event_default (pads, data, event, FALSE);
4735 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
4737 GstQTMux *mux = GST_QT_MUX_CAST (element);
4740 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
4742 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
4743 GstQTPad *qtpad = (GstQTPad *) walk->data;
4744 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
4745 if (qtpad->collect.pad == pad) {
4746 /* this is it, remove */
4747 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
4748 gst_element_remove_pad (element, pad);
4753 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
4754 mux->current_pad = NULL;
4755 mux->current_chunk_size = 0;
4756 mux->current_chunk_duration = 0;
4759 gst_collect_pads_remove_pad (mux->collect, pad);
4761 if (mux->sinkpads == NULL) {
4762 /* No more outstanding request pads, reset our counters */
4763 mux->video_pads = 0;
4764 mux->audio_pads = 0;
4765 mux->subtitle_pads = 0;
4770 gst_qt_mux_request_new_pad (GstElement * element,
4771 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
4773 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
4774 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4775 GstQTPad *collect_pad;
4777 GstQTPadSetCapsFunc setcaps_func;
4780 gboolean lock = TRUE;
4782 if (templ->direction != GST_PAD_SINK)
4783 goto wrong_direction;
4785 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
4788 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
4789 setcaps_func = gst_qt_mux_audio_sink_set_caps;
4790 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
4791 name = g_strdup (req_name);
4793 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
4795 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
4796 setcaps_func = gst_qt_mux_video_sink_set_caps;
4797 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
4798 name = g_strdup (req_name);
4800 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
4802 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
4803 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
4804 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
4805 name = g_strdup (req_name);
4807 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
4811 goto wrong_template;
4813 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
4815 /* create pad and add to collections */
4816 newpad = gst_pad_new_from_template (templ, name);
4818 collect_pad = (GstQTPad *)
4819 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
4820 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
4822 gst_qt_mux_pad_reset (collect_pad);
4823 collect_pad->trak = atom_trak_new (qtmux->context);
4824 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
4826 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
4828 /* set up pad functions */
4829 collect_pad->set_caps = setcaps_func;
4831 gst_pad_set_active (newpad, TRUE);
4832 gst_element_add_pad (element, newpad);
4839 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
4844 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
4849 GST_WARNING_OBJECT (qtmux, "This is not our template!");
4855 gst_qt_mux_get_property (GObject * object,
4856 guint prop_id, GValue * value, GParamSpec * pspec)
4858 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4860 GST_OBJECT_LOCK (qtmux);
4862 case PROP_MOVIE_TIMESCALE:
4863 g_value_set_uint (value, qtmux->timescale);
4865 case PROP_TRAK_TIMESCALE:
4866 g_value_set_uint (value, qtmux->trak_timescale);
4869 g_value_set_boolean (value, qtmux->guess_pts);
4871 #ifndef GST_REMOVE_DEPRECATED
4872 case PROP_DTS_METHOD:
4873 g_value_set_enum (value, qtmux->dts_method);
4876 case PROP_FAST_START:
4877 g_value_set_boolean (value, qtmux->fast_start);
4879 case PROP_FAST_START_TEMP_FILE:
4880 g_value_set_string (value, qtmux->fast_start_file_path);
4882 case PROP_MOOV_RECOV_FILE:
4883 g_value_set_string (value, qtmux->moov_recov_file_path);
4885 case PROP_FRAGMENT_DURATION:
4886 g_value_set_uint (value, qtmux->fragment_duration);
4888 case PROP_STREAMABLE:
4889 g_value_set_boolean (value, qtmux->streamable);
4891 case PROP_RESERVED_MAX_DURATION:
4892 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4894 case PROP_RESERVED_DURATION_REMAINING:
4895 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
4896 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4898 GstClockTime remaining = qtmux->reserved_duration_remaining;
4900 /* Report the remaining space as the calculated remaining, minus
4901 * however much we've muxed since the last update */
4902 if (remaining > qtmux->muxed_since_last_update)
4903 remaining -= qtmux->muxed_since_last_update;
4906 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
4907 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
4908 remaining, qtmux->reserved_duration_remaining,
4909 qtmux->muxed_since_last_update);
4910 g_value_set_uint64 (value, remaining);
4913 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4914 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
4916 case PROP_RESERVED_BYTES_PER_SEC:
4917 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
4919 case PROP_INTERLEAVE_BYTES:
4920 g_value_set_uint64 (value, qtmux->interleave_bytes);
4922 case PROP_INTERLEAVE_TIME:
4923 g_value_set_uint64 (value, qtmux->interleave_time);
4926 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4929 GST_OBJECT_UNLOCK (qtmux);
4933 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
4937 g_free (qtmux->fast_start_file_path);
4938 qtmux->fast_start_file_path = NULL;
4940 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
4941 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
4946 gst_qt_mux_set_property (GObject * object,
4947 guint prop_id, const GValue * value, GParamSpec * pspec)
4949 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4951 GST_OBJECT_LOCK (qtmux);
4953 case PROP_MOVIE_TIMESCALE:
4954 qtmux->timescale = g_value_get_uint (value);
4956 case PROP_TRAK_TIMESCALE:
4957 qtmux->trak_timescale = g_value_get_uint (value);
4960 qtmux->guess_pts = g_value_get_boolean (value);
4962 #ifndef GST_REMOVE_DEPRECATED
4963 case PROP_DTS_METHOD:
4964 qtmux->dts_method = g_value_get_enum (value);
4967 case PROP_FAST_START:
4968 qtmux->fast_start = g_value_get_boolean (value);
4970 case PROP_FAST_START_TEMP_FILE:
4971 g_free (qtmux->fast_start_file_path);
4972 qtmux->fast_start_file_path = g_value_dup_string (value);
4973 /* NULL means to generate a random one */
4974 if (!qtmux->fast_start_file_path) {
4975 gst_qt_mux_generate_fast_start_file_path (qtmux);
4978 case PROP_MOOV_RECOV_FILE:
4979 g_free (qtmux->moov_recov_file_path);
4980 qtmux->moov_recov_file_path = g_value_dup_string (value);
4982 case PROP_FRAGMENT_DURATION:
4983 qtmux->fragment_duration = g_value_get_uint (value);
4985 case PROP_STREAMABLE:{
4986 GstQTMuxClass *qtmux_klass =
4987 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4988 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
4989 qtmux->streamable = g_value_get_boolean (value);
4993 case PROP_RESERVED_MAX_DURATION:
4994 qtmux->reserved_max_duration = g_value_get_uint64 (value);
4996 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4997 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
4999 case PROP_RESERVED_BYTES_PER_SEC:
5000 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
5002 case PROP_INTERLEAVE_BYTES:
5003 qtmux->interleave_bytes = g_value_get_uint64 (value);
5004 qtmux->interleave_bytes_set = TRUE;
5006 case PROP_INTERLEAVE_TIME:
5007 qtmux->interleave_time = g_value_get_uint64 (value);
5008 qtmux->interleave_time_set = TRUE;
5011 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5014 GST_OBJECT_UNLOCK (qtmux);
5017 static GstStateChangeReturn
5018 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
5020 GstStateChangeReturn ret;
5021 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
5023 switch (transition) {
5024 case GST_STATE_CHANGE_NULL_TO_READY:
5026 case GST_STATE_CHANGE_READY_TO_PAUSED:
5027 gst_collect_pads_start (qtmux->collect);
5028 qtmux->state = GST_QT_MUX_STATE_STARTED;
5029 qtmux->first_tc = NULL;
5032 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5034 case GST_STATE_CHANGE_PAUSED_TO_READY:
5035 gst_collect_pads_stop (qtmux->collect);
5041 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5043 switch (transition) {
5044 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
5046 case GST_STATE_CHANGE_PAUSED_TO_READY:
5047 gst_qt_mux_reset (qtmux, TRUE);
5049 case GST_STATE_CHANGE_READY_TO_NULL:
5059 gst_qt_mux_register (GstPlugin * plugin)
5061 GTypeInfo typeinfo = {
5062 sizeof (GstQTMuxClass),
5063 (GBaseInitFunc) gst_qt_mux_base_init,
5065 (GClassInitFunc) gst_qt_mux_class_init,
5070 (GInstanceInitFunc) gst_qt_mux_init,
5072 static const GInterfaceInfo tag_setter_info = {
5075 static const GInterfaceInfo tag_xmp_writer_info = {
5078 static const GInterfaceInfo preset_info = {
5082 GstQTMuxFormat format;
5083 GstQTMuxClassParams *params;
5086 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
5088 GST_LOG ("Registering muxers");
5091 GstQTMuxFormatProp *prop;
5092 GstCaps *subtitle_caps;
5094 prop = &gst_qt_mux_format_list[i];
5095 format = prop->format;
5096 if (format == GST_QT_MUX_FORMAT_NONE)
5099 /* create a cache for these properties */
5100 params = g_new0 (GstQTMuxClassParams, 1);
5101 params->prop = prop;
5102 params->src_caps = gst_static_caps_get (&prop->src_caps);
5103 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
5104 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
5105 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
5106 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
5107 params->subtitle_sink_caps = subtitle_caps;
5109 gst_caps_unref (subtitle_caps);
5112 /* create the type now */
5113 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
5115 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
5116 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
5117 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
5118 &tag_xmp_writer_info);
5119 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
5121 if (!gst_element_register (plugin, prop->name, prop->rank, type))
5127 GST_LOG ("Finished registering muxers");
5129 /* FIXME: ideally classification tag should be added and
5130 registered in gstreamer core gsttaglist
5133 GST_LOG ("Registering tags");
5135 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
5136 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
5137 gst_tag_merge_use_first);
5139 GST_LOG ("Finished registering tags");