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
150 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
155 * The basic building blocks of MP4 files are:
156 * - an 'ftyp' box at the very start
157 * - an 'mdat' box which contains the raw audio/video/subtitle data;
158 * this is just a bunch of bytes, completely unframed and possibly
159 * unordered with no additional meta-information
160 * - a 'moov' box that contains information about the different streams
161 * and what they contain, as well as sample tables for each stream
162 * that tell the demuxer where in the mdat box each buffer/sample is
163 * and what its duration/timestamp etc. is, and whether it's a
165 * Additionally, fragmented MP4 works by writing chunks of data in
166 * pairs of 'moof' and 'mdat' boxes:
167 * - 'moof' boxes, header preceding each mdat fragment describing the
168 * contents, like a moov but only for that fragment.
169 * - a 'mfra' box for Fragmented MP4, which is written at the end and
170 * contains a summary of all fragments and seek tables.
172 * Currently mp4mux can work in 4 different modes / generate 4 types
173 * of output files/streams:
175 * - Normal mp4: mp4mux will write a little ftyp identifier at the
176 * beginning, then start an mdat box into which it will write all the
177 * sample data. At EOS it will then write the moov header with track
178 * headers and sample tables at the end of the file, and rewrite the
179 * start of the file to fix up the mdat box size at the beginning.
180 * It has to wait for EOS to write the moov (which includes the
181 * sample tables) because it doesn't know how much space those
182 * tables will be. The output downstream must be seekable to rewrite
183 * the mdat box at EOS.
185 * - Fragmented mp4: moov header with track headers at start
186 * but no sample table, followed by N fragments, each containing
187 * track headers with sample tables followed by some data. Downstream
188 * does not need to be seekable if the 'streamable' flag is TRUE,
189 * as the final mfra and total duration will be omitted.
191 * - Fast-start mp4: the goal here is to create a file where the moov
192 * headers are at the beginning; what mp4mux will do is write all
193 * sample data into a temp file and build moov header plus sample
194 * tables in memory and then when EOS comes, it will push out the
195 * moov header plus sample tables at the beginning, followed by the
196 * mdat sample data at the end which is read in from the temp file
197 * Files created in this mode are better for streaming over the
198 * network, since the client doesn't have to seek to the end of the
199 * file to get the headers, but it requires copying all sample data
200 * out of the temp file at EOS, which can be expensive. Downstream does
201 * not need to be seekable, because of the use of the temp file.
203 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
204 * and reserved-moov-update-period properties to reserve free space
205 * at the start of the file and periodically write the MOOV atom out
206 * to it. That means that killing the muxing at any point still
207 * results in a playable file, at the cost of wasting some amount of
208 * free space at the start of file. The approximate recording duration
209 * has to be known in advance to estimate how much free space to reserve
210 * for the moov, and the downstream must be seekable.
211 * If the moov header grows larger than the reserved space, an error
212 * is generated - so it's better to over-estimate the amount of space
213 * to reserve. To ensure the file is playable at any point, the moov
214 * is updated using a 'ping-pong' strategy, so the output is never in
218 #ifndef GST_REMOVE_DEPRECATED
227 gst_qt_mux_dts_method_get_type (void)
229 static GType gst_qt_mux_dts_method = 0;
231 if (!gst_qt_mux_dts_method) {
232 static const GEnumValue dts_methods[] = {
233 {DTS_METHOD_DD, "delta/duration", "dd"},
234 {DTS_METHOD_REORDER, "reorder", "reorder"},
235 {DTS_METHOD_ASC, "ascending", "asc"},
239 gst_qt_mux_dts_method =
240 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
243 return gst_qt_mux_dts_method;
246 #define GST_TYPE_QT_MUX_DTS_METHOD \
247 (gst_qt_mux_dts_method_get_type ())
250 /* QTMux signals and args */
260 PROP_MOVIE_TIMESCALE,
263 PROP_FAST_START_TEMP_FILE,
264 PROP_MOOV_RECOV_FILE,
265 PROP_FRAGMENT_DURATION,
267 PROP_RESERVED_MAX_DURATION,
268 PROP_RESERVED_DURATION_REMAINING,
269 PROP_RESERVED_MOOV_UPDATE_PERIOD,
270 PROP_RESERVED_BYTES_PER_SEC,
271 PROP_RESERVED_PREFILL,
272 #ifndef GST_REMOVE_DEPRECATED
276 PROP_INTERLEAVE_BYTES,
277 PROP_INTERLEAVE_TIME,
278 PROP_MAX_RAW_AUDIO_DRIFT,
281 /* some spare for header size as well */
282 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
284 #define DEFAULT_MOVIE_TIMESCALE 0
285 #define DEFAULT_TRAK_TIMESCALE 0
286 #define DEFAULT_DO_CTTS TRUE
287 #define DEFAULT_FAST_START FALSE
288 #define DEFAULT_FAST_START_TEMP_FILE NULL
289 #define DEFAULT_MOOV_RECOV_FILE NULL
290 #define DEFAULT_FRAGMENT_DURATION 0
291 #define DEFAULT_STREAMABLE TRUE
292 #ifndef GST_REMOVE_DEPRECATED
293 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
295 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
296 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
297 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
298 #define DEFAULT_RESERVED_PREFILL FALSE
299 #define DEFAULT_INTERLEAVE_BYTES 0
300 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
301 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
303 static void gst_qt_mux_finalize (GObject * object);
305 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
306 GstStateChange transition);
308 /* property functions */
309 static void gst_qt_mux_set_property (GObject * object,
310 guint prop_id, const GValue * value, GParamSpec * pspec);
311 static void gst_qt_mux_get_property (GObject * object,
312 guint prop_id, GValue * value, GParamSpec * pspec);
315 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
316 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
317 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
320 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
321 GstCollectData * data, GstEvent * event, gpointer user_data);
323 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
325 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
329 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
331 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
332 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
334 static GstElementClass *parent_class = NULL;
337 gst_qt_mux_base_init (gpointer g_class)
339 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
340 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
341 GstQTMuxClassParams *params;
342 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
343 GstPadTemplate *srctempl;
344 gchar *longname, *description;
347 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
348 GST_QT_MUX_PARAMS_QDATA);
349 g_assert (params != NULL);
351 /* construct the element details struct */
352 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
353 description = g_strdup_printf ("Multiplex audio and video into a %s file",
354 params->prop->long_name);
355 gst_element_class_set_static_metadata (element_class, longname,
356 "Codec/Muxer", description,
357 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
359 g_free (description);
362 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
363 GST_PAD_ALWAYS, params->src_caps);
364 gst_element_class_add_pad_template (element_class, srctempl);
366 if (params->audio_sink_caps) {
367 audiosinktempl = gst_pad_template_new ("audio_%u",
368 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
369 gst_element_class_add_pad_template (element_class, audiosinktempl);
372 if (params->video_sink_caps) {
373 videosinktempl = gst_pad_template_new ("video_%u",
374 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
375 gst_element_class_add_pad_template (element_class, videosinktempl);
378 if (params->subtitle_sink_caps) {
379 subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
380 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
381 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
384 klass->format = params->prop->format;
388 gst_qt_mux_class_init (GstQTMuxClass * klass)
390 GObjectClass *gobject_class;
391 GstElementClass *gstelement_class;
392 GParamFlags streamable_flags;
393 const gchar *streamable_desc;
395 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
396 "be streamed and hence no indexes written or duration written."
398 gobject_class = (GObjectClass *) klass;
399 gstelement_class = (GstElementClass *) klass;
401 parent_class = g_type_class_peek_parent (klass);
403 gobject_class->finalize = gst_qt_mux_finalize;
404 gobject_class->get_property = gst_qt_mux_get_property;
405 gobject_class->set_property = gst_qt_mux_set_property;
407 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
408 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
409 streamable_desc = STREAMABLE_DESC;
410 streamable = DEFAULT_STREAMABLE;
413 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
414 streamable_flags |= G_PARAM_DEPRECATED;
418 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
419 g_param_spec_uint ("movie-timescale", "Movie timescale",
420 "Timescale to use in the movie (units per second, 0 == default)",
421 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
422 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
423 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
424 g_param_spec_uint ("trak-timescale", "Track timescale",
425 "Timescale to use for the tracks (units per second, 0 is automatic)",
426 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
427 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
428 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
429 g_param_spec_boolean ("presentation-time",
430 "Include presentation-time info",
431 "Calculate and include presentation/composition time "
432 "(in addition to decoding time)", DEFAULT_DO_CTTS,
433 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
434 #ifndef GST_REMOVE_DEPRECATED
435 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
436 g_param_spec_enum ("dts-method", "dts-method",
437 "Method to determine DTS time (DEPRECATED)",
438 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
439 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
440 G_PARAM_STATIC_STRINGS));
442 g_object_class_install_property (gobject_class, PROP_FAST_START,
443 g_param_spec_boolean ("faststart", "Format file to faststart",
444 "If the file should be formatted for faststart (headers first)",
445 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
447 g_param_spec_string ("faststart-file", "File to use for storing buffers",
448 "File that will be used temporarily to store data from the stream "
449 "when creating a faststart file. If null a filepath will be "
450 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
451 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
452 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
453 g_param_spec_string ("moov-recovery-file",
454 "File to store data for posterior moov atom recovery",
455 "File to be used to store "
456 "data for moov atom making movie file recovery possible in case "
457 "of a crash during muxing. Null for disabled. (Experimental)",
458 DEFAULT_MOOV_RECOV_FILE,
459 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
460 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
461 g_param_spec_uint ("fragment-duration", "Fragment duration",
462 "Fragment durations in ms (produce a fragmented file if > 0)",
463 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
464 2000 : DEFAULT_FRAGMENT_DURATION,
465 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
466 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
467 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
468 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
469 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
470 g_param_spec_uint64 ("reserved-max-duration",
471 "Reserved maximum file duration (ns)",
472 "When set to a value > 0, reserves space for index tables at the "
473 "beginning of the file.",
474 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
475 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
476 g_object_class_install_property (gobject_class,
477 PROP_RESERVED_DURATION_REMAINING,
478 g_param_spec_uint64 ("reserved-duration-remaining",
479 "Report the approximate amount of remaining recording space (ns)",
480 "Reports the approximate amount of remaining moov header space "
481 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
482 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
483 g_object_class_install_property (gobject_class,
484 PROP_RESERVED_MOOV_UPDATE_PERIOD,
485 g_param_spec_uint64 ("reserved-moov-update-period",
486 "Interval at which to update index tables (ns)",
487 "When used with reserved-max-duration, periodically updates the "
488 "index tables with information muxed so far.", 0, G_MAXUINT64,
489 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
490 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
491 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
492 g_param_spec_uint ("reserved-bytes-per-sec",
493 "Reserved MOOV bytes per second, per track",
494 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
495 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
496 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
497 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
498 g_param_spec_boolean ("reserved-prefill",
499 "Reserved Prefill Samples Table",
500 "Prefill samples table of reserved duration",
501 DEFAULT_RESERVED_PREFILL,
502 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
503 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
504 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
505 "Interleave between streams in bytes",
506 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
507 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
508 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
509 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
510 "Interleave between streams in nanoseconds",
511 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
512 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
513 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
514 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
515 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
516 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
517 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
519 gstelement_class->request_new_pad =
520 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
521 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
522 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
526 gst_qt_mux_pad_reset (GstQTPad * qtpad)
529 qtpad->is_out_of_order = FALSE;
530 qtpad->sample_size = 0;
533 qtpad->sample_offset = 0;
534 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
535 qtpad->first_ts = GST_CLOCK_TIME_NONE;
536 qtpad->first_dts = GST_CLOCK_TIME_NONE;
537 qtpad->prepare_buf_func = NULL;
538 qtpad->create_empty_buffer = NULL;
539 qtpad->avg_bitrate = 0;
540 qtpad->max_bitrate = 0;
541 qtpad->total_duration = 0;
542 qtpad->total_bytes = 0;
543 qtpad->sparse = FALSE;
545 gst_buffer_replace (&qtpad->last_buf, NULL);
548 gst_tag_list_unref (qtpad->tags);
552 /* reference owned elsewhere */
554 qtpad->tc_trak = NULL;
557 atom_traf_free (qtpad->traf);
560 atom_array_clear (&qtpad->fragment_buffers);
562 g_array_unref (qtpad->samples);
563 qtpad->samples = NULL;
565 /* reference owned elsewhere */
568 qtpad->first_pts = GST_CLOCK_TIME_NONE;
571 gst_video_time_code_free (qtpad->first_tc);
572 qtpad->first_tc = NULL;
574 if (qtpad->raw_audio_adapter)
575 gst_object_unref (qtpad->raw_audio_adapter);
576 qtpad->raw_audio_adapter = NULL;
580 * Takes GstQTMux back to its initial state
583 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
587 qtmux->state = GST_QT_MUX_STATE_NONE;
588 qtmux->header_size = 0;
589 qtmux->mdat_size = 0;
592 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
593 qtmux->fragment_sequence = 0;
596 atom_ftyp_free (qtmux->ftyp);
600 atom_moov_free (qtmux->moov);
604 atom_mfra_free (qtmux->mfra);
607 if (qtmux->fast_start_file) {
608 fclose (qtmux->fast_start_file);
609 g_remove (qtmux->fast_start_file_path);
610 qtmux->fast_start_file = NULL;
612 if (qtmux->moov_recov_file) {
613 fclose (qtmux->moov_recov_file);
614 qtmux->moov_recov_file = NULL;
616 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
617 AtomInfo *ainfo = (AtomInfo *) walk->data;
618 ainfo->free_func (ainfo->atom);
621 g_slist_free (qtmux->extra_atoms);
622 qtmux->extra_atoms = NULL;
624 GST_OBJECT_LOCK (qtmux);
625 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
626 GST_OBJECT_UNLOCK (qtmux);
629 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
630 GstQTPad *qtpad = (GstQTPad *) walk->data;
631 gst_qt_mux_pad_reset (qtpad);
633 /* hm, moov_free above yanked the traks away from us,
634 * so do not free, but do clear */
639 qtmux->moov = atom_moov_new (qtmux->context);
640 /* ensure all is as nice and fresh as request_new_pad would provide it */
641 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
642 GstQTPad *qtpad = (GstQTPad *) walk->data;
644 qtpad->trak = atom_trak_new (qtmux->context);
645 atom_moov_add_trak (qtmux->moov, qtpad->trak);
649 qtmux->current_pad = NULL;
650 qtmux->current_chunk_size = 0;
651 qtmux->current_chunk_duration = 0;
652 qtmux->current_chunk_offset = -1;
654 qtmux->reserved_moov_size = 0;
655 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
656 qtmux->muxed_since_last_update = 0;
657 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
661 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
663 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
664 GstPadTemplate *templ;
666 templ = gst_element_class_get_pad_template (klass, "src");
667 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
668 gst_pad_use_fixed_caps (qtmux->srcpad);
669 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
671 qtmux->sinkpads = NULL;
672 qtmux->collect = gst_collect_pads_new ();
673 gst_collect_pads_set_event_function (qtmux->collect,
674 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
675 gst_collect_pads_set_clip_function (qtmux->collect,
676 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
677 gst_collect_pads_set_function (qtmux->collect,
678 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
680 /* properties set to default upon construction */
682 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
683 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
684 qtmux->reserved_bytes_per_sec_per_trak =
685 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
686 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
687 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
688 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
690 /* always need this */
692 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
694 /* internals to initial state */
695 gst_qt_mux_reset (qtmux, TRUE);
700 gst_qt_mux_finalize (GObject * object)
702 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
704 gst_qt_mux_reset (qtmux, FALSE);
706 g_free (qtmux->fast_start_file_path);
707 g_free (qtmux->moov_recov_file_path);
709 atoms_context_free (qtmux->context);
710 gst_object_unref (qtmux->collect);
712 g_slist_free (qtmux->sinkpads);
714 G_OBJECT_CLASS (parent_class)->finalize (object);
718 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
725 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
730 size = gst_buffer_get_size (buf);
731 newbuf = gst_buffer_new_and_alloc (size + 8);
732 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
734 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
735 GST_WRITE_UINT32_BE (map.data, map.size);
736 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
738 gst_buffer_unmap (buf, &map);
739 gst_buffer_unref (buf);
745 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
752 const guint8 *dataend;
754 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
759 gst_buffer_map (buf, &frommap, GST_MAP_READ);
761 dataend = memchr (frommap.data, 0, frommap.size);
762 size = dataend ? dataend - frommap.data : frommap.size;
763 newbuf = gst_buffer_new_and_alloc (size + 2);
765 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
767 GST_WRITE_UINT16_BE (tomap.data, size);
768 memcpy (tomap.data + 2, frommap.data, size);
770 gst_buffer_unmap (newbuf, &tomap);
771 gst_buffer_unmap (buf, &frommap);
773 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
775 /* gst_buffer_copy_into is trying to be too clever and
776 * won't copy duration when size is different */
777 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
779 gst_buffer_unref (buf);
785 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
786 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
791 g_return_if_fail (qtpad->trak_ste);
793 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
795 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
799 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
803 GstByteReader reader;
806 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
807 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
811 if (G_UNLIKELY (map.size < 8))
814 gst_byte_reader_init (&reader, map.data, map.size);
815 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
820 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
822 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
825 gst_bit_reader_init (&bits, map.data, map.size);
827 /* off + sync + crc */
828 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
830 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
831 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
832 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
833 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
834 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
836 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
837 gst_bit_reader_skip_unchecked (&bits, 2);
838 if ((acmod & 0x4)) /* if a surround channel exists */
839 gst_bit_reader_skip_unchecked (&bits, 2);
840 if (acmod == 0x2) /* if in 2/0 mode */
841 gst_bit_reader_skip_unchecked (&bits, 2);
843 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
845 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
846 bsmod, acmod, lfe_on);
848 /* AC-3 spec says that those values should be constant for the
849 * whole stream when muxed in mp4. We trust the input follows it */
850 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
851 "prepare buffer function");
852 qtpad->prepare_buf_func = NULL;
856 gst_buffer_unmap (buf, &map);
861 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
866 GST_WRITE_UINT16_BE (data, 0);
868 return gst_buffer_new_wrapped (data, 2);
872 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
873 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
875 switch (gst_tag_get_type (tag)) {
881 if (!gst_tag_list_get_string (list, tag, &str) || !str)
883 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
884 GST_FOURCC_ARGS (fourcc), str);
885 atom_udta_add_str_tag (udta, fourcc, str);
894 if (!gst_tag_list_get_double (list, tag, &value))
896 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
897 GST_FOURCC_ARGS (fourcc), (gint) value);
898 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
905 /* paired unsigned integers */
909 got_tag = gst_tag_list_get_uint (list, tag, &value);
910 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
913 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
914 GST_FOURCC_ARGS (fourcc), value, count);
915 atom_udta_add_uint_tag (udta, fourcc, 0,
916 value << 16 | (count & 0xFFFF));
918 /* unpaired unsigned integers */
919 if (!gst_tag_list_get_uint (list, tag, &value))
921 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
922 GST_FOURCC_ARGS (fourcc), value);
923 atom_udta_add_uint_tag (udta, fourcc, 1, value);
928 g_assert_not_reached ();
934 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
935 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
943 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
945 if (!gst_tag_list_get_date (list, tag, &date) || !date)
948 year = g_date_get_year (date);
949 month = g_date_get_month (date);
950 day = g_date_get_day (date);
954 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
955 day == G_DATE_BAD_DAY) {
956 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
960 str = g_strdup_printf ("%u-%u-%u", year, month, day);
961 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
962 GST_FOURCC_ARGS (fourcc), str);
963 atom_udta_add_str_tag (udta, fourcc, str);
968 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
969 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
971 GValue value = { 0, };
975 GstStructure *structure;
979 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
981 if (!gst_tag_list_copy_value (&value, list, tag))
984 sample = gst_value_get_sample (&value);
989 buf = gst_sample_get_buffer (sample);
993 caps = gst_sample_get_caps (sample);
995 GST_WARNING_OBJECT (qtmux, "preview image without caps");
999 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1001 structure = gst_caps_get_structure (caps, 0);
1002 if (gst_structure_has_name (structure, "image/jpeg"))
1004 else if (gst_structure_has_name (structure, "image/png"))
1008 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1012 gst_buffer_map (buf, &map, GST_MAP_READ);
1013 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1014 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1015 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1016 gst_buffer_unmap (buf, &map);
1018 g_value_unset (&value);
1022 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1023 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1028 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1029 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1031 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1035 if (!gst_tag_list_get_uint (list, tag2, &number))
1039 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1040 GST_FOURCC_ARGS (fourcc), str);
1041 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1043 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1044 GST_FOURCC_ARGS (fourcc), str, number);
1045 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1052 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1053 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1058 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1060 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1063 year = g_date_get_year (date);
1066 if (year == G_DATE_BAD_YEAR) {
1067 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1071 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1072 GST_FOURCC_ARGS (fourcc), year);
1073 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1077 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1078 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1080 gdouble latitude = -360, longitude = -360, altitude = 0;
1081 gchar *location = NULL;
1082 guint8 *data, *ddata;
1083 gint size = 0, len = 0;
1084 gboolean ret = FALSE;
1086 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1088 ret = gst_tag_list_get_string (list, tag, &location);
1089 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1091 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1093 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1100 len = strlen (location);
1101 size += len + 1 + 2;
1103 /* role + (long, lat, alt) + body + notes */
1104 size += 1 + 3 * 4 + 1 + 1;
1106 data = ddata = g_malloc (size);
1109 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1112 memcpy (data + 2, location, len);
1113 GST_WRITE_UINT8 (data + 2 + len, 0);
1114 data += len + 1 + 2;
1116 GST_WRITE_UINT8 (data, 0);
1117 /* long, lat, alt */
1118 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1119 QT_WRITE_SFP32 (data + 1, longitude);
1120 QT_WRITE_SFP32 (data + 5, latitude);
1121 QT_WRITE_SFP32 (data + 9, altitude);
1122 /* neither astronomical body nor notes */
1123 GST_WRITE_UINT16_BE (data + 13, 0);
1125 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1126 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1131 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1132 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1134 gchar *keywords = NULL;
1135 guint8 *data, *ddata;
1139 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1141 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1144 kwds = g_strsplit (keywords, ",", 0);
1148 for (i = 0; kwds[i]; i++) {
1149 /* size byte + null-terminator */
1150 size += strlen (kwds[i]) + 1 + 1;
1153 /* language tag + count + keywords */
1156 data = ddata = g_malloc (size);
1159 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1161 GST_WRITE_UINT8 (data + 2, i);
1164 for (i = 0; kwds[i]; ++i) {
1165 gint len = strlen (kwds[i]);
1167 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1168 GST_FOURCC_ARGS (fourcc), kwds[i]);
1170 GST_WRITE_UINT8 (data, len + 1);
1171 memcpy (data + 1, kwds[i], len + 1);
1177 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1182 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1183 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1191 size = strlen (input);
1193 if (size < 4 + 3 + 1 + 1 + 1) {
1194 /* at least the minimum xxxx://y/z */
1195 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1200 /* read the fourcc */
1201 memcpy (&fourcc, data, 4);
1205 if (strncmp (data, "://", 3) != 0) {
1211 /* read the table number */
1212 if (sscanf (data, "%d", &table) != 1) {
1216 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1217 ", table numbers should be positive, ignoring tag", table);
1221 /* find the next / */
1222 while (size > 0 && data[0] != '/') {
1229 g_assert (data[0] == '/');
1238 /* read up the rest of the string */
1239 *p_content = g_strdup (data);
1240 *p_table = (guint16) table;
1246 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1247 "input (%s) didn't match the expected entitycode://table/content",
1254 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1255 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1257 gchar *clsf_data = NULL;
1261 gchar *content = NULL;
1264 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1266 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1269 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1270 GST_FOURCC_ARGS (fourcc), clsf_data);
1272 /* parse the string, format is:
1273 * entityfourcc://table/content
1275 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1279 size = strlen (content) + 1;
1281 /* now we have everything, build the atom
1282 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1283 data = g_malloc (4 + 2 + 2 + size);
1284 GST_WRITE_UINT32_LE (data, entity);
1285 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1286 GST_WRITE_UINT16_BE (data + 6, 0);
1287 memcpy (data + 8, content, size);
1290 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1294 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1295 const GstTagList * list, AtomUDTA * udta, const char *tag,
1296 const char *tag2, guint32 fourcc);
1299 * Struct to record mappings from gstreamer tags to fourcc codes
1301 typedef struct _GstTagToFourcc
1304 const gchar *gsttag;
1305 const gchar *gsttag2;
1306 const GstQTMuxAddUdtaTagFunc func;
1309 /* tag list tags to fourcc matching */
1310 static const GstTagToFourcc tag_matches_mp4[] = {
1311 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1312 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1313 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1314 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1315 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1316 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1317 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1318 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1319 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1320 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1321 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1322 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1323 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1324 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1325 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1326 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1327 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1328 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1329 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1330 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1331 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1332 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1333 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1334 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1335 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1336 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1337 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1338 gst_qt_mux_add_mp4_tag},
1339 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1340 gst_qt_mux_add_mp4_tag},
1341 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1342 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1346 static const GstTagToFourcc tag_matches_3gp[] = {
1347 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1348 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1349 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1350 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1351 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1352 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1353 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1354 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1355 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1356 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1357 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1358 gst_qt_mux_add_3gp_classification},
1362 /* qtdemux produces these for atoms it cannot parse */
1363 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1366 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1368 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1369 GstBuffer *xmp = NULL;
1371 /* adobe specs only have 'quicktime' and 'mp4',
1372 * but I guess we can extrapolate to gpp.
1373 * Keep mj2 out for now as we don't add any tags for it yet.
1374 * If you have further info about xmp on these formats, please share */
1375 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1378 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1380 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1381 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1384 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1387 /* for isom/mp4, it is a top level uuid atom */
1388 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1391 ainfo = build_uuid_xmp_atom (xmp);
1393 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1398 gst_buffer_unref (xmp);
1402 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1405 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1408 const gchar *tag, *tag2;
1409 const GstTagToFourcc *tag_matches;
1411 switch (qtmux_klass->format) {
1412 case GST_QT_MUX_FORMAT_3GP:
1413 tag_matches = tag_matches_3gp;
1415 case GST_QT_MUX_FORMAT_MJ2:
1419 /* sort of iTunes style for mp4 and QT (?) */
1420 tag_matches = tag_matches_mp4;
1427 /* Clear existing tags so we don't add them over and over */
1428 atom_udta_clear_tags (udta);
1430 for (i = 0; tag_matches[i].fourcc; i++) {
1431 fourcc = tag_matches[i].fourcc;
1432 tag = tag_matches[i].gsttag;
1433 tag2 = tag_matches[i].gsttag2;
1435 g_assert (tag_matches[i].func);
1436 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1439 /* add unparsed blobs if present */
1440 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1443 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1444 for (i = 0; i < num_tags; ++i) {
1445 GstSample *sample = NULL;
1447 const GstStructure *s;
1449 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1452 buf = gst_sample_get_buffer (sample);
1454 if (buf && (s = gst_sample_get_info (sample))) {
1455 const gchar *style = NULL;
1458 gst_buffer_map (buf, &map, GST_MAP_READ);
1459 GST_DEBUG_OBJECT (qtmux,
1460 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1461 GST_PTR_FORMAT, i, num_tags, map.size, s);
1462 if (s && (style = gst_structure_get_string (s, "style"))) {
1463 /* try to prevent some style tag ending up into another variant
1464 * (todo: make into a list if more cases) */
1465 if ((strcmp (style, "itunes") == 0 &&
1466 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1467 (strcmp (style, "iso") == 0 &&
1468 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1469 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1470 atom_udta_add_blob_tag (udta, map.data, map.size);
1473 gst_buffer_unmap (buf, &map);
1475 gst_sample_unref (sample);
1483 * Gets the tagsetter iface taglist and puts the known tags
1484 * into the output stream
1487 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1489 const GstTagList *tags = NULL;
1492 GST_OBJECT_LOCK (qtmux);
1493 if (qtmux->tags_changed) {
1494 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1495 qtmux->tags_changed = FALSE;
1497 GST_OBJECT_UNLOCK (qtmux);
1499 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1501 if (tags && !gst_tag_list_is_empty (tags)) {
1502 GstTagList *copy = gst_tag_list_copy (tags);
1504 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1505 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1506 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1507 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1509 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1510 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1511 gst_qt_mux_add_xmp_tags (qtmux, copy);
1512 gst_tag_list_unref (copy);
1514 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1517 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1518 GstCollectData *cdata = (GstCollectData *) walk->data;
1519 GstQTPad *qpad = (GstQTPad *) cdata;
1520 GstPad *pad = qpad->collect.pad;
1522 if (qpad->tags_changed && qpad->tags) {
1523 GST_DEBUG_OBJECT (pad, "Adding tags");
1524 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1525 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1526 qpad->tags_changed = FALSE;
1527 GST_DEBUG_OBJECT (pad, "Tags added");
1529 GST_DEBUG_OBJECT (pad, "No new tags received");
1534 static inline GstBuffer *
1535 _gst_buffer_new_take_data (guint8 * data, guint size)
1539 buf = gst_buffer_new ();
1540 gst_buffer_append_memory (buf,
1541 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1546 static GstFlowReturn
1547 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1553 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1555 size = gst_buffer_get_size (buf);
1556 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1558 if (mind_fast && qtmux->fast_start_file) {
1562 GST_LOG_OBJECT (qtmux, "to temporary file");
1563 gst_buffer_map (buf, &map, GST_MAP_READ);
1564 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1565 gst_buffer_unmap (buf, &map);
1566 gst_buffer_unref (buf);
1572 GST_LOG_OBJECT (qtmux, "downstream");
1573 res = gst_pad_push (qtmux->srcpad, buf);
1576 if (G_LIKELY (offset))
1584 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1585 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1586 return GST_FLOW_ERROR;
1591 gst_qt_mux_seek_to_beginning (FILE * f)
1594 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1596 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1597 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1600 if (fseek (f, (long) 0, SEEK_SET) != 0)
1606 static GstFlowReturn
1607 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1609 GstFlowReturn ret = GST_FLOW_OK;
1610 GstBuffer *buf = NULL;
1612 if (fflush (qtmux->fast_start_file))
1615 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1618 /* hm, this could all take a really really long time,
1619 * but there may not be another way to get moov atom first
1620 * (somehow optimize copy?) */
1621 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1622 while (ret == GST_FLOW_OK) {
1623 const int bufsize = 4096;
1627 buf = gst_buffer_new_and_alloc (bufsize);
1628 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1629 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1631 gst_buffer_unmap (buf, &map);
1634 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1635 gst_buffer_unmap (buf, &map);
1636 if (size != bufsize)
1637 gst_buffer_set_size (buf, size);
1638 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1642 gst_buffer_unref (buf);
1644 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1646 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1654 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1655 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1656 ret = GST_FLOW_ERROR;
1661 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1662 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1663 ret = GST_FLOW_ERROR;
1668 /* clear descriptor so we don't remove temp file later on,
1669 * might be possible to recover */
1670 fclose (qtmux->fast_start_file);
1671 qtmux->fast_start_file = NULL;
1677 * Sends the initial mdat atom fields (size fields and fourcc type),
1678 * the subsequent buffers are considered part of it's data.
1679 * As we can't predict the amount of data that we are going to place in mdat
1680 * we need to record the position of the size field in the stream so we can
1681 * seek back to it later and update when the streams have finished.
1683 static GstFlowReturn
1684 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1685 gboolean extended, gboolean fsync_after)
1690 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1691 "size %" G_GUINT64_FORMAT, size);
1693 /* if the qtmux state is EOS, really write the mdat, otherwise
1694 * allow size == 0 for a placeholder atom */
1695 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1699 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1700 /* Always write 16-bytes, but put a free atom first
1701 * if the size is < 4GB. */
1702 buf = gst_buffer_new_and_alloc (16);
1703 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1706 /* Write extended mdat header and large_size field */
1707 GST_WRITE_UINT32_BE (map.data, 1);
1708 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1709 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1711 /* Write an empty free atom, then standard 32-bit mdat */
1712 GST_WRITE_UINT32_BE (map.data, 8);
1713 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1714 GST_WRITE_UINT32_BE (map.data + 8, size);
1715 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1717 gst_buffer_unmap (buf, &map);
1719 buf = gst_buffer_new_and_alloc (8);
1720 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1722 /* Vanilla 32-bit mdat */
1723 GST_WRITE_UINT32_BE (map.data, size);
1724 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1725 gst_buffer_unmap (buf, &map);
1728 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1730 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1732 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1737 * We get the position of the mdat size field, seek back to it
1738 * and overwrite with the real value
1740 static GstFlowReturn
1741 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1742 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1746 /* We must have recorded the mdat position for this to work */
1747 g_assert (mdat_pos != 0);
1749 /* seek and rewrite the header */
1750 gst_segment_init (&segment, GST_FORMAT_BYTES);
1751 segment.start = mdat_pos;
1752 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1754 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1758 static GstFlowReturn
1759 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1762 guint64 size = 0, offset = 0;
1763 guint8 *data = NULL;
1765 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1767 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1768 goto serialize_error;
1770 buf = _gst_buffer_new_take_data (data, offset);
1772 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1773 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1778 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1779 ("Failed to serialize ftyp"));
1780 return GST_FLOW_ERROR;
1785 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1786 GstBuffer ** p_prefix)
1788 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1789 guint32 major, version;
1791 GstBuffer *prefix = NULL;
1792 AtomFTYP *ftyp = NULL;
1794 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1796 /* init and send context and ftyp based on current property state */
1797 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1798 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1799 qtmux->fast_start_file != NULL);
1800 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1807 gst_buffer_unref (prefix);
1812 static GstFlowReturn
1813 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1815 GstFlowReturn ret = GST_FLOW_OK;
1816 GstBuffer *prefix = NULL;
1818 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1820 /* init and send context and ftyp based on current property state */
1822 atom_ftyp_free (qtmux->ftyp);
1825 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1827 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1828 if (ret != GST_FLOW_OK)
1831 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1835 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1837 GstStructure *structure;
1838 GValue array = { 0 };
1839 GValue value = { 0 };
1840 GstCaps *caps, *tcaps;
1842 tcaps = gst_pad_get_current_caps (mux->srcpad);
1843 caps = gst_caps_copy (tcaps);
1844 gst_caps_unref (tcaps);
1846 structure = gst_caps_get_structure (caps, 0);
1848 g_value_init (&array, GST_TYPE_ARRAY);
1850 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1851 g_value_init (&value, GST_TYPE_BUFFER);
1852 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1853 gst_value_array_append_value (&array, &value);
1854 g_value_unset (&value);
1856 gst_structure_set_value (structure, "streamheader", &array);
1857 g_value_unset (&array);
1858 gst_pad_set_caps (mux->srcpad, caps);
1859 gst_caps_unref (caps);
1863 * Write out a free space atom. The offset is adjusted by the full
1864 * size, but a smaller buffer is sent
1866 static GstFlowReturn
1867 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1868 gboolean fsync_after)
1872 guint8 *data = NULL;
1873 guint64 offset = 0, bsize = 0;
1876 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1878 /* We can't make a free space atom smaller than the header */
1882 node_header = g_malloc0 (sizeof (Atom));
1883 node_header->type = FOURCC_free;
1884 node_header->size = size;
1887 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
1888 goto serialize_error;
1890 buf = _gst_buffer_new_take_data (data, offset);
1891 g_free (node_header);
1894 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1896 GST_LOG_OBJECT (qtmux, "Pushing free atom");
1897 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1904 /* Make sure downstream position ends up at the end of this free box */
1905 gst_segment_init (&segment, GST_FORMAT_BYTES);
1906 segment.start = *off;
1907 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1915 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1916 ("Not enough free reserved space"));
1917 return GST_FLOW_ERROR;
1921 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1922 ("Failed to serialize mdat"));
1923 g_free (node_header);
1924 return GST_FLOW_ERROR;
1929 gst_qt_mux_configure_moov (GstQTMux * qtmux)
1931 gboolean fragmented = FALSE;
1934 GST_OBJECT_LOCK (qtmux);
1935 timescale = qtmux->timescale;
1936 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
1937 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
1939 GST_OBJECT_UNLOCK (qtmux);
1941 /* inform lower layers of our property wishes, and determine duration.
1942 * Let moov take care of this using its list of traks;
1943 * so that released pads are also included */
1944 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1946 atom_moov_update_timescale (qtmux->moov, timescale);
1947 atom_moov_set_fragmented (qtmux->moov, fragmented);
1949 atom_moov_update_duration (qtmux->moov);
1952 static GstFlowReturn
1953 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
1954 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
1956 guint64 offset = 0, size = 0;
1959 GstFlowReturn ret = GST_FLOW_OK;
1961 guint64 current_time = atoms_get_current_qt_time ();
1963 /* update modification times */
1964 qtmux->moov->mvhd.time_info.modification_time = current_time;
1965 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
1966 GstCollectData *cdata = (GstCollectData *) walk->data;
1967 GstQTPad *qtpad = (GstQTPad *) cdata;
1969 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
1970 qtpad->trak->tkhd.modification_time = current_time;
1973 /* serialize moov */
1976 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1977 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1978 goto serialize_error;
1979 qtmux->last_moov_size = offset;
1981 /* Check we have enough reserved space for this and a Free atom */
1982 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
1983 goto too_small_reserved;
1984 buf = _gst_buffer_new_take_data (data, offset);
1985 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1987 /* If at EOS, this is the final moov, put in the streamheader
1988 * (apparently used by a flumotion util) */
1989 if (qtmux->state == GST_QT_MUX_STATE_EOS)
1990 gst_qt_mux_set_header_on_caps (qtmux, buf);
1993 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1994 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1996 /* Write out a free atom if needed */
1997 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
1998 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
1999 (guint32) (padded_moov_size - offset));
2001 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2008 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2009 ("Not enough free reserved header space"),
2010 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2011 offset, padded_moov_size));
2012 return GST_FLOW_ERROR;
2017 return GST_FLOW_ERROR;
2021 /* either calculates size of extra atoms or pushes them */
2022 static GstFlowReturn
2023 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2027 guint64 loffset = 0, size = 0;
2029 GstFlowReturn ret = GST_FLOW_OK;
2031 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2032 AtomInfo *ainfo = (AtomInfo *) walk->data;
2036 if (!ainfo->copy_data_func (ainfo->atom,
2037 send ? &data : NULL, &size, &loffset))
2038 goto serialize_error;
2043 GST_DEBUG_OBJECT (qtmux,
2044 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2045 GST_FOURCC_ARGS (ainfo->atom->type));
2046 buf = _gst_buffer_new_take_data (data, loffset);
2047 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2048 if (ret != GST_FLOW_OK)
2061 return GST_FLOW_ERROR;
2066 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2068 gboolean seekable = FALSE;
2069 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2071 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2072 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2073 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2075 /* have to assume seeking is not supported if query not handled downstream */
2076 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2079 gst_query_unref (query);
2085 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2088 gboolean fail = FALSE;
2089 AtomFTYP *ftyp = NULL;
2090 GstBuffer *prefix = NULL;
2092 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2093 qtmux->moov_recov_file_path);
2095 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2096 if (qtmux->moov_recov_file == NULL) {
2097 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2098 qtmux->moov_recov_file_path);
2102 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2104 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2105 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2106 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2110 atom_ftyp_free (ftyp);
2112 gst_buffer_unref (prefix);
2114 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2115 GstCollectData *cdata = (GstCollectData *) walk->data;
2116 GstQTPad *qpad = (GstQTPad *) cdata;
2117 /* write info for each stream */
2118 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2120 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2130 fclose (qtmux->moov_recov_file);
2131 qtmux->moov_recov_file = NULL;
2135 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2137 switch (qpad->fourcc) {
2144 return qpad->sample_offset;
2147 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2148 qpad->expected_sample_duration_n,
2149 qpad->expected_sample_duration_d *
2150 atom_trak_get_timescale (qpad->trak));
2157 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2159 switch (qpad->fourcc) {
2161 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2163 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2165 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2167 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2174 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2176 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2178 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2180 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2187 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2189 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2191 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2193 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2200 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2202 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2204 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2206 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2215 guint64 next_sample_offset;
2217 block_idx = prefill_get_block_index (qtmux, qpad);
2218 next_sample_offset =
2219 gst_util_uint64_scale (block_idx + 1,
2220 qpad->expected_sample_duration_d *
2221 atom_trak_get_timescale (qpad->trak),
2222 qpad->expected_sample_duration_n);
2224 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2229 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2237 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2239 switch (qpad->fourcc) {
2246 return gst_util_uint64_scale (qpad->sample_offset + 1,
2247 qpad->expected_sample_duration_d * GST_SECOND,
2248 qpad->expected_sample_duration_n);
2252 guint64 next_sample_offset;
2254 block_idx = prefill_get_block_index (qtmux, qpad);
2255 next_sample_offset =
2256 gst_util_uint64_scale (block_idx + 1,
2257 qpad->expected_sample_duration_d *
2258 atom_trak_get_timescale (qpad->trak),
2259 qpad->expected_sample_duration_n);
2261 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2262 atom_trak_get_timescale (qpad->trak));
2265 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2273 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2278 GstClockTime input_timestamp;
2279 guint64 input_timestamp_distance;
2282 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2284 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2285 qtpad->expected_sample_duration_n,
2286 qtpad->expected_sample_duration_d *
2287 atom_trak_get_timescale (qtpad->trak));
2289 gst_util_uint64_scale (block_idx + 1,
2290 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2291 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2293 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2294 GST_COLLECT_PADS_STATE_EOS)
2295 && gst_adapter_available (qtpad->raw_audio_adapter) <
2296 nsamples * qtpad->sample_size)
2297 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2302 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2303 &input_timestamp_distance);
2304 if (input_timestamp != GST_CLOCK_TIME_NONE)
2306 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2307 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2310 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2311 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2312 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2313 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2314 GST_BUFFER_PTS (buf) = input_timestamp;
2315 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2316 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2318 qtpad->raw_audio_adapter_offset += nsamples;
2320 /* Check if we have yet another block of raw audio in the adapter */
2322 gst_util_uint64_scale (block_idx + 2,
2323 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2324 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2325 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2326 nsamples * qtpad->sample_size) {
2328 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2329 &input_timestamp_distance);
2330 if (input_timestamp != GST_CLOCK_TIME_NONE)
2332 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2333 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2334 qtpad->raw_audio_adapter_pts = input_timestamp;
2336 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2343 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2345 switch (qpad->fourcc) {
2352 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2353 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2360 /* Find the (first) video track and assume that we have to output
2362 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2363 GstCollectData *cdata = (GstCollectData *) walk->data;
2364 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2366 if (tmp_qpad->trak->is_video) {
2367 qpad->expected_sample_duration_n =
2368 tmp_qpad->expected_sample_duration_n;
2369 qpad->expected_sample_duration_d =
2370 tmp_qpad->expected_sample_duration_d;
2376 GST_INFO_OBJECT (qpad->collect.pad,
2377 "Found no video framerate, using 40ms audio buffers");
2378 qpad->expected_sample_duration_n = 25;
2379 qpad->expected_sample_duration_d = 1;
2382 /* Set a prepare_buf_func that ensures this */
2383 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2384 qpad->raw_audio_adapter = gst_adapter_new ();
2385 qpad->raw_audio_adapter_offset = 0;
2386 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2396 find_best_pad_prefill (GstQTMux * qtmux)
2399 GstQTPad *best_pad = NULL;
2401 if (qtmux->current_pad &&
2402 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2403 (qtmux->interleave_bytes == 0
2404 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2405 && (qtmux->interleave_time == 0
2406 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2407 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2408 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2410 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2411 best_pad = qtmux->current_pad;
2413 } else if (qtmux->collect->data->next) {
2414 best_pad = qtmux->current_pad = NULL;
2418 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2420 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2421 GstCollectData *cdata = (GstCollectData *) walk->data;
2422 GstQTPad *qtpad = (GstQTPad *) cdata;
2423 GstClockTime timestamp;
2425 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2428 timestamp = qtpad->total_duration;
2430 if (best_pad == NULL ||
2431 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2433 best_time = timestamp;
2442 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2446 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2448 /* Update expected sample sizes/durations as needed, this is for raw
2449 * audio where samples are actual audio samples. */
2450 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2451 GstCollectData *cdata = (GstCollectData *) walk->data;
2452 GstQTPad *qpad = (GstQTPad *) cdata;
2454 if (!prefill_update_sample_size (qtmux, qpad))
2458 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2459 /* For the first sample check/update timecode as needed. We do that before
2460 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2461 * initial buffer directly, not with last_buf */
2462 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2463 GstCollectData *cdata = (GstCollectData *) walk->data;
2464 GstQTPad *qpad = (GstQTPad *) cdata;
2466 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2467 GstVideoTimeCodeMeta *tc_meta;
2469 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2470 GstVideoTimeCode *tc = &tc_meta->tc;
2472 qpad->tc_trak = atom_trak_new (qtmux->context);
2473 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2475 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2476 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2478 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context, tc);
2480 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2481 qtmux->mdat_size, FALSE, 0);
2483 qpad->tc_pos = qtmux->mdat_size;
2484 qpad->first_tc = gst_video_time_code_copy (tc);
2485 qpad->first_pts = GST_BUFFER_PTS (buffer);
2487 qtmux->current_chunk_offset = -1;
2488 qtmux->current_chunk_size = 0;
2489 qtmux->current_chunk_duration = 0;
2490 qtmux->mdat_size += 4;
2493 gst_buffer_unref (buffer);
2497 while ((qpad = find_best_pad_prefill (qtmux))) {
2498 GstClockTime timestamp, next_timestamp, duration;
2499 guint nsamples, sample_size;
2500 guint64 chunk_offset;
2501 gint64 scaled_duration;
2502 gint64 pts_offset = 0;
2503 gboolean sync = FALSE;
2504 TrakBufferEntryInfo sample_entry;
2506 sample_size = prefill_get_sample_size (qtmux, qpad);
2508 if (sample_size == -1) {
2513 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2515 timestamp = qpad->total_duration;
2516 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2517 duration = next_timestamp - timestamp;
2519 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2520 qpad->first_ts = timestamp;
2521 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2522 qpad->first_dts = timestamp;
2524 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2525 qtmux->current_pad = qpad;
2526 if (qtmux->current_chunk_offset == -1)
2527 qtmux->current_chunk_offset = qtmux->mdat_size;
2529 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2530 qtmux->current_chunk_size = 0;
2531 qtmux->current_chunk_duration = 0;
2533 if (qpad->sample_size)
2534 nsamples = sample_size / qpad->sample_size;
2537 qpad->last_dts = timestamp;
2538 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2539 atom_trak_get_timescale (qpad->trak),
2540 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2541 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2543 qtmux->current_chunk_size += sample_size;
2544 qtmux->current_chunk_duration += duration;
2545 qpad->total_bytes += sample_size;
2547 chunk_offset = qtmux->current_chunk_offset;
2549 /* I-frame only, no frame reordering */
2553 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2554 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2555 qtmux->longest_chunk = qtmux->current_chunk_duration;
2558 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2559 sample_entry.nsamples = nsamples;
2560 sample_entry.delta = scaled_duration / nsamples;
2561 sample_entry.size = sample_size / nsamples;
2562 sample_entry.chunk_offset = chunk_offset;
2563 sample_entry.pts_offset = pts_offset;
2564 sample_entry.sync = sync;
2565 sample_entry.do_pts = TRUE;
2566 g_array_append_val (qpad->samples, sample_entry);
2567 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2568 sample_size / nsamples, chunk_offset, sync, pts_offset);
2570 qpad->total_duration = next_timestamp;
2571 qtmux->mdat_size += sample_size;
2572 qpad->sample_offset += nsamples;
2578 static GstFlowReturn
2579 gst_qt_mux_start_file (GstQTMux * qtmux)
2581 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2582 GstFlowReturn ret = GST_FLOW_OK;
2586 GstClockTime reserved_max_duration;
2587 guint reserved_bytes_per_sec_per_trak;
2590 GST_DEBUG_OBJECT (qtmux, "starting file");
2592 GST_OBJECT_LOCK (qtmux);
2593 reserved_max_duration = qtmux->reserved_max_duration;
2594 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2595 GST_OBJECT_UNLOCK (qtmux);
2597 /* stream-start (FIXME: create id based on input ids) */
2598 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2599 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2601 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2602 /* qtmux has structure with and without variant, remove all but the first */
2603 while (gst_caps_get_size (caps) > 1)
2604 gst_caps_remove_structure (caps, 1);
2605 gst_pad_set_caps (qtmux->srcpad, caps);
2606 gst_caps_unref (caps);
2608 /* Default is 'normal' mode */
2609 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2611 /* Require a sensible fragment duration when muxing
2612 * using the ISML muxer */
2613 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2614 qtmux->fragment_duration == 0)
2617 if (qtmux->fragment_duration > 0) {
2618 if (qtmux->streamable)
2619 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2621 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2622 } else if (qtmux->fast_start) {
2623 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2624 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2625 if (qtmux->reserved_prefill)
2626 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2628 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2631 switch (qtmux->mux_mode) {
2632 case GST_QT_MUX_MODE_MOOV_AT_END:
2633 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2634 /* We have to be able to seek to rewrite the mdat header, or any
2635 * moov atom we write will not be visible in the file, because an
2636 * MDAT with 0 as the size covers the rest of the file. A file
2637 * with no moov is not playable, so error out now. */
2638 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2639 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2640 ("Downstream is not seekable - will not be able to create a playable file"),
2642 return GST_FLOW_ERROR;
2645 case GST_QT_MUX_MODE_FAST_START:
2646 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2647 break; /* Don't need seekability, ignore */
2648 case GST_QT_MUX_MODE_FRAGMENTED:
2649 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2650 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2651 "streamable=false. Will ignore that and create streamable output "
2653 qtmux->streamable = TRUE;
2654 g_object_notify (G_OBJECT (qtmux), "streamable");
2657 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2658 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2659 GST_WARNING_OBJECT (qtmux,
2660 "downstream is not seekable, will not be able "
2661 "to trim samples table at the end if less than reserved-duration is "
2667 /* let downstream know we think in BYTES and expect to do seeking later on */
2668 gst_segment_init (&segment, GST_FORMAT_BYTES);
2669 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2671 GST_OBJECT_LOCK (qtmux);
2673 if (qtmux->timescale == 0) {
2674 guint32 suggested_timescale = 0;
2677 /* Calculate a reasonable timescale for the moov:
2678 * If there is video, it is the biggest video track timescale or an even
2679 * multiple of it if it's smaller than 1800.
2680 * Otherwise it is 1800 */
2681 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2682 GstCollectData *cdata = (GstCollectData *) walk->data;
2683 GstQTPad *qpad = (GstQTPad *) cdata;
2689 if (!qpad->trak->mdia.minf.vmhd)
2692 suggested_timescale =
2693 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
2696 if (suggested_timescale == 0)
2697 suggested_timescale = 1800;
2699 while (suggested_timescale < 1800)
2700 suggested_timescale *= 2;
2702 qtmux->timescale = suggested_timescale;
2705 /* initialize our moov recovery file */
2706 if (qtmux->moov_recov_file_path) {
2707 gst_qt_mux_prepare_moov_recovery (qtmux);
2710 /* Make sure the first time we update the moov, we'll
2711 * include any tagsetter tags */
2712 qtmux->tags_changed = TRUE;
2714 GST_OBJECT_UNLOCK (qtmux);
2717 * send mdat header if already needed, and mark position for later update.
2718 * We don't send ftyp now if we are on fast start mode, because we can
2719 * better fine tune using the information we gather to create the whole moov
2722 switch (qtmux->mux_mode) {
2723 case GST_QT_MUX_MODE_MOOV_AT_END:
2724 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2725 if (ret != GST_FLOW_OK)
2728 /* Store this as the mdat offset for later updating
2729 * when we write the moov */
2730 qtmux->mdat_pos = qtmux->header_size;
2731 /* extended atom in case we go over 4GB while writing and need
2732 * the full 64-bit atom */
2734 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2737 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2738 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2739 if (ret != GST_FLOW_OK)
2742 /* Pad ftyp out to an 8-byte boundary before starting the moov
2743 * ping pong region. It should be well less than 1 disk sector,
2744 * unless there's a bajillion compatible types listed,
2745 * but let's be sure the free atom doesn't cross a sector
2746 * boundary anyway */
2747 if (qtmux->header_size % 8) {
2748 /* Extra 8 bytes for the padding free atom header */
2749 guint padding = (guint) (16 - (qtmux->header_size % 8));
2750 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2752 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2754 if (ret != GST_FLOW_OK)
2758 /* Store this as the moov offset for later updating.
2759 * We record mdat position below */
2760 qtmux->moov_pos = qtmux->header_size;
2762 /* Set up the initial 'ping' state of the ping-pong buffers */
2763 qtmux->reserved_moov_first_active = TRUE;
2765 gst_qt_mux_configure_moov (qtmux);
2766 gst_qt_mux_setup_metadata (qtmux);
2767 /* Empty free atom to begin, starting on an 8-byte boundary */
2768 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2769 if (ret != GST_FLOW_OK)
2771 /* Moov header, not padded yet */
2772 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2773 if (ret != GST_FLOW_OK)
2775 /* The moov we just sent contains the 'base' size of the moov, before
2776 * we put in any time-dependent per-trak data. Use that to make
2777 * a good estimate of how much extra to reserve */
2778 /* Calculate how much space to reserve for our MOOV atom.
2779 * We actually reserve twice that, for ping-pong buffers */
2780 qtmux->base_moov_size = qtmux->last_moov_size;
2781 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2782 qtmux->base_moov_size);
2783 qtmux->reserved_moov_size = qtmux->base_moov_size +
2784 gst_util_uint64_scale (reserved_max_duration,
2785 reserved_bytes_per_sec_per_trak *
2786 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2788 /* Need space for at least 4 atom headers. More really, but
2789 * this as an absolute minimum */
2790 if (qtmux->reserved_moov_size < 4 * 8)
2791 goto reserved_moov_too_small;
2793 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2794 2 * qtmux->reserved_moov_size + 16);
2796 GST_OBJECT_LOCK (qtmux);
2797 qtmux->reserved_duration_remaining =
2798 gst_util_uint64_scale (qtmux->reserved_moov_size -
2799 qtmux->base_moov_size, GST_SECOND,
2800 reserved_bytes_per_sec_per_trak *
2801 atom_moov_get_trak_count (qtmux->moov));
2802 GST_OBJECT_UNLOCK (qtmux);
2804 /* Now that we know how much reserved space is targetted,
2805 * output a free atom to fill the extra reserved */
2806 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2807 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2808 if (ret != GST_FLOW_OK)
2811 /* Then a free atom containing 'pong' buffer, with an
2812 * extra 8 bytes to account for the free atom header itself */
2813 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2814 qtmux->reserved_moov_size + 8, FALSE);
2815 if (ret != GST_FLOW_OK)
2818 /* extra atoms go after the free/moov(s), before the mdat */
2820 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2821 if (ret != GST_FLOW_OK)
2824 qtmux->mdat_pos = qtmux->header_size;
2825 /* extended atom in case we go over 4GB while writing and need
2826 * the full 64-bit atom */
2828 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2831 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2832 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2833 if (ret != GST_FLOW_OK)
2836 /* Store this as the moov offset for later updating.
2837 * We record mdat position below */
2838 qtmux->moov_pos = qtmux->header_size;
2840 if (!gst_qt_mux_prefill_samples (qtmux)) {
2841 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2842 ("Unsupported codecs or configuration for prefill mode"), (NULL));
2844 return GST_FLOW_ERROR;
2847 gst_qt_mux_update_global_statistics (qtmux);
2848 gst_qt_mux_configure_moov (qtmux);
2849 gst_qt_mux_update_edit_lists (qtmux);
2850 gst_qt_mux_setup_metadata (qtmux);
2852 /* Moov header with pre-filled samples */
2853 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2854 if (ret != GST_FLOW_OK)
2857 /* last_moov_size now contains the full size of the moov, moov_pos the
2858 * position. This allows us to rewrite it in the very end as needed */
2859 qtmux->reserved_moov_size =
2860 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
2862 /* Send an additional free atom at the end so we definitely have space
2863 * to rewrite the moov header at the end and remove the samples that
2864 * were not actually written */
2866 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2867 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
2868 if (ret != GST_FLOW_OK)
2871 /* extra atoms go after the free/moov(s), before the mdat */
2873 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2874 if (ret != GST_FLOW_OK)
2877 qtmux->mdat_pos = qtmux->header_size;
2879 /* And now send the mdat header */
2881 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
2882 qtmux->mdat_size, TRUE, FALSE);
2884 /* chunks position is set relative to the first byte of the
2885 * MDAT atom payload. Set the overall offset into the file */
2886 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
2891 gst_segment_init (&segment, GST_FORMAT_BYTES);
2892 segment.start = qtmux->moov_pos;
2893 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2895 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2896 if (ret != GST_FLOW_OK)
2899 segment.start = qtmux->header_size;
2900 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2903 qtmux->current_chunk_size = 0;
2904 qtmux->current_chunk_duration = 0;
2905 qtmux->current_chunk_offset = -1;
2906 qtmux->mdat_size = 0;
2907 qtmux->current_pad = NULL;
2908 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
2910 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2911 GstCollectData *cdata = (GstCollectData *) walk->data;
2912 GstQTPad *qtpad = (GstQTPad *) cdata;
2914 qtpad->total_bytes = 0;
2915 qtpad->total_duration = 0;
2916 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
2917 qtpad->last_dts = GST_CLOCK_TIME_NONE;
2918 qtpad->sample_offset = 0;
2922 case GST_QT_MUX_MODE_FAST_START:
2923 GST_OBJECT_LOCK (qtmux);
2924 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2925 if (!qtmux->fast_start_file)
2927 GST_OBJECT_UNLOCK (qtmux);
2928 /* send a dummy buffer for preroll */
2929 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2931 case GST_QT_MUX_MODE_FRAGMENTED:
2932 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2933 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2934 if (ret != GST_FLOW_OK)
2936 /* store the moov pos so we can update the duration later
2937 * in non-streamable mode */
2938 qtmux->moov_pos = qtmux->header_size;
2940 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2941 qtmux->fragment_duration);
2942 /* also used as snapshot marker to indicate fragmented file */
2943 qtmux->fragment_sequence = 1;
2944 /* prepare moov and/or tags */
2945 gst_qt_mux_configure_moov (qtmux);
2946 gst_qt_mux_setup_metadata (qtmux);
2947 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2948 if (ret != GST_FLOW_OK)
2952 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2953 if (ret != GST_FLOW_OK)
2955 /* prepare index if not streamable */
2956 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2957 qtmux->mfra = atom_mfra_new (qtmux->context);
2965 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2966 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2967 return GST_FLOW_ERROR;
2969 reserved_moov_too_small:
2971 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2972 ("Not enough reserved space for creating headers"), (NULL));
2973 return GST_FLOW_ERROR;
2977 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2978 (("Could not open temporary file \"%s\""),
2979 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2980 GST_OBJECT_UNLOCK (qtmux);
2981 return GST_FLOW_ERROR;
2985 static GstFlowReturn
2986 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2988 GstFlowReturn ret = GST_FLOW_OK;
2991 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2992 GstCollectData *cdata = (GstCollectData *) walk->data;
2993 GstQTPad *qtpad = (GstQTPad *) cdata;
2995 /* avoid add_buffer complaining if not negotiated
2996 * in which case no buffers either, so skipping */
2997 if (!qtpad->fourcc) {
2998 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2999 GST_PAD_NAME (qtpad->collect.pad));
3003 /* send last buffer; also flushes possibly queued buffers/ts */
3004 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3005 GST_PAD_NAME (qtpad->collect.pad));
3006 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3007 if (ret != GST_FLOW_OK) {
3008 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3009 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3010 gst_flow_get_name (ret));
3018 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3022 /* for setting some subtitles fields */
3023 guint max_width = 0;
3024 guint max_height = 0;
3026 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3028 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3029 GstCollectData *cdata = (GstCollectData *) walk->data;
3030 GstQTPad *qtpad = (GstQTPad *) cdata;
3032 if (!qtpad->fourcc) {
3033 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3034 GST_PAD_NAME (qtpad->collect.pad));
3038 /* having flushed above, can check for buffers now */
3039 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3040 /* determine max stream duration */
3041 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3042 || qtpad->last_dts > qtmux->last_dts) {
3043 qtmux->last_dts = qtpad->last_dts;
3045 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3046 || qtpad->first_ts < qtmux->first_ts) {
3047 qtmux->first_ts = qtpad->first_ts;
3051 /* subtitles need to know the video width/height,
3052 * it is stored shifted 16 bits to the left according to the
3054 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3055 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3057 /* update average bitrate of streams if needed */
3059 guint32 avgbitrate = 0;
3060 guint32 maxbitrate = qtpad->max_bitrate;
3062 if (qtpad->avg_bitrate)
3063 avgbitrate = qtpad->avg_bitrate;
3064 else if (qtpad->total_duration > 0)
3065 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3066 8 * GST_SECOND, qtpad->total_duration);
3068 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3072 /* need to update values on subtitle traks now that we know the
3073 * max width and height */
3074 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3075 GstCollectData *cdata = (GstCollectData *) walk->data;
3076 GstQTPad *qtpad = (GstQTPad *) cdata;
3078 if (!qtpad->fourcc) {
3079 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3080 GST_PAD_NAME (qtpad->collect.pad));
3084 if (qtpad->fourcc == FOURCC_tx3g) {
3085 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3090 /* Called after gst_qt_mux_update_global_statistics() updates the
3091 * first_ts tracking, to create/set edit lists for delayed streams */
3093 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3097 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3098 GST_TIME_ARGS (qtmux->first_ts));
3099 /* add/update EDTSs for late streams. configure_moov will have
3100 * set the trak durations above by summing the sample tables,
3101 * here we extend that if needing to insert an empty segment */
3102 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3103 GstCollectData *cdata = (GstCollectData *) walk->data;
3104 GstQTPad *qtpad = (GstQTPad *) cdata;
3106 atom_trak_edts_clear (qtpad->trak);
3108 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3109 guint32 lateness = 0;
3110 guint32 duration = qtpad->trak->tkhd.duration;
3113 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3118 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3119 lateness = gst_util_uint64_scale_round (diff,
3120 qtmux->timescale, GST_SECOND);
3123 GST_DEBUG_OBJECT (qtmux,
3124 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3125 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3127 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3128 (guint32) (1 * 65536.0));
3132 /* Always write an edit list for the whole track. In general this is not
3133 * necessary except for the case of having a gap or DTS adjustment but
3134 * it allows to give the whole track's duration in the usually more
3135 * accurate media timescale
3138 GstClockTime ctts = 0;
3139 guint32 media_start;
3141 if (qtpad->first_ts > qtpad->first_dts)
3142 ctts = qtpad->first_ts - qtpad->first_dts;
3144 media_start = gst_util_uint64_scale_round (ctts,
3145 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3147 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3148 * is empty because there's no gap added above, this call
3149 * will not replace index 1, it will create the entry at index 0.
3150 * Luckily, that's exactly what we want here */
3151 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3152 (guint32) (1 * 65536.0));
3155 /* need to add the empty time to the trak duration */
3156 duration += lateness;
3157 qtpad->trak->tkhd.duration = duration;
3158 if (qtpad->tc_trak) {
3159 qtpad->tc_trak->tkhd.duration = duration;
3160 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3163 /* And possibly grow the moov duration */
3164 if (duration > qtmux->moov->mvhd.time_info.duration) {
3165 qtmux->moov->mvhd.time_info.duration = duration;
3166 qtmux->moov->mvex.mehd.fragment_duration = duration;
3172 static GstFlowReturn
3173 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3178 guint64 offset = qtpad->tc_pos;
3179 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3181 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3184 g_assert (qtpad->tc_pos != -1);
3186 gst_segment_init (&segment, GST_FORMAT_BYTES);
3187 segment.start = offset;
3188 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3190 buf = gst_buffer_new_and_alloc (4);
3191 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3193 GST_WRITE_UINT32_BE (map.data,
3194 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3195 gst_buffer_unmap (buf, &map);
3197 /* Reset this value, so the timecode won't be re-rewritten */
3200 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3203 static GstFlowReturn
3204 gst_qt_mux_stop_file (GstQTMux * qtmux)
3206 gboolean ret = GST_FLOW_OK;
3207 guint64 offset = 0, size = 0;
3208 gboolean large_file;
3211 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3213 /* pushing last buffers for each pad */
3214 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3217 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3218 /* Streamable mode; no need to write duration or MFRA */
3219 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3223 gst_qt_mux_update_global_statistics (qtmux);
3224 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3225 GstQTPad *qtpad = (GstQTPad *) walk->data;
3227 if (qtpad->tc_pos != -1) {
3228 /* File is being stopped and timecode hasn't been updated. Update it now
3229 * with whatever we have */
3230 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3231 if (ret != GST_FLOW_OK)
3236 switch (qtmux->mux_mode) {
3237 case GST_QT_MUX_MODE_FRAGMENTED:{
3239 guint8 *data = NULL;
3243 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3244 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3245 goto serialize_error;
3246 buf = _gst_buffer_new_take_data (data, offset);
3247 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3248 if (ret != GST_FLOW_OK)
3251 /* only mvex duration is updated,
3252 * mvhd should be consistent with empty moov
3253 * (but TODO maybe some clients do not handle that well ?) */
3254 qtmux->moov->mvex.mehd.fragment_duration =
3255 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3256 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3257 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3258 /* seek and rewrite the header */
3259 gst_segment_init (&segment, GST_FORMAT_BYTES);
3260 segment.start = qtmux->moov_pos;
3261 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3262 /* no need to seek back */
3263 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3265 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3266 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3267 if (G_UNLIKELY (ret != GST_FLOW_OK))
3269 /* Finalise by writing the final size into the mdat. Up until now
3270 * it's been 0, which means 'rest of the file'
3271 * No need to seek back after this, we won't write any more */
3272 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3273 qtmux->mdat_size, NULL, TRUE);
3275 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3277 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3279 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3280 GstCollectData *cdata = (GstCollectData *) walk->data;
3281 GstQTPad *qpad = (GstQTPad *) cdata;
3282 const TrakBufferEntryInfo *sample_entry;
3284 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3286 /* Get the block index of the last sample we wrote, not of the next
3287 * sample we would write */
3288 block_idx = prefill_get_block_index (qtmux, qpad);
3289 g_assert (block_idx > 0);
3293 &g_array_index (qpad->samples, TrakBufferEntryInfo, block_idx);
3298 guint64 nsamples = 0;
3301 n = atom_array_get_len (&stbl->stts.entries);
3302 for (i = 0; i < n; i++) {
3303 entry = &atom_array_index (&stbl->stts.entries, i);
3304 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3305 entry->sample_count = qpad->sample_offset - nsamples;
3306 stbl->stts.entries.len = i + 1;
3309 nsamples += entry->sample_count;
3316 g_assert (stbl->stsz.entries.len == 0);
3317 stbl->stsz.table_size = qpad->sample_offset;
3323 guint64 nsamples = 0;
3324 gint chunk_index = 0;
3326 n = stbl->stco64.entries.len;
3327 for (i = 0; i < n; i++) {
3328 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3330 if (*entry == sample_entry->chunk_offset) {
3331 stbl->stco64.entries.len = i + 1;
3332 chunk_index = i + 1;
3337 g_assert (chunk_index > 0);
3339 n = stbl->stsc.entries.len;
3340 for (i = 0; i < n; i++) {
3341 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3343 if (entry->first_chunk >= chunk_index)
3348 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3350 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3351 i - 1).samples_per_chunk;
3357 STSCEntry *prev_entry =
3358 &atom_array_index (&stbl->stsc.entries, i - 1);
3361 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3362 if (qpad->sample_offset - nsamples > 0) {
3363 stbl->stsc.entries.len = i;
3364 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3365 qpad->sample_offset - nsamples);
3367 stbl->stsc.entries.len = i;
3368 stbl->stco64.entries.len--;
3371 /* Everything in a single chunk */
3372 stbl->stsc.entries.len = 0;
3373 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3374 qpad->sample_offset);
3381 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3382 AtomTREX *trex = walk2->data;
3384 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3385 trex->track_ID = next_track_id;
3390 qpad->trak->tkhd.track_ID = next_track_id++;
3393 qtmux->moov->mvhd.next_track_id = next_track_id;
3395 gst_qt_mux_update_global_statistics (qtmux);
3396 gst_qt_mux_configure_moov (qtmux);
3398 gst_qt_mux_update_edit_lists (qtmux);
3400 /* Check if any gap edit lists were added. We don't have any space
3401 * reserved for this in the moov and the pre-finalized moov would have
3402 * broken A/V synchronization. Error out here now
3404 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3405 GstCollectData *cdata = (GstCollectData *) walk->data;
3406 GstQTPad *qpad = (GstQTPad *) cdata;
3408 if (qpad->trak->edts
3409 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3410 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3411 ("Can't support gaps in prefill mode"));
3413 return GST_FLOW_ERROR;
3417 gst_qt_mux_setup_metadata (qtmux);
3418 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3423 gst_segment_init (&segment, GST_FORMAT_BYTES);
3424 segment.start = qtmux->moov_pos;
3425 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3428 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3430 if (ret != GST_FLOW_OK)
3433 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3435 gst_qt_mux_send_free_atom (qtmux, NULL,
3436 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3439 if (ret != GST_FLOW_OK)
3443 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3444 qtmux->mdat_size, NULL, FALSE);
3451 /* Moov-at-end or fast-start mode from here down */
3452 gst_qt_mux_configure_moov (qtmux);
3454 gst_qt_mux_update_edit_lists (qtmux);
3456 /* tags into file metadata */
3457 gst_qt_mux_setup_metadata (qtmux);
3459 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3461 switch (qtmux->mux_mode) {
3462 case GST_QT_MUX_MODE_FAST_START:{
3463 /* if faststart, update the offset of the atoms in the movie with the offset
3464 * that the movie headers before mdat will cause.
3465 * Also, send the ftyp */
3468 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3469 if (ret != GST_FLOW_OK) {
3472 /* copy into NULL to obtain size */
3473 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3474 goto serialize_error;
3475 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3477 offset += qtmux->header_size + (large_file ? 16 : 8);
3479 /* sum up with the extra atoms size */
3480 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3481 if (ret != GST_FLOW_OK)
3486 offset = qtmux->header_size;
3490 /* Now that we know the size of moov + extra atoms, we can adjust
3491 * the chunk offsets stored into the moov */
3492 atom_moov_chunks_set_offset (qtmux->moov, offset);
3494 /* write out moov and extra atoms */
3495 /* note: as of this point, we no longer care about tracking written data size,
3496 * since there is no more use for it anyway */
3497 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3498 if (ret != GST_FLOW_OK)
3502 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3503 if (ret != GST_FLOW_OK)
3506 switch (qtmux->mux_mode) {
3507 case GST_QT_MUX_MODE_MOOV_AT_END:
3509 /* mdat needs update iff not using faststart */
3510 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3511 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3512 qtmux->mdat_size, NULL, FALSE);
3513 /* note; no seeking back to the end of file is done,
3514 * since we no longer write anything anyway */
3517 case GST_QT_MUX_MODE_FAST_START:
3519 /* send mdat atom and move buffered data into it */
3520 /* mdat_size = accumulated (buffered data) */
3521 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3523 if (ret != GST_FLOW_OK)
3525 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3526 if (ret != GST_FLOW_OK)
3531 g_assert_not_reached ();
3539 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3540 ("Failed to serialize moov"));
3541 return GST_FLOW_ERROR;
3545 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3546 return GST_FLOW_ERROR;
3550 static GstFlowReturn
3551 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3552 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3553 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3555 GstFlowReturn ret = GST_FLOW_OK;
3557 /* setup if needed */
3558 if (G_UNLIKELY (!pad->traf || force))
3562 /* flush pad fragment if threshold reached,
3563 * or at new keyframe if we should be minding those in the first place */
3564 if (G_UNLIKELY (force || (sync && pad->sync) ||
3565 pad->fragment_duration < (gint64) delta)) {
3567 guint64 size = 0, offset = 0;
3568 guint8 *data = NULL;
3570 guint i, total_size;
3572 /* now we know where moof ends up, update offset in tfra */
3574 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3576 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3577 /* takes ownership */
3578 atom_moof_add_traf (moof, pad->traf);
3580 atom_moof_copy_data (moof, &data, &size, &offset);
3581 buffer = _gst_buffer_new_take_data (data, offset);
3582 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3583 gst_buffer_get_size (buffer));
3584 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3586 /* and actual data */
3588 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3590 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3593 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3594 atom_array_get_len (&pad->fragment_buffers), total_size);
3595 if (ret == GST_FLOW_OK)
3596 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3598 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3599 if (G_LIKELY (ret == GST_FLOW_OK))
3600 ret = gst_qt_mux_send_buffer (qtmux,
3601 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3604 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3607 atom_array_clear (&pad->fragment_buffers);
3608 atom_moof_free (moof);
3609 qtmux->fragment_sequence++;
3614 if (G_UNLIKELY (!pad->traf)) {
3615 GST_LOG_OBJECT (qtmux, "setting up new fragment");
3616 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3617 atom_array_init (&pad->fragment_buffers, 512);
3618 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3619 atom_trak_get_timescale (pad->trak), 1000);
3621 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3622 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3623 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3625 atom_traf_set_base_decode_time (pad->traf, dts);
3628 /* add buffer and metadata */
3629 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3631 atom_array_append (&pad->fragment_buffers, buf, 256);
3632 pad->fragment_duration -= delta;
3635 guint32 sn = atom_traf_get_sample_num (pad->traf);
3637 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3638 atom_tfra_add_entry (pad->tfra, dts, sn);
3641 if (G_UNLIKELY (force))
3647 /* Here's the clever bit of robust recording: Updating the moov
3648 * header is done using a ping-pong scheme inside 2 blocks of size
3649 * 'reserved_moov_size' at the start of the file, in such a way that the
3650 * file on-disk is always valid if interrupted.
3651 * Inside the reserved space, we have 2 pairs of free + moov atoms
3652 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3653 * at offset "reserved_moov_size".
3655 * 1. Free-A has 0 size payload, moov-A immediately after is
3656 * active/current, and is padded with an internal Free atom to
3657 * end at reserved_space/2. Free-B is at reserved_space/2, sized
3658 * to cover the remaining free space (including moov-B).
3659 * 2. We write moov-B (which is invisible inside free-B), and pad it to
3660 * end at the end of free space. Then, we update free-A to size
3661 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
3662 * free-B header, and makes moov-B active.
3663 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
3664 * Change the size of free-A to make moov-A active again.
3665 * 4. Rinse and repeat.
3668 static GstFlowReturn
3669 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
3673 guint64 freeA_offset;
3674 guint32 new_freeA_size;
3675 guint64 new_moov_offset;
3677 /* Update moov info, then seek and rewrite the MOOV atom */
3678 gst_qt_mux_update_global_statistics (qtmux);
3679 gst_qt_mux_configure_moov (qtmux);
3681 gst_qt_mux_update_edit_lists (qtmux);
3683 /* tags into file metadata */
3684 gst_qt_mux_setup_metadata (qtmux);
3686 /* chunks position is set relative to the first byte of the
3687 * MDAT atom payload. Set the overall offset into the file */
3688 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3690 /* Calculate which moov to rewrite. qtmux->moov_pos points to
3691 * the start of the free-A header */
3692 freeA_offset = qtmux->moov_pos;
3693 if (qtmux->reserved_moov_first_active) {
3694 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
3695 /* After this, freeA will include itself, moovA, plus the freeB
3697 new_freeA_size = qtmux->reserved_moov_size + 16;
3699 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
3702 /* the moov we update is after free-A, calculate its offset */
3703 new_moov_offset = freeA_offset + new_freeA_size;
3705 /* Swap ping-pong cadence marker */
3706 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
3708 /* seek and rewrite the MOOV atom */
3709 gst_segment_init (&segment, GST_FORMAT_BYTES);
3710 segment.start = new_moov_offset;
3711 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3714 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3716 if (ret != GST_FLOW_OK)
3719 /* Update the estimated recording space remaining, based on amount used so
3720 * far and duration muxed so far */
3721 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
3722 GstClockTime remain;
3723 GstClockTime time_muxed = qtmux->last_dts;
3726 gst_util_uint64_scale (qtmux->reserved_moov_size -
3727 qtmux->last_moov_size, time_muxed,
3728 qtmux->last_moov_size - qtmux->base_moov_size);
3729 /* Always under-estimate slightly, so users
3730 * have time to stop muxing before we run out */
3731 if (remain < GST_SECOND / 2)
3734 remain -= GST_SECOND / 2;
3736 GST_INFO_OBJECT (qtmux,
3737 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
3738 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
3739 qtmux->reserved_moov_size, qtmux->last_moov_size,
3740 GST_TIME_ARGS (qtmux->last_dts),
3741 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
3743 GST_OBJECT_LOCK (qtmux);
3744 qtmux->reserved_duration_remaining = remain;
3745 qtmux->muxed_since_last_update = 0;
3746 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
3747 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
3748 GST_OBJECT_UNLOCK (qtmux);
3752 /* Now update the moov-A size. Don't pass offset, since we don't need
3753 * send_free_atom() to seek for us - all our callers seek back to
3754 * where they need after this, or they don't need it */
3755 gst_segment_init (&segment, GST_FORMAT_BYTES);
3756 segment.start = freeA_offset;
3757 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3759 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3764 static GstFlowReturn
3765 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3768 GstFlowReturn flow_ret;
3770 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3772 GST_OBJECT_LOCK (qtmux);
3773 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3774 GST_OBJECT_UNLOCK (qtmux);
3778 /* Update if position is > the threshold or there's been no update yet */
3779 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3780 (position <= qtmux->last_moov_update ||
3781 (position - qtmux->last_moov_update) <
3782 qtmux->reserved_moov_update_period)) {
3783 /* Update the offset of how much we've muxed, so the
3784 * report of remaining space keeps counting down */
3785 if (position > qtmux->last_moov_update &&
3786 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3787 GST_LOG_OBJECT (qtmux,
3788 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3789 qtmux->muxed_since_last_update);
3790 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3792 GST_OBJECT_UNLOCK (qtmux);
3793 return GST_FLOW_OK; /* No update needed yet */
3796 qtmux->last_moov_update = position;
3797 GST_OBJECT_UNLOCK (qtmux);
3799 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3800 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3801 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3803 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3804 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3807 /* Seek back to previous position */
3808 gst_segment_init (&segment, GST_FORMAT_BYTES);
3809 segment.start = mdat_offset;
3810 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3815 static GstFlowReturn
3816 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3817 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3818 gint64 last_dts, gint64 scaled_duration, guint sample_size,
3819 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3821 GstFlowReturn ret = GST_FLOW_OK;
3823 /* note that a new chunk is started each time (not fancy but works) */
3824 if (qtmux->moov_recov_file) {
3825 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3826 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3827 do_pts, pts_offset)) {
3828 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3829 "recovery file, disabling recovery");
3830 fclose (qtmux->moov_recov_file);
3831 qtmux->moov_recov_file = NULL;
3835 switch (qtmux->mux_mode) {
3836 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3837 const TrakBufferEntryInfo *sample_entry;
3838 guint64 block_idx = prefill_get_block_index (qtmux, pad);
3840 if (block_idx >= pad->samples->len) {
3841 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3842 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
3843 block_idx, pad->samples->len));
3844 gst_buffer_unref (buffer);
3845 return GST_FLOW_ERROR;
3848 /* Check if all values are as expected */
3850 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
3852 /* Allow +/- 1 difference for the scaled_duration to allow
3853 * for some rounding errors
3855 if (sample_entry->nsamples != nsamples
3856 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
3857 || sample_entry->size != sample_size
3858 || sample_entry->chunk_offset != chunk_offset
3859 || sample_entry->pts_offset != pts_offset
3860 || sample_entry->sync != sync) {
3861 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3862 ("Unexpected values in sample %" G_GUINT64_FORMAT,
3863 pad->sample_offset + 1));
3864 gst_buffer_unref (buffer);
3865 return GST_FLOW_ERROR;
3868 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3871 case GST_QT_MUX_MODE_MOOV_AT_END:
3872 case GST_QT_MUX_MODE_FAST_START:
3873 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3874 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3875 sample_size, chunk_offset, sync, pts_offset);
3876 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3877 /* Check if it's time to re-write the headers in robust-recording mode */
3878 if (ret == GST_FLOW_OK
3879 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3880 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3882 case GST_QT_MUX_MODE_FRAGMENTED:
3883 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3884 /* ensure that always sync samples are marked as such */
3885 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3886 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3887 sample_size, !pad->sync || sync, pts_offset);
3894 static GstFlowReturn
3895 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
3896 GstBuffer * buf, GstFlowReturn ret)
3898 GstVideoTimeCodeMeta *tc_meta;
3899 GstVideoTimeCode *tc;
3902 guint32 frames_since_daily_jam;
3903 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3905 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3908 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
3911 tc_meta = gst_buffer_get_video_time_code_meta (buf);
3917 /* This means we never got a timecode before */
3918 if (pad->first_tc == NULL) {
3919 #ifndef GST_DISABLE_GST_DEBUG
3920 gchar *tc_str = gst_video_time_code_to_string (tc);
3921 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
3924 g_assert (pad->tc_trak == NULL);
3925 pad->first_tc = gst_video_time_code_copy (tc);
3926 /* If frames are out of order, the frame we're currently getting might
3927 * not be the first one. Just write a 0 timecode for now and wait
3928 * until we receive a timecode that's lower than the current one */
3929 if (pad->is_out_of_order) {
3930 pad->first_pts = GST_BUFFER_PTS (buf);
3931 frames_since_daily_jam = 0;
3932 /* Position to rewrite */
3933 pad->tc_pos = qtmux->mdat_size;
3935 frames_since_daily_jam =
3936 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
3937 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3939 /* Write the timecode trak now */
3940 pad->tc_trak = atom_trak_new (qtmux->context);
3941 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
3943 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
3944 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
3946 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context, pad->first_tc);
3948 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3949 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3950 g_assert (szret == 4);
3952 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
3953 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3955 /* Need to reset the current chunk (of the previous pad) here because
3956 * some other data was written now above, and the pad has to start a
3958 qtmux->current_chunk_offset = -1;
3959 qtmux->current_chunk_size = 0;
3960 qtmux->current_chunk_duration = 0;
3961 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
3962 frames_since_daily_jam =
3963 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
3964 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3966 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3967 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3968 g_assert (szret == 4);
3970 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3973 qtmux->current_chunk_offset = -1;
3974 qtmux->current_chunk_size = 0;
3975 qtmux->current_chunk_duration = 0;
3976 } else if (pad->is_out_of_order) {
3977 /* Check for a lower timecode than the one stored */
3978 g_assert (pad->tc_trak != NULL);
3979 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
3980 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
3981 gst_video_time_code_free (pad->first_tc);
3982 pad->first_tc = gst_video_time_code_copy (tc);
3985 guint64 bk_size = qtmux->mdat_size;
3987 /* If this frame's DTS is after the first PTS received, it means
3988 * we've already received the first frame to be presented. Otherwise
3989 * the decoder would need to go back in time */
3990 gst_qt_mux_update_timecode (qtmux, pad);
3992 /* Reset writing position */
3993 gst_segment_init (&segment, GST_FORMAT_BYTES);
3994 segment.start = bk_size;
3995 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4003 * Here we push the buffer and update the tables in the track atoms
4005 static GstFlowReturn
4006 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4008 GstBuffer *last_buf = NULL;
4009 GstClockTime duration;
4010 guint nsamples, sample_size;
4011 guint64 chunk_offset;
4012 gint64 last_dts, scaled_duration;
4013 gint64 pts_offset = 0;
4014 gboolean sync = FALSE;
4015 GstFlowReturn ret = GST_FLOW_OK;
4019 goto not_negotiated;
4021 /* if this pad has a prepare function, call it */
4022 if (pad->prepare_buf_func != NULL) {
4025 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4026 if (buf && !new_buf)
4031 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4032 if (ret != GST_FLOW_OK) {
4034 gst_buffer_unref (buf);
4038 last_buf = pad->last_buf;
4039 pad->last_buf = buf;
4041 if (last_buf == NULL) {
4042 #ifndef GST_DISABLE_GST_DEBUG
4044 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4045 "received NULL buffer, doing nothing",
4046 GST_PAD_NAME (pad->collect.pad));
4048 GST_LOG_OBJECT (qtmux,
4049 "Pad %s has no previous buffer stored, storing now",
4050 GST_PAD_NAME (pad->collect.pad));
4056 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4059 /* if this is the first buffer, store the timestamp */
4060 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4061 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4062 pad->first_ts = GST_BUFFER_PTS (last_buf);
4063 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4064 pad->first_ts = GST_BUFFER_DTS (last_buf);
4067 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4068 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4069 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4070 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4073 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4074 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4076 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4077 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4078 pad->first_ts = pad->first_dts = 0;
4080 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4081 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4082 GST_TIME_ARGS (pad->first_ts));
4085 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4086 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4087 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4088 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4089 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4090 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4091 pad->last_buf = buf = gst_buffer_make_writable (buf);
4092 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4095 buffer_size = gst_buffer_get_size (last_buf);
4097 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4098 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4099 guint fill_size = required_buffer_size - buffer_size;
4103 if (required_buffer_size < buffer_size) {
4104 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4105 ("Sample size %u bigger than expected maximum %u", buffer_size,
4106 required_buffer_size));
4110 if (fill_size > 0) {
4111 GST_DEBUG_OBJECT (qtmux,
4112 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4113 required_buffer_size);
4114 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4115 gst_memory_map (mem, &map, GST_MAP_WRITE);
4116 memset (map.data, 0, map.size);
4117 gst_memory_unmap (mem, &map);
4118 last_buf = gst_buffer_make_writable (last_buf);
4119 gst_buffer_append_memory (last_buf, mem);
4120 buffer_size = required_buffer_size;
4124 /* duration actually means time delta between samples, so we calculate
4125 * the duration based on the difference in DTS or PTS, falling back
4126 * to DURATION if the other two don't exist, such as with the last
4127 * sample before EOS. Or use 0 if nothing else is available */
4128 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4129 duration = GST_BUFFER_DURATION (last_buf);
4133 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4134 && GST_BUFFER_DTS_IS_VALID (last_buf))
4135 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4136 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4137 && GST_BUFFER_PTS_IS_VALID (last_buf))
4138 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4141 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4142 GST_DEBUG_OBJECT (qtmux,
4143 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4144 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4145 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4146 qtmux->current_chunk_size,
4147 GST_TIME_ARGS (qtmux->current_chunk_duration));
4148 qtmux->current_pad = pad;
4149 if (qtmux->current_chunk_offset == -1)
4150 qtmux->current_chunk_offset = qtmux->mdat_size;
4152 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4153 qtmux->current_chunk_size = 0;
4154 qtmux->current_chunk_duration = 0;
4157 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4158 atom_trak_get_timescale (pad->trak), GST_SECOND);
4160 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4161 if (pad->sample_size && !qtmux->fragment_sequence) {
4162 GstClockTime expected_timestamp;
4164 /* Constant size packets: usually raw audio (with many samples per
4165 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4167 sample_size = pad->sample_size;
4168 if (buffer_size % sample_size != 0)
4169 goto fragmented_sample;
4171 /* note: qt raw audio storage warps it implicitly into a timewise
4172 * perfect stream, discarding buffer times.
4173 * If the difference between the current PTS and the expected one
4174 * becomes too big, we error out: there was a gap and we have no way to
4175 * represent that, causing A/V sync to be off */
4176 expected_timestamp =
4177 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4178 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4179 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4180 expected_timestamp) > qtmux->max_raw_audio_drift)
4181 goto raw_audio_timestamp_drift;
4183 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4184 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4185 atom_trak_get_timescale (pad->trak), GST_SECOND);
4186 duration = GST_BUFFER_DURATION (last_buf);
4188 nsamples = buffer_size / sample_size;
4190 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4191 atom_trak_get_timescale (pad->trak));
4194 /* timescale = samplerate */
4195 scaled_duration = 1;
4197 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4198 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4201 sample_size = buffer_size;
4202 if ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4203 || GST_BUFFER_DTS_IS_VALID (last_buf)) {
4205 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4206 pad->last_dts = GST_BUFFER_DTS (buf);
4208 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4210 if ((gint64) (pad->last_dts) < 0) {
4211 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4212 atom_trak_get_timescale (pad->trak), GST_SECOND);
4214 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4215 atom_trak_get_timescale (pad->trak), GST_SECOND);
4217 scaled_duration = scaled_dts - last_dts;
4218 last_dts = scaled_dts;
4220 /* first convert intended timestamp (in GstClockTime resolution) to
4221 * trak timescale, then derive delta;
4222 * this ensures sums of (scale)delta add up to converted timestamp,
4223 * which only deviates at most 1/scale from timestamp itself */
4224 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4225 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4226 pad->last_dts += duration;
4230 /* for computing the avg bitrate */
4231 pad->total_bytes += buffer_size;
4232 pad->total_duration += duration;
4233 qtmux->current_chunk_size += buffer_size;
4234 qtmux->current_chunk_duration += duration;
4236 chunk_offset = qtmux->current_chunk_offset;
4238 GST_LOG_OBJECT (qtmux,
4239 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4240 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4241 GST_LOG_OBJECT (qtmux,
4242 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4243 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4244 nsamples, scaled_duration, sample_size, chunk_offset);
4246 /* might be a sync sample */
4248 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4249 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4250 GST_PAD_NAME (pad->collect.pad));
4254 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4255 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4256 atom_trak_get_timescale (pad->trak), GST_SECOND);
4258 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4259 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4262 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4263 atom_trak_get_timescale (pad->trak), GST_SECOND);
4265 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4266 " timebase_dts: %d pts_offset: %d",
4267 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4268 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4269 (int) (last_dts), (int) (pts_offset));
4271 if (GST_CLOCK_TIME_IS_VALID (duration)
4272 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4273 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4274 GST_DEBUG_OBJECT (qtmux,
4275 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4276 GST_TIME_ARGS (qtmux->current_chunk_duration),
4277 GST_PAD_NAME (pad->collect.pad));
4278 qtmux->longest_chunk = qtmux->current_chunk_duration;
4281 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4282 const TrakBufferEntryInfo *sample_entry;
4283 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4285 if (block_idx >= pad->samples->len) {
4286 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4287 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4288 block_idx, pad->samples->len));
4292 /* Check if all values are as expected */
4294 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4296 if (chunk_offset < sample_entry->chunk_offset) {
4297 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4298 GstBuffer *fill_buf;
4300 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4301 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4303 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4304 if (ret != GST_FLOW_OK)
4306 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4307 qtmux->current_chunk_size = buffer_size;
4308 qtmux->current_chunk_duration = duration;
4309 } else if (chunk_offset != sample_entry->chunk_offset) {
4310 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4311 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4312 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4317 /* now we go and register this buffer/sample all over */
4318 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4319 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4320 chunk_offset, sync, TRUE, pts_offset);
4321 pad->sample_offset += nsamples;
4323 /* if this is sparse and we have a next buffer, check if there is any gap
4324 * between them to insert an empty sample */
4325 if (pad->sparse && buf) {
4326 if (pad->create_empty_buffer) {
4327 GstBuffer *empty_buf;
4328 gint64 empty_duration =
4329 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4330 gint64 empty_duration_scaled;
4332 empty_buf = pad->create_empty_buffer (pad, empty_duration);
4334 empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
4335 atom_trak_get_timescale (pad->trak), GST_SECOND);
4337 pad->total_bytes += gst_buffer_get_size (empty_buf);
4338 pad->total_duration += duration;
4341 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4342 last_dts + scaled_duration, empty_duration_scaled,
4343 gst_buffer_get_size (empty_buf), chunk_offset, sync, TRUE, 0);
4345 /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
4346 g_assert_not_reached ();
4347 GST_WARNING_OBJECT (qtmux,
4348 "no empty buffer creation function found for pad %s",
4349 GST_PAD_NAME (pad->collect.pad));
4360 gst_buffer_unref (last_buf);
4361 return GST_FLOW_ERROR;
4365 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4366 ("Audio buffer contains fragmented sample."));
4369 raw_audio_timestamp_drift:
4371 /* TODO: Could in theory be implemented with edit lists */
4372 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4373 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4374 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4375 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4376 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4378 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4383 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4388 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4389 ("format wasn't negotiated before buffer flow on pad %s",
4390 GST_PAD_NAME (pad->collect.pad)));
4392 gst_buffer_unref (buf);
4393 return GST_FLOW_NOT_NEGOTIATED;
4398 * DTS running time can be negative. There is no way to represent that in
4399 * MP4 however, thus we need to offset DTS so that it starts from 0.
4402 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4403 GstCollectData * cdata, GstBuffer ** buf)
4408 pts = GST_BUFFER_PTS (*buf);
4409 dts = GST_COLLECT_PADS_DTS (cdata);
4411 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4412 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4413 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4415 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4416 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4417 pad->dts_adjustment = -dts;
4419 pad->dts_adjustment = 0;
4422 if (pad->dts_adjustment > 0) {
4423 *buf = gst_buffer_make_writable (*buf);
4425 dts += pad->dts_adjustment;
4427 if (GST_CLOCK_TIME_IS_VALID (pts))
4428 pts += pad->dts_adjustment;
4430 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4431 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4436 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4440 GST_BUFFER_PTS (*buf) = pts;
4441 GST_BUFFER_DTS (*buf) = dts;
4443 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4444 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4449 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4452 GstQTPad *best_pad = NULL;
4454 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4455 guint64 smallest_offset = G_MAXUINT64;
4456 guint64 chunk_offset = 0;
4458 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4459 GstCollectData *cdata = (GstCollectData *) walk->data;
4460 GstQTPad *qtpad = (GstQTPad *) cdata;
4461 const TrakBufferEntryInfo *sample_entry;
4462 guint64 block_idx, current_block_idx;
4463 guint64 chunk_offset_offset = 0;
4464 GstBuffer *tmp_buf =
4465 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4467 /* Check for EOS pads and just skip them */
4468 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4469 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4472 gst_buffer_unref (tmp_buf);
4474 /* Find the exact offset where the next sample of this track is supposed
4475 * to be written at */
4476 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4478 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4479 while (block_idx > 0) {
4480 const TrakBufferEntryInfo *tmp =
4481 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4483 if (tmp->chunk_offset != sample_entry->chunk_offset)
4485 chunk_offset_offset += tmp->size * tmp->nsamples;
4489 /* Except for the previously selected pad being EOS we always have
4490 * qtmux->current_chunk_offset + qtmux->current_chunk_size
4492 * sample_entry->chunk_offset + chunk_offset_offset
4493 * for the best pad. Instead of checking that, we just return the
4494 * pad that has the smallest offset for the next to-be-written sample.
4496 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4497 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4499 chunk_offset = sample_entry->chunk_offset;
4503 if (chunk_offset != qtmux->current_chunk_offset) {
4504 qtmux->current_pad = NULL;
4510 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4511 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4512 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4513 && (qtmux->interleave_time == 0
4514 || qtmux->current_chunk_duration <= qtmux->interleave_time)
4515 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4516 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4517 GstBuffer *tmp_buf =
4518 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4520 if (tmp_buf || qtmux->current_pad->last_buf) {
4521 best_pad = qtmux->current_pad;
4523 gst_buffer_unref (tmp_buf);
4524 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4525 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4527 } else if (qtmux->collect->data->next) {
4528 /* Only switch pads if we have more than one, otherwise
4529 * we can just put everything into a single chunk and save
4530 * a few bytes of offsets
4532 if (qtmux->current_pad)
4533 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4534 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4535 best_pad = qtmux->current_pad = NULL;
4539 GstClockTime best_time = GST_CLOCK_TIME_NONE;
4541 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4542 GstCollectData *cdata = (GstCollectData *) walk->data;
4543 GstQTPad *qtpad = (GstQTPad *) cdata;
4545 GstClockTime timestamp;
4547 tmp_buf = gst_collect_pads_peek (pads, cdata);
4549 /* This one is newly EOS now, finish it for real */
4550 if (qtpad->last_buf) {
4551 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4556 if (qtpad->last_buf)
4557 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4559 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4562 if (best_pad == NULL ||
4563 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4565 best_time = timestamp;
4569 gst_buffer_unref (tmp_buf);
4573 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4574 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4576 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4583 static GstFlowReturn
4584 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4586 GstFlowReturn ret = GST_FLOW_OK;
4587 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4588 GstQTPad *best_pad = NULL;
4590 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4591 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4594 qtmux->state = GST_QT_MUX_STATE_DATA;
4597 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4598 return GST_FLOW_EOS;
4600 best_pad = find_best_pad (qtmux, pads);
4602 /* clipping already converted to running time */
4603 if (best_pad != NULL) {
4604 GstBuffer *buf = NULL;
4606 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4607 best_pad->raw_audio_adapter == NULL ||
4608 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4609 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4611 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4612 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4615 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
4616 (GstCollectData *) best_pad, &buf);
4618 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
4620 qtmux->state = GST_QT_MUX_STATE_EOS;
4621 ret = gst_qt_mux_stop_file (qtmux);
4622 if (ret == GST_FLOW_OK) {
4623 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
4624 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
4627 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
4628 gst_flow_get_name (ret));
4636 check_field (GQuark field_id, const GValue * value, gpointer user_data)
4638 GstStructure *structure = (GstStructure *) user_data;
4639 const GValue *other = gst_structure_id_get_value (structure, field_id);
4642 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
4646 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
4649 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
4650 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
4652 return gst_structure_foreach (sub_s, check_field, sup_s);
4656 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4658 GstPad *pad = qtpad->collect.pad;
4659 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4660 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4661 GstStructure *structure;
4662 const gchar *mimetype;
4663 gint rate, channels;
4664 const GValue *value = NULL;
4665 const GstBuffer *codec_data = NULL;
4666 GstQTMuxFormat format;
4667 AudioSampleEntry entry = { 0, };
4668 AtomInfo *ext_atom = NULL;
4669 gint constant_size = 0;
4670 const gchar *stream_format;
4672 /* does not go well to renegotiate stream mid-way, unless
4673 * the old caps are a subset of the new one (this means upstream
4674 * added more info to the caps, as both should be 'fixed' caps) */
4675 if (qtpad->fourcc) {
4676 GstCaps *current_caps;
4678 current_caps = gst_pad_get_current_caps (pad);
4679 g_assert (caps != NULL);
4681 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4682 gst_caps_unref (current_caps);
4683 goto refuse_renegotiation;
4685 GST_DEBUG_OBJECT (qtmux,
4686 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4687 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4688 gst_caps_unref (current_caps);
4693 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4694 GST_DEBUG_PAD_NAME (pad), caps);
4696 qtpad->prepare_buf_func = NULL;
4698 format = qtmux_klass->format;
4699 structure = gst_caps_get_structure (caps, 0);
4700 mimetype = gst_structure_get_name (structure);
4703 if (!gst_structure_get_int (structure, "channels", &channels) ||
4704 !gst_structure_get_int (structure, "rate", &rate)) {
4709 value = gst_structure_get_value (structure, "codec_data");
4711 codec_data = gst_value_get_buffer (value);
4713 qtpad->is_out_of_order = FALSE;
4715 /* set common properties */
4716 entry.sample_rate = rate;
4717 entry.channels = channels;
4719 entry.sample_size = 16;
4720 /* this is the typical compressed case */
4721 if (format == GST_QT_MUX_FORMAT_QT) {
4723 entry.compression_id = -2;
4726 /* now map onto a fourcc, and some extra properties */
4727 if (strcmp (mimetype, "audio/mpeg") == 0) {
4728 gint mpegversion = 0, mpegaudioversion = 0;
4731 gst_structure_get_int (structure, "mpegversion", &mpegversion);
4732 switch (mpegversion) {
4734 gst_structure_get_int (structure, "layer", &layer);
4735 gst_structure_get_int (structure, "mpegaudioversion",
4739 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
4740 if (format == GST_QT_MUX_FORMAT_QT)
4741 entry.fourcc = FOURCC__mp3;
4743 entry.fourcc = FOURCC_mp4a;
4745 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
4746 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4747 qtpad->max_bitrate);
4750 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
4751 entry.samples_per_packet = 384;
4752 } else if (layer == 2) {
4753 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
4754 entry.samples_per_packet = 1152;
4756 g_warn_if_fail (layer == 3);
4757 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
4759 entry.bytes_per_sample = 2;
4763 /* check stream-format */
4764 stream_format = gst_structure_get_string (structure, "stream-format");
4765 if (stream_format) {
4766 if (strcmp (stream_format, "raw") != 0) {
4767 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
4768 "please use 'raw'", stream_format);
4772 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
4776 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
4777 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
4782 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
4783 /* warn if not Low Complexity profile */
4786 GST_WARNING_OBJECT (qtmux,
4787 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
4791 entry.fourcc = FOURCC_mp4a;
4793 if (format == GST_QT_MUX_FORMAT_QT)
4794 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
4795 qtpad->avg_bitrate, qtpad->max_bitrate);
4798 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
4799 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4800 qtpad->max_bitrate);
4805 } else if (strcmp (mimetype, "audio/AMR") == 0) {
4806 entry.fourcc = FOURCC_samr;
4807 entry.sample_size = 16;
4808 entry.samples_per_packet = 160;
4809 entry.bytes_per_sample = 2;
4810 ext_atom = build_amr_extension ();
4811 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
4812 entry.fourcc = FOURCC_sawb;
4813 entry.sample_size = 16;
4814 entry.samples_per_packet = 320;
4815 entry.bytes_per_sample = 2;
4816 ext_atom = build_amr_extension ();
4817 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
4820 gst_audio_info_init (&info);
4821 if (!gst_audio_info_from_caps (&info, caps))
4824 /* spec has no place for a distinction in these */
4825 if (info.finfo->width != info.finfo->depth) {
4826 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
4830 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
4831 if (info.finfo->endianness == G_LITTLE_ENDIAN)
4832 entry.fourcc = FOURCC_sowt;
4833 else if (info.finfo->endianness == G_BIG_ENDIAN)
4834 entry.fourcc = FOURCC_twos;
4836 entry.fourcc = FOURCC_sowt;
4837 /* maximum backward compatibility; only new version for > 16 bit */
4838 if (info.finfo->depth <= 16)
4840 /* not compressed in any case */
4841 entry.compression_id = 0;
4842 /* QT spec says: max at 16 bit even if sample size were actually larger,
4843 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
4844 entry.sample_size = info.finfo->depth;
4845 entry.bytes_per_sample = info.finfo->depth / 8;
4846 entry.samples_per_packet = 1;
4847 entry.bytes_per_packet = info.finfo->depth / 8;
4848 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
4850 if (info.finfo->width == 8 && info.finfo->depth == 8) {
4851 /* fall back to old 8-bit version */
4852 entry.fourcc = FOURCC_raw_;
4854 entry.compression_id = 0;
4855 entry.sample_size = 8;
4857 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
4861 constant_size = (info.finfo->depth / 8) * info.channels;
4862 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
4863 entry.fourcc = FOURCC_alaw;
4864 entry.samples_per_packet = 1023;
4865 entry.bytes_per_sample = 2;
4866 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
4867 entry.fourcc = FOURCC_ulaw;
4868 entry.samples_per_packet = 1023;
4869 entry.bytes_per_sample = 2;
4870 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
4872 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
4873 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
4876 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
4878 entry.fourcc = MS_WAVE_FOURCC (0x11);
4879 /* 4 byte header per channel (including one sample). 2 samples per byte
4880 remaining. Simplifying gives the following (samples per block per
4882 entry.samples_per_packet = 2 * blocksize / channels - 7;
4883 entry.bytes_per_sample = 2;
4885 entry.bytes_per_frame = blocksize;
4886 entry.bytes_per_packet = blocksize / channels;
4887 /* ADPCM has constant size packets */
4889 /* TODO: I don't really understand why this helps, but it does! Constant
4890 * size and compression_id of -2 seem to be incompatible, and other files
4891 * in the wild use this too. */
4892 entry.compression_id = -1;
4894 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
4895 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
4896 GstBuffer *codec_config;
4900 entry.fourcc = FOURCC_alac;
4901 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
4902 /* let's check if codec data already comes with 'alac' atom prefix */
4903 if (!codec_data || (len = map.size) < 28) {
4904 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
4905 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
4908 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
4911 gst_buffer_copy_region ((GstBuffer *) codec_data,
4912 GST_BUFFER_COPY_MEMORY, 8, len);
4914 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
4916 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
4918 /* does not look good, but perhaps some trailing unneeded stuff */
4919 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
4921 if (format == GST_QT_MUX_FORMAT_QT)
4922 ext_atom = build_mov_alac_extension (codec_config);
4924 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
4925 /* set some more info */
4926 gst_buffer_map (codec_config, &map, GST_MAP_READ);
4927 entry.bytes_per_sample = 2;
4928 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
4929 gst_buffer_unmap (codec_config, &map);
4930 gst_buffer_unref (codec_config);
4931 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
4932 entry.fourcc = FOURCC_ac_3;
4934 /* Fixed values according to TS 102 366 but it also mentions that
4935 * they should be ignored */
4937 entry.sample_size = 16;
4939 /* AC-3 needs an extension atom but its data can only be obtained from
4940 * the stream itself. Abuse the prepare_buf_func so we parse a frame
4941 * and get the needed data */
4942 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
4943 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
4944 /* Based on the specification defined in:
4945 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
4946 guint8 channels, mapping_family, stream_count, coupled_count;
4950 guint8 channel_mapping[256];
4951 const GValue *streamheader;
4952 const GValue *first_element;
4955 entry.fourcc = FOURCC_opus;
4956 entry.sample_size = 16;
4958 streamheader = gst_structure_get_value (structure, "streamheader");
4959 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
4960 gst_value_array_get_size (streamheader) != 0) {
4961 first_element = gst_value_array_get_value (streamheader, 0);
4962 header = gst_value_get_buffer (first_element);
4963 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
4964 &mapping_family, &stream_count, &coupled_count, channel_mapping,
4965 &pre_skip, &output_gain)) {
4966 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
4970 GST_WARNING_OBJECT (qtmux,
4971 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
4973 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
4974 &mapping_family, &stream_count, &coupled_count,
4976 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
4983 entry.channels = channels;
4984 ext_atom = build_opus_extension (rate, channels, mapping_family,
4985 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
4991 /* ok, set the pad info accordingly */
4992 qtpad->fourcc = entry.fourcc;
4993 qtpad->sample_size = constant_size;
4995 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
4996 qtmux->context, &entry,
4997 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
4998 ext_atom, constant_size);
5000 gst_object_unref (qtmux);
5006 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5007 GST_PAD_NAME (pad), caps);
5008 gst_object_unref (qtmux);
5011 refuse_renegotiation:
5013 GST_WARNING_OBJECT (qtmux,
5014 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5015 GST_PAD_NAME (pad), caps);
5016 gst_object_unref (qtmux);
5022 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5024 GstPad *pad = qtpad->collect.pad;
5025 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5026 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5027 GstStructure *structure;
5028 const gchar *mimetype;
5029 gint width, height, depth = -1;
5030 gint framerate_num, framerate_den;
5032 const GValue *value = NULL;
5033 const GstBuffer *codec_data = NULL;
5034 VisualSampleEntry entry = { 0, };
5035 GstQTMuxFormat format;
5036 AtomInfo *ext_atom = NULL;
5037 GList *ext_atom_list = NULL;
5038 gboolean sync = FALSE;
5039 int par_num, par_den;
5041 /* does not go well to renegotiate stream mid-way, unless
5042 * the old caps are a subset of the new one (this means upstream
5043 * added more info to the caps, as both should be 'fixed' caps) */
5044 if (qtpad->fourcc) {
5045 GstCaps *current_caps;
5047 current_caps = gst_pad_get_current_caps (pad);
5048 g_assert (caps != NULL);
5050 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5051 gst_caps_unref (current_caps);
5052 goto refuse_renegotiation;
5054 GST_DEBUG_OBJECT (qtmux,
5055 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5056 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5057 gst_caps_unref (current_caps);
5062 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5063 GST_DEBUG_PAD_NAME (pad), caps);
5065 qtpad->prepare_buf_func = NULL;
5067 format = qtmux_klass->format;
5068 structure = gst_caps_get_structure (caps, 0);
5069 mimetype = gst_structure_get_name (structure);
5071 /* required parts */
5072 if (!gst_structure_get_int (structure, "width", &width) ||
5073 !gst_structure_get_int (structure, "height", &height))
5078 /* works as a default timebase */
5079 framerate_num = 10000;
5081 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5083 gst_structure_get_int (structure, "depth", &depth);
5084 value = gst_structure_get_value (structure, "codec_data");
5086 codec_data = gst_value_get_buffer (value);
5090 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5093 qtpad->is_out_of_order = FALSE;
5095 /* bring frame numerator into a range that ensures both reasonable resolution
5096 * as well as a fair duration */
5097 qtpad->expected_sample_duration_n = framerate_num;
5098 qtpad->expected_sample_duration_d = framerate_den;
5099 rate = qtmux->trak_timescale ?
5100 qtmux->trak_timescale : atom_framerate_to_timescale (framerate_num,
5102 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5105 /* set common properties */
5106 entry.width = width;
5107 entry.height = height;
5108 entry.par_n = par_num;
5109 entry.par_d = par_den;
5110 /* should be OK according to qt and iso spec, override if really needed */
5111 entry.color_table_id = -1;
5112 entry.frame_count = 1;
5115 /* sync entries by default */
5118 /* now map onto a fourcc, and some extra properties */
5119 if (strcmp (mimetype, "video/x-raw") == 0) {
5120 const gchar *format;
5122 const GstVideoFormatInfo *vinfo;
5124 format = gst_structure_get_string (structure, "format");
5125 fmt = gst_video_format_from_string (format);
5126 vinfo = gst_video_format_get_info (fmt);
5129 case GST_VIDEO_FORMAT_UYVY:
5132 entry.fourcc = FOURCC_2vuy;
5133 entry.depth = depth;
5136 case GST_VIDEO_FORMAT_v210:
5139 entry.fourcc = FOURCC_v210;
5140 entry.depth = depth;
5144 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5145 entry.fourcc = FOURCC_raw_;
5146 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5151 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5153 if (format == GST_QT_MUX_FORMAT_QT)
5154 entry.fourcc = FOURCC_h263;
5156 entry.fourcc = FOURCC_s263;
5157 ext_atom = build_h263_extension ();
5158 if (ext_atom != NULL)
5159 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5160 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5161 strcmp (mimetype, "video/mpeg") == 0) {
5164 if (strcmp (mimetype, "video/x-divx") == 0) {
5165 gst_structure_get_int (structure, "divxversion", &version);
5166 version = version == 5 ? 1 : 0;
5168 gst_structure_get_int (structure, "mpegversion", &version);
5169 version = version == 4 ? 1 : 0;
5172 entry.fourcc = FOURCC_mp4v;
5174 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5175 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5176 qtpad->max_bitrate);
5177 if (ext_atom != NULL)
5178 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5180 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5181 "output might not play in Apple QuickTime (try global-headers?)");
5183 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5185 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5189 entry.fourcc = FOURCC_avc1;
5191 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5192 if (ext_atom != NULL)
5193 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5194 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5195 if (ext_atom != NULL)
5196 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5197 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5198 const gchar *format;
5201 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5205 format = gst_structure_get_string (structure, "stream-format");
5206 if (strcmp (format, "hvc1") == 0)
5207 entry.fourcc = FOURCC_hvc1;
5208 else if (strcmp (format, "hev1") == 0)
5209 entry.fourcc = FOURCC_hev1;
5211 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5212 if (ext_atom != NULL)
5213 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5215 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5216 if (ext_atom != NULL)
5217 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5219 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5221 const GstBuffer *seqh = NULL;
5222 const GValue *seqh_value;
5225 gst_structure_get_int (structure, "svqversion", &version);
5227 entry.fourcc = FOURCC_SVQ3;
5231 seqh_value = gst_structure_get_value (structure, "seqh");
5233 seqh = gst_value_get_buffer (seqh_value);
5234 ext_atom = build_SMI_atom (seqh);
5236 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5239 /* we need to add the gamma anyway because quicktime might crash
5240 * when it doesn't find it */
5241 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5242 /* it seems that using 0 here makes it ignored */
5245 ext_atom = build_gama_atom (gamma);
5247 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5249 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5250 "a bug at http://bugzilla.gnome.org", version);
5252 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5254 gboolean pal = TRUE;
5257 if (framerate_num != 25 || framerate_den != 1)
5259 gst_structure_get_int (structure, "dvversion", &version);
5260 /* fall back to typical one */
5266 entry.fourcc = FOURCC_dvcp;
5268 entry.fourcc = FOURCC_dvc_;
5272 entry.fourcc = FOURCC_dv5p;
5274 entry.fourcc = FOURCC_dv5n;
5277 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5280 } else if (strcmp (mimetype, "image/jpeg") == 0) {
5281 entry.fourcc = FOURCC_jpeg;
5283 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5284 strcmp (mimetype, "image/x-jpc") == 0) {
5285 const gchar *colorspace;
5286 const GValue *cmap_array;
5287 const GValue *cdef_array;
5290 if (strcmp (mimetype, "image/x-jpc") == 0) {
5291 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5294 gst_structure_get_int (structure, "num-components", &ncomp);
5295 cmap_array = gst_structure_get_value (structure, "component-map");
5296 cdef_array = gst_structure_get_value (structure, "channel-definitions");
5299 entry.fourcc = FOURCC_mjp2;
5302 colorspace = gst_structure_get_string (structure, "colorspace");
5305 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5306 cdef_array)) != NULL) {
5307 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5309 ext_atom = build_jp2x_extension (codec_data);
5311 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5313 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5316 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5317 entry.fourcc = FOURCC_VP80;
5319 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5320 entry.fourcc = FOURCC_drac;
5321 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5324 gst_structure_get_uint (structure, "format", &fourcc);
5325 entry.fourcc = fourcc;
5326 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5329 gst_structure_get_uint (structure, "format", &fourcc);
5330 entry.fourcc = fourcc;
5331 } else if (strcmp (mimetype, "video/x-prores") == 0) {
5332 const gchar *variant;
5334 variant = gst_structure_get_string (structure, "variant");
5335 if (!variant || !g_strcmp0 (variant, "standard"))
5336 entry.fourcc = FOURCC_apcn;
5337 else if (!g_strcmp0 (variant, "lt"))
5338 entry.fourcc = FOURCC_apcs;
5339 else if (!g_strcmp0 (variant, "hq"))
5340 entry.fourcc = FOURCC_apch;
5341 else if (!g_strcmp0 (variant, "proxy"))
5342 entry.fourcc = FOURCC_apco;
5343 else if (!g_strcmp0 (variant, "4444"))
5344 entry.fourcc = FOURCC_ap4h;
5345 else if (!g_strcmp0 (variant, "4444xq"))
5346 entry.fourcc = FOURCC_ap4x;
5350 if (!qtmux->interleave_time_set)
5351 qtmux->interleave_time = 500 * GST_MSECOND;
5352 if (!qtmux->interleave_bytes_set)
5353 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5354 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5355 entry.fourcc = FOURCC_cfhd;
5362 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5363 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5365 GstVideoColorimetry colorimetry;
5367 s = gst_structure_get_string (structure, "colorimetry");
5368 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5370 build_colr_extension (&colorimetry,
5371 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5373 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5377 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5378 || strcmp (mimetype, "image/x-j2c") == 0
5379 || strcmp (mimetype, "image/x-jpc") == 0) {
5381 GstVideoInterlaceMode interlace_mode;
5382 GstVideoFieldOrder field_order;
5385 if (strcmp (mimetype, "image/x-j2c") == 0 ||
5386 strcmp (mimetype, "image/x-jpc") == 0) {
5389 gst_structure_get_int (structure, "fields", &fields);
5392 s = gst_structure_get_string (structure, "interlace-mode");
5394 interlace_mode = gst_video_interlace_mode_from_string (s);
5398 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5399 GST_VIDEO_INTERLACE_MODE_MIXED;
5401 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5402 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5403 s = gst_structure_get_string (structure, "field-order");
5405 field_order = gst_video_field_order_from_string (s);
5408 ext_atom = build_fiel_extension (interlace_mode, field_order);
5410 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5414 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5415 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5416 /* The 'clap' extension is also defined for MP4 but inventing values in
5417 * general seems a bit tricky for this one. We only write it for
5418 * SD resolution in MOV, where it is a requirement.
5419 * The same goes for the 'tapt' extension, just that it is not defined for
5420 * MP4 and only for MOV
5422 gint dar_num, dar_den;
5423 gint clef_width, clef_height, prof_width;
5424 gint clap_width_n, clap_width_d, clap_height;
5428 /* First, guess display aspect ratio based on pixel aspect ratio,
5429 * width and height. We assume that display aspect ratio is either
5432 approx_dar = (gdouble) (width * par_num) / (height * par_den);
5433 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5436 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5440 dar_num = width * par_num;
5441 dar_den = height * par_den;
5442 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5447 /* Then, calculate clean-aperture values (clap and clef)
5448 * using the guessed DAR.
5450 clef_height = clap_height = (height == 486 ? 480 : height);
5451 clef_width = gst_util_uint64_scale (clef_height,
5452 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5453 prof_width = gst_util_uint64_scale (width,
5454 par_num * G_GUINT64_CONSTANT (65536), par_den);
5455 clap_width_n = clap_height * dar_num * par_den;
5456 clap_width_d = dar_den * par_num;
5457 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5458 clap_width_n /= cdiv;
5459 clap_width_d /= cdiv;
5461 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5462 height << 16, width << 16, height << 16);
5463 qtpad->trak->tapt = ext_atom;
5465 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5466 clap_height, 1, 0, 1, 0, 1);
5468 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5471 /* ok, set the pad info accordingly */
5472 qtpad->fourcc = entry.fourcc;
5475 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5476 qtmux->context, &entry, rate, ext_atom_list);
5477 if (strcmp (mimetype, "video/x-prores") == 0) {
5478 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5479 const gchar *compressor = NULL;
5480 mp4v->spatial_quality = 0x3FF;
5481 mp4v->temporal_quality = 0;
5482 mp4v->vendor = FOURCC_appl;
5483 mp4v->horizontal_resolution = 72 << 16;
5484 mp4v->vertical_resolution = 72 << 16;
5485 mp4v->depth = (entry.fourcc == FOURCC_ap4h
5486 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5488 /* Set compressor name, required by some software */
5489 switch (entry.fourcc) {
5491 compressor = "Apple ProRes 422";
5494 compressor = "Apple ProRes 422 LT";
5497 compressor = "Apple ProRes 422 HQ";
5500 compressor = "Apple ProRes 422 Proxy";
5503 compressor = "Apple ProRes 4444";
5506 compressor = "Apple ProRes 4444 XQ";
5510 strcpy ((gchar *) mp4v->compressor + 1, compressor);
5511 mp4v->compressor[0] = strlen (compressor);
5515 gst_object_unref (qtmux);
5521 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5522 GST_PAD_NAME (pad), caps);
5523 gst_object_unref (qtmux);
5526 refuse_renegotiation:
5528 GST_WARNING_OBJECT (qtmux,
5529 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5531 gst_object_unref (qtmux);
5537 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5539 GstPad *pad = qtpad->collect.pad;
5540 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5541 GstStructure *structure;
5542 SubtitleSampleEntry entry = { 0, };
5544 /* does not go well to renegotiate stream mid-way, unless
5545 * the old caps are a subset of the new one (this means upstream
5546 * added more info to the caps, as both should be 'fixed' caps) */
5547 if (qtpad->fourcc) {
5548 GstCaps *current_caps;
5550 current_caps = gst_pad_get_current_caps (pad);
5551 g_assert (caps != NULL);
5553 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5554 gst_caps_unref (current_caps);
5555 goto refuse_renegotiation;
5557 GST_DEBUG_OBJECT (qtmux,
5558 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5559 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5560 gst_caps_unref (current_caps);
5565 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5566 GST_DEBUG_PAD_NAME (pad), caps);
5568 /* subtitles default */
5569 subtitle_sample_entry_init (&entry);
5570 qtpad->is_out_of_order = FALSE;
5571 qtpad->sync = FALSE;
5572 qtpad->sparse = TRUE;
5573 qtpad->prepare_buf_func = NULL;
5575 structure = gst_caps_get_structure (caps, 0);
5577 if (gst_structure_has_name (structure, "text/x-raw")) {
5578 const gchar *format = gst_structure_get_string (structure, "format");
5579 if (format && strcmp (format, "utf8") == 0) {
5580 entry.fourcc = FOURCC_tx3g;
5581 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
5582 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
5589 qtpad->fourcc = entry.fourcc;
5591 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
5592 qtmux->context, &entry);
5594 gst_object_unref (qtmux);
5600 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5601 GST_PAD_NAME (pad), caps);
5602 gst_object_unref (qtmux);
5605 refuse_renegotiation:
5607 GST_WARNING_OBJECT (qtmux,
5608 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5610 gst_object_unref (qtmux);
5616 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
5617 GstEvent * event, gpointer user_data)
5620 guint32 avg_bitrate = 0, max_bitrate = 0;
5621 GstPad *pad = data->pad;
5622 gboolean ret = TRUE;
5624 qtmux = GST_QT_MUX_CAST (user_data);
5625 switch (GST_EVENT_TYPE (event)) {
5626 case GST_EVENT_CAPS:
5629 GstQTPad *collect_pad;
5631 gst_event_parse_caps (event, &caps);
5633 /* find stream data */
5634 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5635 g_assert (collect_pad);
5636 g_assert (collect_pad->set_caps);
5638 ret = collect_pad->set_caps (collect_pad, caps);
5639 gst_event_unref (event);
5643 case GST_EVENT_TAG:{
5645 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
5646 GstTagMergeMode mode;
5648 GstQTPad *collect_pad;
5650 GST_OBJECT_LOCK (qtmux);
5651 mode = gst_tag_setter_get_tag_merge_mode (setter);
5652 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5654 gst_event_parse_tag (event, &list);
5655 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
5656 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
5658 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
5659 gst_tag_setter_merge_tags (setter, list, mode);
5660 qtmux->tags_changed = TRUE;
5662 if (!collect_pad->tags)
5663 collect_pad->tags = gst_tag_list_new_empty ();
5664 gst_tag_list_insert (collect_pad->tags, list, mode);
5665 collect_pad->tags_changed = TRUE;
5667 GST_OBJECT_UNLOCK (qtmux);
5669 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
5670 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
5671 GstQTPad *qtpad = gst_pad_get_element_private (pad);
5674 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
5675 qtpad->avg_bitrate = avg_bitrate;
5676 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
5677 qtpad->max_bitrate = max_bitrate;
5680 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
5681 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
5683 GstQTPad *qtpad = gst_pad_get_element_private (pad);
5686 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
5687 qtpad->trak->mdia.mdhd.language_code =
5688 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
5689 (iso_code[2] - 0x60);
5695 gst_event_unref (event);
5705 return gst_collect_pads_event_default (pads, data, event, FALSE);
5711 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
5713 GstQTMux *mux = GST_QT_MUX_CAST (element);
5716 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
5718 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
5719 GstQTPad *qtpad = (GstQTPad *) walk->data;
5720 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
5721 if (qtpad->collect.pad == pad) {
5722 /* this is it, remove */
5723 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
5724 gst_element_remove_pad (element, pad);
5729 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
5730 mux->current_pad = NULL;
5731 mux->current_chunk_size = 0;
5732 mux->current_chunk_duration = 0;
5735 gst_collect_pads_remove_pad (mux->collect, pad);
5737 if (mux->sinkpads == NULL) {
5738 /* No more outstanding request pads, reset our counters */
5739 mux->video_pads = 0;
5740 mux->audio_pads = 0;
5741 mux->subtitle_pads = 0;
5746 gst_qt_mux_request_new_pad (GstElement * element,
5747 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
5749 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
5750 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
5751 GstQTPad *collect_pad;
5753 GstQTPadSetCapsFunc setcaps_func;
5756 gboolean lock = TRUE;
5758 if (templ->direction != GST_PAD_SINK)
5759 goto wrong_direction;
5761 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
5764 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
5765 setcaps_func = gst_qt_mux_audio_sink_set_caps;
5766 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
5767 name = g_strdup (req_name);
5769 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
5771 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
5772 setcaps_func = gst_qt_mux_video_sink_set_caps;
5773 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
5774 name = g_strdup (req_name);
5776 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
5778 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
5779 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
5780 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
5781 name = g_strdup (req_name);
5783 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
5787 goto wrong_template;
5789 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
5791 /* create pad and add to collections */
5792 newpad = gst_pad_new_from_template (templ, name);
5794 collect_pad = (GstQTPad *)
5795 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
5796 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
5798 gst_qt_mux_pad_reset (collect_pad);
5799 collect_pad->trak = atom_trak_new (qtmux->context);
5800 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
5802 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
5804 /* set up pad functions */
5805 collect_pad->set_caps = setcaps_func;
5807 gst_pad_set_active (newpad, TRUE);
5808 gst_element_add_pad (element, newpad);
5815 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
5820 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
5825 GST_WARNING_OBJECT (qtmux, "This is not our template!");
5831 gst_qt_mux_get_property (GObject * object,
5832 guint prop_id, GValue * value, GParamSpec * pspec)
5834 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
5836 GST_OBJECT_LOCK (qtmux);
5838 case PROP_MOVIE_TIMESCALE:
5839 g_value_set_uint (value, qtmux->timescale);
5841 case PROP_TRAK_TIMESCALE:
5842 g_value_set_uint (value, qtmux->trak_timescale);
5845 g_value_set_boolean (value, qtmux->guess_pts);
5847 #ifndef GST_REMOVE_DEPRECATED
5848 case PROP_DTS_METHOD:
5849 g_value_set_enum (value, qtmux->dts_method);
5852 case PROP_FAST_START:
5853 g_value_set_boolean (value, qtmux->fast_start);
5855 case PROP_FAST_START_TEMP_FILE:
5856 g_value_set_string (value, qtmux->fast_start_file_path);
5858 case PROP_MOOV_RECOV_FILE:
5859 g_value_set_string (value, qtmux->moov_recov_file_path);
5861 case PROP_FRAGMENT_DURATION:
5862 g_value_set_uint (value, qtmux->fragment_duration);
5864 case PROP_STREAMABLE:
5865 g_value_set_boolean (value, qtmux->streamable);
5867 case PROP_RESERVED_MAX_DURATION:
5868 g_value_set_uint64 (value, qtmux->reserved_max_duration);
5870 case PROP_RESERVED_DURATION_REMAINING:
5871 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
5872 g_value_set_uint64 (value, qtmux->reserved_max_duration);
5874 GstClockTime remaining = qtmux->reserved_duration_remaining;
5876 /* Report the remaining space as the calculated remaining, minus
5877 * however much we've muxed since the last update */
5878 if (remaining > qtmux->muxed_since_last_update)
5879 remaining -= qtmux->muxed_since_last_update;
5882 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
5883 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
5884 remaining, qtmux->reserved_duration_remaining,
5885 qtmux->muxed_since_last_update);
5886 g_value_set_uint64 (value, remaining);
5889 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
5890 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
5892 case PROP_RESERVED_BYTES_PER_SEC:
5893 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
5895 case PROP_RESERVED_PREFILL:
5896 g_value_set_boolean (value, qtmux->reserved_prefill);
5898 case PROP_INTERLEAVE_BYTES:
5899 g_value_set_uint64 (value, qtmux->interleave_bytes);
5901 case PROP_INTERLEAVE_TIME:
5902 g_value_set_uint64 (value, qtmux->interleave_time);
5904 case PROP_MAX_RAW_AUDIO_DRIFT:
5905 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
5908 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5911 GST_OBJECT_UNLOCK (qtmux);
5915 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
5919 g_free (qtmux->fast_start_file_path);
5920 qtmux->fast_start_file_path = NULL;
5922 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
5923 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
5928 gst_qt_mux_set_property (GObject * object,
5929 guint prop_id, const GValue * value, GParamSpec * pspec)
5931 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
5933 GST_OBJECT_LOCK (qtmux);
5935 case PROP_MOVIE_TIMESCALE:
5936 qtmux->timescale = g_value_get_uint (value);
5938 case PROP_TRAK_TIMESCALE:
5939 qtmux->trak_timescale = g_value_get_uint (value);
5942 qtmux->guess_pts = g_value_get_boolean (value);
5944 #ifndef GST_REMOVE_DEPRECATED
5945 case PROP_DTS_METHOD:
5946 qtmux->dts_method = g_value_get_enum (value);
5949 case PROP_FAST_START:
5950 qtmux->fast_start = g_value_get_boolean (value);
5952 case PROP_FAST_START_TEMP_FILE:
5953 g_free (qtmux->fast_start_file_path);
5954 qtmux->fast_start_file_path = g_value_dup_string (value);
5955 /* NULL means to generate a random one */
5956 if (!qtmux->fast_start_file_path) {
5957 gst_qt_mux_generate_fast_start_file_path (qtmux);
5960 case PROP_MOOV_RECOV_FILE:
5961 g_free (qtmux->moov_recov_file_path);
5962 qtmux->moov_recov_file_path = g_value_dup_string (value);
5964 case PROP_FRAGMENT_DURATION:
5965 qtmux->fragment_duration = g_value_get_uint (value);
5967 case PROP_STREAMABLE:{
5968 GstQTMuxClass *qtmux_klass =
5969 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5970 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
5971 qtmux->streamable = g_value_get_boolean (value);
5975 case PROP_RESERVED_MAX_DURATION:
5976 qtmux->reserved_max_duration = g_value_get_uint64 (value);
5978 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
5979 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
5981 case PROP_RESERVED_BYTES_PER_SEC:
5982 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
5984 case PROP_RESERVED_PREFILL:
5985 qtmux->reserved_prefill = g_value_get_boolean (value);
5987 case PROP_INTERLEAVE_BYTES:
5988 qtmux->interleave_bytes = g_value_get_uint64 (value);
5989 qtmux->interleave_bytes_set = TRUE;
5991 case PROP_INTERLEAVE_TIME:
5992 qtmux->interleave_time = g_value_get_uint64 (value);
5993 qtmux->interleave_time_set = TRUE;
5995 case PROP_MAX_RAW_AUDIO_DRIFT:
5996 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
5999 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6002 GST_OBJECT_UNLOCK (qtmux);
6005 static GstStateChangeReturn
6006 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6008 GstStateChangeReturn ret;
6009 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6011 switch (transition) {
6012 case GST_STATE_CHANGE_NULL_TO_READY:
6014 case GST_STATE_CHANGE_READY_TO_PAUSED:
6015 gst_collect_pads_start (qtmux->collect);
6016 qtmux->state = GST_QT_MUX_STATE_STARTED;
6018 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6020 case GST_STATE_CHANGE_PAUSED_TO_READY:
6021 gst_collect_pads_stop (qtmux->collect);
6027 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6029 switch (transition) {
6030 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6032 case GST_STATE_CHANGE_PAUSED_TO_READY:
6033 gst_qt_mux_reset (qtmux, TRUE);
6035 case GST_STATE_CHANGE_READY_TO_NULL:
6045 gst_qt_mux_register (GstPlugin * plugin)
6047 GTypeInfo typeinfo = {
6048 sizeof (GstQTMuxClass),
6049 (GBaseInitFunc) gst_qt_mux_base_init,
6051 (GClassInitFunc) gst_qt_mux_class_init,
6056 (GInstanceInitFunc) gst_qt_mux_init,
6058 static const GInterfaceInfo tag_setter_info = {
6061 static const GInterfaceInfo tag_xmp_writer_info = {
6064 static const GInterfaceInfo preset_info = {
6068 GstQTMuxFormat format;
6069 GstQTMuxClassParams *params;
6072 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6074 GST_LOG ("Registering muxers");
6077 GstQTMuxFormatProp *prop;
6078 GstCaps *subtitle_caps;
6080 prop = &gst_qt_mux_format_list[i];
6081 format = prop->format;
6082 if (format == GST_QT_MUX_FORMAT_NONE)
6085 /* create a cache for these properties */
6086 params = g_new0 (GstQTMuxClassParams, 1);
6087 params->prop = prop;
6088 params->src_caps = gst_static_caps_get (&prop->src_caps);
6089 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6090 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6091 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6092 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6093 params->subtitle_sink_caps = subtitle_caps;
6095 gst_caps_unref (subtitle_caps);
6098 /* create the type now */
6099 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6101 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6102 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6103 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6104 &tag_xmp_writer_info);
6105 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6107 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6113 GST_LOG ("Finished registering muxers");
6115 /* FIXME: ideally classification tag should be added and
6116 registered in gstreamer core gsttaglist
6119 GST_LOG ("Registering tags");
6121 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6122 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6123 gst_tag_merge_use_first);
6125 GST_LOG ("Finished registering tags");