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
51 * @short_description: Muxer for ISO MP4-based files
62 #include <glib/gstdio.h>
65 #include <gst/base/gstbytereader.h>
66 #include <gst/base/gstbitreader.h>
67 #include <gst/audio/audio.h>
68 #include <gst/video/video.h>
69 #include <gst/tag/tag.h>
70 #include <gst/pbutils/pbutils.h>
72 #include <sys/types.h>
74 #include <io.h> /* lseek, open, close, read */
76 #define lseek _lseeki64
82 #define ftruncate g_win32_ftruncate
89 #include "gstisomp4elements.h"
92 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
93 #define GST_CAT_DEFAULT gst_qt_mux_debug
96 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
101 * The basic building blocks of MP4 files are:
102 * - an 'ftyp' box at the very start
103 * - an 'mdat' box which contains the raw audio/video/subtitle data;
104 * this is just a bunch of bytes, completely unframed and possibly
105 * unordered with no additional meta-information
106 * - a 'moov' box that contains information about the different streams
107 * and what they contain, as well as sample tables for each stream
108 * that tell the demuxer where in the mdat box each buffer/sample is
109 * and what its duration/timestamp etc. is, and whether it's a
111 * Additionally, fragmented MP4 works by writing chunks of data in
112 * pairs of 'moof' and 'mdat' boxes:
113 * - 'moof' boxes, header preceding each mdat fragment describing the
114 * contents, like a moov but only for that fragment.
115 * - a 'mfra' box for Fragmented MP4, which is written at the end and
116 * contains a summary of all fragments and seek tables.
118 * Currently mp4mux can work in 4 different modes / generate 4 types
119 * of output files/streams:
121 * - Normal mp4: mp4mux will write a little ftyp identifier at the
122 * beginning, then start an mdat box into which it will write all the
123 * sample data. At EOS it will then write the moov header with track
124 * headers and sample tables at the end of the file, and rewrite the
125 * start of the file to fix up the mdat box size at the beginning.
126 * It has to wait for EOS to write the moov (which includes the
127 * sample tables) because it doesn't know how much space those
128 * tables will be. The output downstream must be seekable to rewrite
129 * the mdat box at EOS.
131 * - Fragmented mp4: moov header with track headers at start
132 * but no sample table, followed by N fragments, each containing
133 * track headers with sample tables followed by some data. Downstream
134 * does not need to be seekable if the 'streamable' flag is TRUE,
135 * as the final mfra and total duration will be omitted.
137 * - Fast-start mp4: the goal here is to create a file where the moov
138 * headers are at the beginning; what mp4mux will do is write all
139 * sample data into a temp file and build moov header plus sample
140 * tables in memory and then when EOS comes, it will push out the
141 * moov header plus sample tables at the beginning, followed by the
142 * mdat sample data at the end which is read in from the temp file
143 * Files created in this mode are better for streaming over the
144 * network, since the client doesn't have to seek to the end of the
145 * file to get the headers, but it requires copying all sample data
146 * out of the temp file at EOS, which can be expensive. Downstream does
147 * not need to be seekable, because of the use of the temp file.
149 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
150 * and reserved-moov-update-period properties to reserve free space
151 * at the start of the file and periodically write the MOOV atom out
152 * to it. That means that killing the muxing at any point still
153 * results in a playable file, at the cost of wasting some amount of
154 * free space at the start of file. The approximate recording duration
155 * has to be known in advance to estimate how much free space to reserve
156 * for the moov, and the downstream must be seekable.
157 * If the moov header grows larger than the reserved space, an error
158 * is generated - so it's better to over-estimate the amount of space
159 * to reserve. To ensure the file is playable at any point, the moov
160 * is updated using a 'ping-pong' strategy, so the output is never in
164 #ifndef GST_REMOVE_DEPRECATED
173 gst_qt_mux_dts_method_get_type (void)
175 static GType gst_qt_mux_dts_method = 0;
177 if (!gst_qt_mux_dts_method) {
178 static const GEnumValue dts_methods[] = {
179 {DTS_METHOD_DD, "delta/duration", "dd"},
180 {DTS_METHOD_REORDER, "reorder", "reorder"},
181 {DTS_METHOD_ASC, "ascending", "asc"},
185 gst_qt_mux_dts_method =
186 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
189 return gst_qt_mux_dts_method;
192 #define GST_TYPE_QT_MUX_DTS_METHOD \
193 (gst_qt_mux_dts_method_get_type ())
197 gst_qt_mux_fragment_mode_get_type (void)
199 static GType gst_qt_mux_fragment_mode = 0;
201 if (!gst_qt_mux_fragment_mode) {
202 static const GEnumValue gst_qt_mux_fragment_modes[] = {
203 {GST_QT_MUX_FRAGMENT_DASH_OR_MSS, "Dash or Smoothstreaming",
205 {GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE,
206 "First MOOV Fragment Then Finalise", "first-moov-then-finalise"},
208 /* {GST_QT_MUX_FRAGMENT_STREAMABLE, "streamable", "Streamable (ISML only. Deprecated elsewhere)"}, */
212 gst_qt_mux_fragment_mode =
213 g_enum_register_static ("GstQTMuxFragmentMode",
214 gst_qt_mux_fragment_modes);
217 return gst_qt_mux_fragment_mode;
220 #define GST_TYPE_QT_MUX_FRAGMENT_MODE \
221 (gst_qt_mux_fragment_mode_get_type ())
226 PROP_PAD_TRAK_TIMESCALE,
229 #define DEFAULT_PAD_TRAK_TIMESCALE 0
231 G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_AGGREGATOR_PAD);
234 gst_qt_mux_pad_set_property (GObject * object,
235 guint prop_id, const GValue * value, GParamSpec * pspec)
237 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
239 GST_OBJECT_LOCK (pad);
241 case PROP_PAD_TRAK_TIMESCALE:
242 pad->trak_timescale = g_value_get_uint (value);
245 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
248 GST_OBJECT_UNLOCK (pad);
252 gst_qt_mux_pad_get_property (GObject * object,
253 guint prop_id, GValue * value, GParamSpec * pspec)
255 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
257 GST_OBJECT_LOCK (pad);
259 case PROP_PAD_TRAK_TIMESCALE:
260 g_value_set_uint (value, pad->trak_timescale);
263 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
266 GST_OBJECT_UNLOCK (pad);
270 gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
272 GObjectClass *gobject_class = (GObjectClass *) klass;
274 gobject_class->get_property = gst_qt_mux_pad_get_property;
275 gobject_class->set_property = gst_qt_mux_pad_set_property;
277 g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
278 g_param_spec_uint ("trak-timescale", "Track timescale",
279 "Timescale to use for this pad's trak (units per second, 0 is automatic)",
280 0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
281 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
285 gst_qt_mux_pad_init (GstQTMuxPad * pad)
287 pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
291 gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
295 GST_OBJECT_LOCK (pad);
296 timescale = pad->trak_timescale;
297 GST_OBJECT_UNLOCK (pad);
302 /* QTMux signals and args */
312 PROP_MOVIE_TIMESCALE,
315 PROP_FAST_START_TEMP_FILE,
316 PROP_MOOV_RECOV_FILE,
317 PROP_FRAGMENT_DURATION,
318 PROP_RESERVED_MAX_DURATION,
319 PROP_RESERVED_DURATION_REMAINING,
320 PROP_RESERVED_MOOV_UPDATE_PERIOD,
321 PROP_RESERVED_BYTES_PER_SEC,
322 PROP_RESERVED_PREFILL,
323 #ifndef GST_REMOVE_DEPRECATED
327 PROP_INTERLEAVE_BYTES,
328 PROP_INTERLEAVE_TIME,
330 PROP_MAX_RAW_AUDIO_DRIFT,
331 PROP_START_GAP_THRESHOLD,
332 PROP_FORCE_CREATE_TIMECODE_TRAK,
336 /* some spare for header size as well */
337 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
339 #define DEFAULT_MOVIE_TIMESCALE 0
340 #define DEFAULT_TRAK_TIMESCALE 0
341 #define DEFAULT_DO_CTTS TRUE
342 #define DEFAULT_FAST_START FALSE
343 #define DEFAULT_FAST_START_TEMP_FILE NULL
344 #define DEFAULT_MOOV_RECOV_FILE NULL
345 #define DEFAULT_FRAGMENT_DURATION 0
346 #define DEFAULT_STREAMABLE TRUE
347 #ifndef GST_REMOVE_DEPRECATED
348 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
350 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
351 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
352 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
353 #define DEFAULT_RESERVED_PREFILL FALSE
354 #define DEFAULT_INTERLEAVE_BYTES 0
355 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
356 #define DEFAULT_FORCE_CHUNKS (FALSE)
357 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
358 #define DEFAULT_START_GAP_THRESHOLD 0
359 #define DEFAULT_FORCE_CREATE_TIMECODE_TRAK FALSE
360 #define DEFAULT_FRAGMENT_MODE GST_QT_MUX_FRAGMENT_DASH_OR_MSS
362 static void gst_qt_mux_finalize (GObject * object);
364 /* property functions */
365 static void gst_qt_mux_set_property (GObject * object,
366 guint prop_id, const GValue * value, GParamSpec * pspec);
367 static void gst_qt_mux_get_property (GObject * object,
368 guint prop_id, GValue * value, GParamSpec * pspec);
371 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
372 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
373 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
376 static gboolean gst_qt_mux_sink_event (GstAggregator * agg,
377 GstAggregatorPad * agg_pad, GstEvent * event);
378 static GstFlowReturn gst_qt_mux_sink_event_pre_queue (GstAggregator * self,
379 GstAggregatorPad * aggpad, GstEvent * event);
382 static GstAggregatorPad *gst_qt_mux_create_new_pad (GstAggregator * self,
383 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps);
384 static GstFlowReturn gst_qt_mux_aggregate (GstAggregator * agg,
386 static GstBuffer *gst_qt_mux_clip_running_time (GstAggregator * agg,
387 GstAggregatorPad * agg_pad, GstBuffer * buf);
388 static gboolean gst_qt_mux_start (GstAggregator * agg);
389 static gboolean gst_qt_mux_stop (GstAggregator * agg);
393 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTMuxPad * pad,
397 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
399 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
400 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
402 static GstFlowReturn gst_qtmux_push_mdat_stored_buffers (GstQTMux * qtmux);
404 static GstElementClass *parent_class = NULL;
407 gst_qt_mux_base_init (gpointer g_class)
409 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
410 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
411 GstQTMuxClassParams *params;
412 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
414 GstPadTemplate *srctempl;
415 gchar *longname, *description;
418 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
419 GST_QT_MUX_PARAMS_QDATA);
423 /* construct the element details struct */
424 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
425 description = g_strdup_printf ("Multiplex audio and video into a %s file",
426 params->prop->long_name);
427 gst_element_class_set_metadata (element_class, longname,
428 "Codec/Muxer", description,
429 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
431 g_free (description);
434 srctempl = gst_pad_template_new_with_gtype ("src", GST_PAD_SRC,
435 GST_PAD_ALWAYS, params->src_caps, GST_TYPE_AGGREGATOR_PAD);
436 gst_element_class_add_pad_template (element_class, srctempl);
438 if (params->audio_sink_caps) {
439 audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
440 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
441 GST_TYPE_QT_MUX_PAD);
442 gst_element_class_add_pad_template (element_class, audiosinktempl);
445 if (params->video_sink_caps) {
446 videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
447 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
448 GST_TYPE_QT_MUX_PAD);
449 gst_element_class_add_pad_template (element_class, videosinktempl);
452 if (params->subtitle_sink_caps) {
453 subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
454 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
455 GST_TYPE_QT_MUX_PAD);
456 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
459 if (params->caption_sink_caps) {
460 captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
461 GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
462 GST_TYPE_QT_MUX_PAD);
463 gst_element_class_add_pad_template (element_class, captionsinktempl);
466 klass->format = params->prop->format;
470 gst_qt_mux_class_init (GstQTMuxClass * klass)
472 GObjectClass *gobject_class;
473 GstElementClass *gstelement_class;
474 GstAggregatorClass *gstagg_class = GST_AGGREGATOR_CLASS (klass);
476 gobject_class = (GObjectClass *) klass;
477 gstelement_class = (GstElementClass *) klass;
479 parent_class = g_type_class_peek_parent (klass);
481 gobject_class->finalize = gst_qt_mux_finalize;
482 gobject_class->get_property = gst_qt_mux_get_property;
483 gobject_class->set_property = gst_qt_mux_set_property;
485 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
486 g_param_spec_uint ("movie-timescale", "Movie timescale",
487 "Timescale to use in the movie (units per second, 0 == default)",
488 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
489 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
490 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
491 g_param_spec_uint ("trak-timescale", "Track timescale",
492 "Timescale to use for the tracks (units per second, 0 is automatic)",
493 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
494 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
495 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
496 g_param_spec_boolean ("presentation-time",
497 "Include presentation-time info",
498 "Calculate and include presentation/composition time "
499 "(in addition to decoding time)", DEFAULT_DO_CTTS,
500 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
501 #ifndef GST_REMOVE_DEPRECATED
502 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
503 g_param_spec_enum ("dts-method", "dts-method",
504 "Method to determine DTS time (DEPRECATED)",
505 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
506 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
507 G_PARAM_STATIC_STRINGS));
509 g_object_class_install_property (gobject_class, PROP_FAST_START,
510 g_param_spec_boolean ("faststart", "Format file to faststart",
511 "If the file should be formatted for faststart (headers first)",
512 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
513 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
514 g_param_spec_string ("faststart-file", "File to use for storing buffers",
515 "File that will be used temporarily to store data from the stream "
516 "when creating a faststart file. If null a filepath will be "
517 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
518 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS |
519 GST_PARAM_DOC_SHOW_DEFAULT));
520 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
521 g_param_spec_string ("moov-recovery-file",
522 "File to store data for posterior moov atom recovery",
523 "File to be used to store "
524 "data for moov atom making movie file recovery possible in case "
525 "of a crash during muxing. Null for disabled. (Experimental)",
526 DEFAULT_MOOV_RECOV_FILE,
527 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
528 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
529 g_param_spec_uint ("fragment-duration", "Fragment duration",
530 "Fragment durations in ms (produce a fragmented file if > 0)",
531 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
532 2000 : DEFAULT_FRAGMENT_DURATION,
533 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
534 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
535 g_param_spec_uint64 ("reserved-max-duration",
536 "Reserved maximum file duration (ns)",
537 "When set to a value > 0, reserves space for index tables at the "
538 "beginning of the file.",
539 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
540 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
541 g_object_class_install_property (gobject_class,
542 PROP_RESERVED_DURATION_REMAINING,
543 g_param_spec_uint64 ("reserved-duration-remaining",
544 "Report the approximate amount of remaining recording space (ns)",
545 "Reports the approximate amount of remaining moov header space "
546 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
547 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
548 g_object_class_install_property (gobject_class,
549 PROP_RESERVED_MOOV_UPDATE_PERIOD,
550 g_param_spec_uint64 ("reserved-moov-update-period",
551 "Interval at which to update index tables (ns)",
552 "When used with reserved-max-duration, periodically updates the "
553 "index tables with information muxed so far.", 0, G_MAXUINT64,
554 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
555 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
556 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
557 g_param_spec_uint ("reserved-bytes-per-sec",
558 "Reserved MOOV bytes per second, per track",
559 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
560 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
561 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
562 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
563 g_param_spec_boolean ("reserved-prefill",
564 "Reserved Prefill Samples Table",
565 "Prefill samples table of reserved duration",
566 DEFAULT_RESERVED_PREFILL,
567 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
568 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
569 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
570 "Interleave between streams in bytes",
571 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
572 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
573 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
574 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
575 "Interleave between streams in nanoseconds",
576 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
577 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
578 g_object_class_install_property (gobject_class, PROP_FORCE_CHUNKS,
579 g_param_spec_boolean ("force-chunks", "Force Chunks",
580 "Force multiple chunks to be created even for single-stream files",
581 DEFAULT_FORCE_CHUNKS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
582 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
583 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
584 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
585 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
586 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
587 g_object_class_install_property (gobject_class, PROP_START_GAP_THRESHOLD,
588 g_param_spec_uint64 ("start-gap-threshold", "Start Gap Threshold",
589 "Threshold for creating an edit list for gaps at the start in nanoseconds",
590 0, G_MAXUINT64, DEFAULT_START_GAP_THRESHOLD,
591 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
592 g_object_class_install_property (gobject_class,
593 PROP_FORCE_CREATE_TIMECODE_TRAK,
594 g_param_spec_boolean ("force-create-timecode-trak",
595 "Force Create Timecode Trak",
596 "Create a timecode trak even in unsupported flavors",
597 DEFAULT_FORCE_CREATE_TIMECODE_TRAK,
598 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
601 * GstBaseQTMux:fragment-mode:
603 * Influence how fragmented files are produces. Only has any affect when the
604 * the 'fragment-duration' property is set to a value greater than '0'
606 * Currently, two options exist:
607 * - "dash-or-mss": for the original fragmented mode that supports dash or
608 * microsoft smoothstreaming with a single input stream
609 * - "first-moov-then-finalise" is a fragmented mode that will start with a
610 * self-contained 'moov' atom for the first fragment, then produce fragments.
611 * When the file is finalised, the initial 'moov' is invalidated and a
612 * new 'moov' is written covering the entire file.
616 g_object_class_install_property (gobject_class, PROP_FRAGMENT_MODE,
617 g_param_spec_enum ("fragment-mode", "Fragment Mode",
618 "How to to write fragments to the file. Only used when "
619 "\'fragment-duration\' is greater than 0",
620 GST_TYPE_QT_MUX_FRAGMENT_MODE, DEFAULT_FRAGMENT_MODE,
621 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
623 gstelement_class->request_new_pad =
624 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
625 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
627 gstagg_class->sink_event = gst_qt_mux_sink_event;
628 gstagg_class->sink_event_pre_queue = gst_qt_mux_sink_event_pre_queue;
629 gstagg_class->aggregate = gst_qt_mux_aggregate;
630 gstagg_class->clip = gst_qt_mux_clip_running_time;
631 gstagg_class->start = gst_qt_mux_start;
632 gstagg_class->stop = gst_qt_mux_stop;
633 gstagg_class->create_new_pad = gst_qt_mux_create_new_pad;
634 gstagg_class->negotiate = NULL;
636 gst_type_mark_as_plugin_api (GST_TYPE_QT_MUX_PAD, 0);
637 gst_type_mark_as_plugin_api (GST_TYPE_QT_MUX_DTS_METHOD, 0);
638 gst_type_mark_as_plugin_api (GST_TYPE_QT_MUX_FRAGMENT_MODE, 0);
642 gst_qt_mux_pad_reset (GstQTMuxPad * qtpad)
645 qtpad->is_out_of_order = FALSE;
646 qtpad->sample_size = 0;
649 qtpad->sample_offset = 0;
650 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
651 qtpad->first_ts = GST_CLOCK_TIME_NONE;
652 qtpad->first_dts = GST_CLOCK_TIME_NONE;
653 qtpad->prepare_buf_func = NULL;
654 qtpad->create_empty_buffer = NULL;
655 qtpad->avg_bitrate = 0;
656 qtpad->max_bitrate = 0;
657 qtpad->total_duration = 0;
658 qtpad->total_bytes = 0;
659 qtpad->sparse = FALSE;
660 qtpad->first_cc_sample_size = 0;
661 qtpad->flow_status = GST_FLOW_OK;
662 qtpad->warned_empty_duration = FALSE;
664 gst_buffer_replace (&qtpad->last_buf, NULL);
666 gst_caps_replace (&qtpad->configured_caps, NULL);
669 gst_tag_list_unref (qtpad->tags);
673 /* reference owned elsewhere */
675 qtpad->tc_trak = NULL;
678 atom_traf_free (qtpad->traf);
681 atom_array_clear (&qtpad->fragment_buffers);
683 g_array_unref (qtpad->samples);
684 qtpad->samples = NULL;
686 /* reference owned elsewhere */
689 qtpad->first_pts = GST_CLOCK_TIME_NONE;
692 gst_video_time_code_free (qtpad->first_tc);
693 qtpad->first_tc = NULL;
695 if (qtpad->raw_audio_adapter)
696 gst_object_unref (qtpad->raw_audio_adapter);
697 qtpad->raw_audio_adapter = NULL;
701 * Takes GstQTMux back to its initial state
704 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
709 qtmux->state = GST_QT_MUX_STATE_NONE;
710 qtmux->header_size = 0;
711 qtmux->mdat_size = 0;
714 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
715 qtmux->fragment_sequence = 0;
718 atom_ftyp_free (qtmux->ftyp);
722 atom_moov_free (qtmux->moov);
726 atom_mfra_free (qtmux->mfra);
729 if (qtmux->fast_start_file) {
730 fclose (qtmux->fast_start_file);
731 g_remove (qtmux->fast_start_file_path);
732 qtmux->fast_start_file = NULL;
734 if (qtmux->moov_recov_file) {
735 fclose (qtmux->moov_recov_file);
736 qtmux->moov_recov_file = NULL;
738 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
739 AtomInfo *ainfo = (AtomInfo *) walk->data;
740 ainfo->free_func (ainfo->atom);
743 g_slist_free (qtmux->extra_atoms);
744 qtmux->extra_atoms = NULL;
746 GST_OBJECT_LOCK (qtmux);
747 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
750 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
751 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
752 gst_qt_mux_pad_reset (qtpad);
754 /* hm, moov_free above yanked the traks away from us,
755 * so do not free, but do clear */
760 qtmux->moov = atom_moov_new (qtmux->context);
761 /* ensure all is as nice and fresh as request_new_pad would provide it */
762 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
763 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
765 qtpad->trak = atom_trak_new (qtmux->context);
766 atom_moov_add_trak (qtmux->moov, qtpad->trak);
769 GST_OBJECT_UNLOCK (qtmux);
771 g_list_free_full (qtmux->output_buffers, (GDestroyNotify) gst_buffer_unref);
772 qtmux->output_buffers = NULL;
774 qtmux->current_pad = NULL;
775 qtmux->current_chunk_size = 0;
776 qtmux->current_chunk_duration = 0;
777 qtmux->current_chunk_offset = -1;
779 qtmux->reserved_moov_size = 0;
780 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
781 qtmux->muxed_since_last_update = 0;
782 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
786 gst_qt_mux_clip_running_time (GstAggregator * agg,
787 GstAggregatorPad * agg_pad, GstBuffer * buf)
789 GstQTMuxPad *qtpad = GST_QT_MUX_PAD (agg_pad);
790 GstBuffer *outbuf = buf;
792 /* invalid left alone and passed */
793 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS_OR_PTS (buf)))) {
795 GstClockTime buf_dts, abs_dts;
798 time = GST_BUFFER_PTS (buf);
800 if (GST_CLOCK_TIME_IS_VALID (time)) {
802 gst_segment_to_running_time (&agg_pad->segment, GST_FORMAT_TIME,
804 if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time))) {
805 GST_DEBUG_OBJECT (agg_pad, "clipping buffer on pad outside segment %"
806 GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
807 gst_buffer_unref (buf);
812 GST_LOG_OBJECT (agg_pad, "buffer pts %" GST_TIME_FORMAT " -> %"
813 GST_TIME_FORMAT " running time",
814 GST_TIME_ARGS (GST_BUFFER_PTS (buf)), GST_TIME_ARGS (time));
815 outbuf = gst_buffer_make_writable (buf);
816 GST_BUFFER_PTS (outbuf) = time;
818 dts_sign = gst_segment_to_running_time_full (&agg_pad->segment,
819 GST_FORMAT_TIME, GST_BUFFER_DTS (outbuf), &abs_dts);
820 buf_dts = GST_BUFFER_DTS (outbuf);
822 GST_BUFFER_DTS (outbuf) = abs_dts;
823 qtpad->dts = abs_dts;
824 } else if (dts_sign < 0) {
825 GST_BUFFER_DTS (outbuf) = GST_CLOCK_TIME_NONE;
826 qtpad->dts = -((gint64) abs_dts);
828 GST_BUFFER_DTS (outbuf) = GST_CLOCK_TIME_NONE;
829 qtpad->dts = GST_CLOCK_STIME_NONE;
832 GST_LOG_OBJECT (agg_pad, "buffer dts %" GST_TIME_FORMAT " -> %"
833 GST_STIME_FORMAT " running time", GST_TIME_ARGS (buf_dts),
834 GST_STIME_ARGS (qtpad->dts));
841 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
843 /* properties set to default upon construction */
845 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
846 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
847 qtmux->reserved_bytes_per_sec_per_trak =
848 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
849 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
850 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
851 qtmux->force_chunks = DEFAULT_FORCE_CHUNKS;
852 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
853 qtmux->start_gap_threshold = DEFAULT_START_GAP_THRESHOLD;
854 qtmux->force_create_timecode_trak = DEFAULT_FORCE_CREATE_TIMECODE_TRAK;
856 /* always need this */
858 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format),
859 qtmux->force_create_timecode_trak);
861 /* internals to initial state */
862 gst_qt_mux_reset (qtmux, TRUE);
867 gst_qt_mux_finalize (GObject * object)
869 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
871 gst_qt_mux_reset (qtmux, FALSE);
873 g_free (qtmux->fast_start_file_path);
874 g_free (qtmux->moov_recov_file_path);
876 atoms_context_free (qtmux->context);
878 G_OBJECT_CLASS (parent_class)->finalize (object);
882 gst_qt_mux_prepare_jpc_buffer (GstQTMuxPad * qtpad, GstBuffer * buf,
889 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
894 size = gst_buffer_get_size (buf);
895 newbuf = gst_buffer_new_and_alloc (size + 8);
896 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
898 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
899 GST_WRITE_UINT32_BE (map.data, map.size);
900 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
902 gst_buffer_unmap (buf, &map);
903 gst_buffer_unref (buf);
909 extract_608_field_from_s334_1a (const guint8 * ccdata, gsize ccdata_size,
910 guint field, guint8 ** res)
913 gsize storage_size = 128;
914 gsize i, res_size = 0;
916 storage = g_malloc0 (storage_size);
918 /* Iterate over the ccdata and put the corresponding tuples for the given field
920 for (i = 0; i < ccdata_size; i += 3) {
921 if ((field == 1 && (ccdata[i * 3] & 0x80)) ||
922 (field == 2 && !(ccdata[i * 3] & 0x80))) {
923 GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
924 ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
925 if (res_size >= storage_size) {
927 storage = g_realloc (storage, storage_size);
929 storage[res_size] = ccdata[i * 3 + 1];
930 storage[res_size + 1] = ccdata[i * 3 + 2];
947 gst_qt_mux_prepare_caption_buffer (GstQTMuxPad * qtpad, GstBuffer * buf,
950 GstBuffer *newbuf = NULL;
951 GstMapInfo map, inmap;
958 in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
960 size = gst_buffer_get_size (buf);
961 gst_buffer_map (buf, &inmap, GST_MAP_READ);
963 GST_LOG_OBJECT (qtmux,
964 "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
965 GST_FOURCC_ARGS (qtpad->fourcc), size);
967 switch (qtpad->fourcc) {
971 gsize cdat_size, cdt2_size, total_size = 0;
972 gsize write_offs = 0;
975 extract_608_field_from_s334_1a (inmap.data, inmap.size, 1, &cdat);
977 extract_608_field_from_s334_1a (inmap.data, inmap.size, 2, &cdt2);
980 total_size += cdat_size + 8;
982 total_size += cdt2_size + 8;
983 if (total_size == 0) {
984 GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
985 /* FIXME : We might want to *always* store something, even if
986 * it's "empty" CC (i.e. 0x80 0x80) */
990 newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
991 /* Let's copy over all metadata and not the memory */
992 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
994 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
995 if (cdat_size || in_prefill) {
996 GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
997 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
999 memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
1001 /* Write 'empty' CC */
1005 write_offs = in_prefill ? 10 : cdat_size + 8;
1010 if (cdt2_size || in_prefill) {
1011 GST_WRITE_UINT32_BE (map.data + write_offs,
1012 in_prefill ? 10 : cdt2_size + 8);
1013 GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
1015 memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
1017 /* Write 'empty' CC */
1018 map.data[write_offs + 8] = 0x80;
1019 map.data[write_offs + 9] = 0x80;
1024 gst_buffer_unmap (newbuf, &map);
1032 /* Take the whole CDP */
1034 if (size > qtpad->first_cc_sample_size) {
1035 GST_ELEMENT_WARNING (qtmux, RESOURCE, WRITE,
1036 ("Truncating too big CEA708 sample (%" G_GSIZE_FORMAT " > %u)",
1037 size, qtpad->first_cc_sample_size), (NULL));
1038 } else if (size < qtpad->first_cc_sample_size) {
1039 GST_ELEMENT_WARNING (qtmux, RESOURCE, WRITE,
1040 ("Padding too small CEA708 sample (%" G_GSIZE_FORMAT " < %u)",
1041 size, qtpad->first_cc_sample_size), (NULL));
1044 actual_size = MIN (qtpad->first_cc_sample_size, size);
1049 newbuf = gst_buffer_new_and_alloc (actual_size + 8);
1051 /* Let's copy over all metadata and not the memory */
1052 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, -1);
1054 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1056 GST_WRITE_UINT32_BE (map.data, actual_size + 8);
1057 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1058 memcpy (map.data + 8, inmap.data, actual_size);
1060 gst_buffer_unmap (newbuf, &map);
1064 /* theoretically this should never happen, but let's keep this here in case */
1065 GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1069 gst_buffer_unmap (buf, &inmap);
1070 gst_buffer_unref (buf);
1076 gst_qt_mux_prepare_tx3g_buffer (GstQTMuxPad * qtpad, GstBuffer * buf,
1083 const guint8 *dataend;
1085 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1090 gst_buffer_map (buf, &frommap, GST_MAP_READ);
1092 dataend = memchr (frommap.data, 0, frommap.size);
1093 size = dataend ? dataend - frommap.data : frommap.size;
1094 newbuf = gst_buffer_new_and_alloc (size + 2);
1096 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1098 GST_WRITE_UINT16_BE (tomap.data, size);
1099 memcpy (tomap.data + 2, frommap.data, size);
1101 gst_buffer_unmap (newbuf, &tomap);
1102 gst_buffer_unmap (buf, &frommap);
1104 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1106 /* gst_buffer_copy_into is trying to be too clever and
1107 * won't copy duration when size is different */
1108 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1110 gst_buffer_unref (buf);
1116 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTMuxPad * qtpad,
1117 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1122 g_return_if_fail (qtpad->trak_ste);
1124 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
1126 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1130 gst_qt_mux_prepare_parse_ac3_frame (GstQTMuxPad * qtpad, GstBuffer * buf,
1134 GstByteReader reader;
1137 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1138 GST_WARNING_OBJECT (qtpad, "Failed to map buffer");
1142 if (G_UNLIKELY (map.size < 8))
1145 gst_byte_reader_init (&reader, map.data, map.size);
1146 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1151 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1153 GST_DEBUG_OBJECT (qtpad, "Found ac3 sync point at offset: %u", off);
1155 gst_bit_reader_init (&bits, map.data, map.size);
1157 /* off + sync + crc */
1158 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1160 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1161 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1162 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1163 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1164 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1166 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
1167 gst_bit_reader_skip_unchecked (&bits, 2);
1168 if ((acmod & 0x4)) /* if a surround channel exists */
1169 gst_bit_reader_skip_unchecked (&bits, 2);
1170 if (acmod == 0x2) /* if in 2/0 mode */
1171 gst_bit_reader_skip_unchecked (&bits, 2);
1173 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1175 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1176 bsmod, acmod, lfe_on);
1178 /* AC-3 spec says that those values should be constant for the
1179 * whole stream when muxed in mp4. We trust the input follows it */
1180 GST_DEBUG_OBJECT (qtpad, "Data parsed, removing "
1181 "prepare buffer function");
1182 qtpad->prepare_buf_func = NULL;
1186 gst_buffer_unmap (buf, &map);
1191 gst_qt_mux_create_empty_tx3g_buffer (GstQTMuxPad * qtpad, gint64 duration)
1195 data = g_malloc (2);
1196 GST_WRITE_UINT16_BE (data, 0);
1198 return gst_buffer_new_wrapped (data, 2);
1202 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1203 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1205 switch (gst_tag_get_type (tag)) {
1211 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1213 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1214 GST_FOURCC_ARGS (fourcc), str);
1215 atom_udta_add_str_tag (udta, fourcc, str);
1224 if (!gst_tag_list_get_double (list, tag, &value))
1226 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1227 GST_FOURCC_ARGS (fourcc), (gint) value);
1228 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1235 /* paired unsigned integers */
1239 got_tag = gst_tag_list_get_uint (list, tag, &value);
1240 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1243 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1244 GST_FOURCC_ARGS (fourcc), value, count);
1245 atom_udta_add_uint_tag (udta, fourcc, 0,
1246 value << 16 | (count & 0xFFFF));
1248 /* unpaired unsigned integers */
1249 if (!gst_tag_list_get_uint (list, tag, &value))
1251 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1252 GST_FOURCC_ARGS (fourcc), value);
1253 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1258 g_assert_not_reached ();
1264 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1265 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1273 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1275 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1278 year = g_date_get_year (date);
1279 month = g_date_get_month (date);
1280 day = g_date_get_day (date);
1284 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1285 day == G_DATE_BAD_DAY) {
1286 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1290 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1291 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1292 GST_FOURCC_ARGS (fourcc), str);
1293 atom_udta_add_str_tag (udta, fourcc, str);
1298 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1299 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1301 GValue value = { 0, };
1305 GstStructure *structure;
1309 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1311 if (!gst_tag_list_copy_value (&value, list, tag))
1314 sample = gst_value_get_sample (&value);
1319 buf = gst_sample_get_buffer (sample);
1323 caps = gst_sample_get_caps (sample);
1325 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1329 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1331 structure = gst_caps_get_structure (caps, 0);
1332 if (gst_structure_has_name (structure, "image/jpeg"))
1334 else if (gst_structure_has_name (structure, "image/png"))
1338 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1342 gst_buffer_map (buf, &map, GST_MAP_READ);
1343 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1344 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1345 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1346 gst_buffer_unmap (buf, &map);
1348 g_value_unset (&value);
1352 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1353 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1358 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1359 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1361 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1365 if (!gst_tag_list_get_uint (list, tag2, &number))
1369 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1370 GST_FOURCC_ARGS (fourcc), str);
1371 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1373 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1374 GST_FOURCC_ARGS (fourcc), str, number);
1375 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1382 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1383 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1388 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1390 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1393 year = g_date_get_year (date);
1396 if (year == G_DATE_BAD_YEAR) {
1397 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1401 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1402 GST_FOURCC_ARGS (fourcc), year);
1403 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1407 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1408 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1410 gdouble latitude = -360, longitude = -360, altitude = 0;
1411 gchar *location = NULL;
1412 guint8 *data, *ddata;
1413 gint size = 0, len = 0;
1414 gboolean ret = FALSE;
1416 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1418 ret = gst_tag_list_get_string (list, tag, &location);
1419 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1421 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1423 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1430 len = strlen (location);
1431 size += len + 1 + 2;
1433 /* role + (long, lat, alt) + body + notes */
1434 size += 1 + 3 * 4 + 1 + 1;
1436 data = ddata = g_malloc (size);
1439 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1442 memcpy (data + 2, location, len);
1443 GST_WRITE_UINT8 (data + 2 + len, 0);
1444 data += len + 1 + 2;
1446 GST_WRITE_UINT8 (data, 0);
1447 /* long, lat, alt */
1448 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1449 QT_WRITE_SFP32 (data + 1, longitude);
1450 QT_WRITE_SFP32 (data + 5, latitude);
1451 QT_WRITE_SFP32 (data + 9, altitude);
1452 /* neither astronomical body nor notes */
1453 GST_WRITE_UINT16_BE (data + 13, 0);
1455 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1456 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1461 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1462 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1464 gchar *keywords = NULL;
1465 guint8 *data, *ddata;
1469 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1471 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1474 kwds = g_strsplit (keywords, ",", 0);
1478 for (i = 0; kwds[i]; i++) {
1479 /* size byte + null-terminator */
1480 size += strlen (kwds[i]) + 1 + 1;
1483 /* language tag + count + keywords */
1486 data = ddata = g_malloc (size);
1489 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1491 GST_WRITE_UINT8 (data + 2, i);
1494 for (i = 0; kwds[i]; ++i) {
1495 gint len = strlen (kwds[i]);
1497 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1498 GST_FOURCC_ARGS (fourcc), kwds[i]);
1500 GST_WRITE_UINT8 (data, len + 1);
1501 memcpy (data + 1, kwds[i], len + 1);
1507 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1512 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1513 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1521 size = strlen (input);
1523 if (size < 4 + 3 + 1 + 1 + 1) {
1524 /* at least the minimum xxxx://y/z */
1525 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1530 /* read the fourcc */
1531 memcpy (&fourcc, data, 4);
1535 if (strncmp (data, "://", 3) != 0) {
1541 /* read the table number */
1542 if (sscanf (data, "%d", &table) != 1) {
1546 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1547 ", table numbers should be positive, ignoring tag", table);
1551 /* find the next / */
1552 while (size > 0 && data[0] != '/') {
1559 g_assert (data[0] == '/');
1568 /* read up the rest of the string */
1569 *p_content = g_strdup (data);
1570 *p_table = (guint16) table;
1576 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1577 "input (%s) didn't match the expected entitycode://table/content",
1584 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1585 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1587 gchar *clsf_data = NULL;
1591 gchar *content = NULL;
1594 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1596 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1599 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1600 GST_FOURCC_ARGS (fourcc), clsf_data);
1602 /* parse the string, format is:
1603 * entityfourcc://table/content
1605 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1609 size = strlen (content) + 1;
1611 /* now we have everything, build the atom
1612 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1613 data = g_malloc (4 + 2 + 2 + size);
1614 GST_WRITE_UINT32_LE (data, entity);
1615 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1616 GST_WRITE_UINT16_BE (data + 6, 0);
1617 memcpy (data + 8, content, size);
1620 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1624 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1625 const GstTagList * list, AtomUDTA * udta, const char *tag,
1626 const char *tag2, guint32 fourcc);
1629 * Struct to record mappings from gstreamer tags to fourcc codes
1631 typedef struct _GstTagToFourcc
1634 const gchar *gsttag;
1635 const gchar *gsttag2;
1636 const GstQTMuxAddUdtaTagFunc func;
1639 /* tag list tags to fourcc matching */
1640 static const GstTagToFourcc tag_matches_mp4[] = {
1641 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1642 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1643 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1644 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1645 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1646 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1647 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1648 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1649 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1650 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1651 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1652 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1653 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1654 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1655 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1656 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1657 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1658 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1659 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1660 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1661 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1662 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1663 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1664 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1665 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1666 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1667 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1668 gst_qt_mux_add_mp4_tag},
1669 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1670 gst_qt_mux_add_mp4_tag},
1671 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1672 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1676 static const GstTagToFourcc tag_matches_3gp[] = {
1677 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1678 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1679 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1680 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1681 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1682 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1683 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1684 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1685 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1686 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1687 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1688 gst_qt_mux_add_3gp_classification},
1692 /* qtdemux produces these for atoms it cannot parse */
1693 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1696 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1698 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1699 GstBuffer *xmp = NULL;
1701 /* adobe specs only have 'quicktime' and 'mp4',
1702 * but I guess we can extrapolate to gpp.
1703 * Keep mj2 out for now as we don't add any tags for it yet.
1704 * If you have further info about xmp on these formats, please share */
1705 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1708 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1710 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1711 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1714 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1717 /* for isom/mp4, it is a top level uuid atom */
1718 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1721 ainfo = build_uuid_xmp_atom (xmp);
1723 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1728 gst_buffer_unref (xmp);
1732 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1735 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1738 const gchar *tag, *tag2;
1739 const GstTagToFourcc *tag_matches;
1741 switch (qtmux_klass->format) {
1742 case GST_QT_MUX_FORMAT_3GP:
1743 tag_matches = tag_matches_3gp;
1745 case GST_QT_MUX_FORMAT_MJ2:
1749 /* sort of iTunes style for mp4 and QT (?) */
1750 tag_matches = tag_matches_mp4;
1757 /* Clear existing tags so we don't add them over and over */
1758 atom_udta_clear_tags (udta);
1760 for (i = 0; tag_matches[i].fourcc; i++) {
1761 fourcc = tag_matches[i].fourcc;
1762 tag = tag_matches[i].gsttag;
1763 tag2 = tag_matches[i].gsttag2;
1765 g_assert (tag_matches[i].func);
1766 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1769 /* add unparsed blobs if present */
1770 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1773 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1774 for (i = 0; i < num_tags; ++i) {
1775 GstSample *sample = NULL;
1777 const GstStructure *s;
1779 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1782 buf = gst_sample_get_buffer (sample);
1784 if (buf && (s = gst_sample_get_info (sample))) {
1785 const gchar *style = NULL;
1788 gst_buffer_map (buf, &map, GST_MAP_READ);
1789 GST_DEBUG_OBJECT (qtmux,
1790 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1791 GST_PTR_FORMAT, i, num_tags, map.size, s);
1792 if (s && (style = gst_structure_get_string (s, "style"))) {
1793 /* try to prevent some style tag ending up into another variant
1794 * (todo: make into a list if more cases) */
1795 if ((strcmp (style, "itunes") == 0 &&
1796 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1797 (strcmp (style, "iso") == 0 &&
1798 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1799 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1800 atom_udta_add_blob_tag (udta, map.data, map.size);
1803 gst_buffer_unmap (buf, &map);
1805 gst_sample_unref (sample);
1813 * Gets the tagsetter iface taglist and puts the known tags
1814 * into the output stream
1817 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1819 const GstTagList *tags = NULL;
1822 GST_OBJECT_LOCK (qtmux);
1823 if (qtmux->tags_changed) {
1824 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1825 qtmux->tags_changed = FALSE;
1827 GST_OBJECT_UNLOCK (qtmux);
1829 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1831 if (tags && !gst_tag_list_is_empty (tags)) {
1832 GstTagList *copy = gst_tag_list_copy (tags);
1834 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1835 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1836 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1837 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1839 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1840 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1841 gst_qt_mux_add_xmp_tags (qtmux, copy);
1842 gst_tag_list_unref (copy);
1844 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1847 GST_OBJECT_LOCK (qtmux);
1848 for (l = GST_ELEMENT (qtmux)->sinkpads; l; l = l->next) {
1849 GstQTMuxPad *qpad = GST_QT_MUX_PAD (l->data);
1851 if (qpad->tags_changed && qpad->tags) {
1852 GST_DEBUG_OBJECT (qpad, "Adding tags");
1853 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1854 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1855 qpad->tags_changed = FALSE;
1856 GST_DEBUG_OBJECT (qpad, "Tags added");
1858 GST_DEBUG_OBJECT (qpad, "No new tags received");
1861 GST_OBJECT_UNLOCK (qtmux);
1864 static inline GstBuffer *
1865 _gst_buffer_new_take_data (guint8 * data, guint size)
1869 buf = gst_buffer_new ();
1870 gst_buffer_append_memory (buf,
1871 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1876 static GstFlowReturn
1877 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1880 GstFlowReturn res = GST_FLOW_OK;
1883 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1885 size = gst_buffer_get_size (buf);
1886 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1888 if (mind_fast && qtmux->fast_start_file) {
1892 GST_LOG_OBJECT (qtmux, "to temporary file");
1893 gst_buffer_map (buf, &map, GST_MAP_READ);
1894 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1895 gst_buffer_unmap (buf, &map);
1896 gst_buffer_unref (buf);
1903 res = gst_qtmux_push_mdat_stored_buffers (qtmux);
1906 if (res == GST_FLOW_OK) {
1907 GST_LOG_OBJECT (qtmux, "downstream");
1908 res = gst_aggregator_finish_buffer (GST_AGGREGATOR (qtmux), buf);
1912 if (res != GST_FLOW_OK)
1913 GST_WARNING_OBJECT (qtmux,
1914 "Failed to send buffer (%p) size %" G_GSIZE_FORMAT, buf, size);
1916 if (G_LIKELY (offset))
1924 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1925 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1926 return GST_FLOW_ERROR;
1931 gst_qt_mux_seek_to_beginning (FILE * f)
1934 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1936 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1937 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1940 if (fseek (f, (long) 0, SEEK_SET) != 0)
1946 static GstFlowReturn
1947 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1949 GstFlowReturn ret = GST_FLOW_OK;
1950 GstBuffer *buf = NULL;
1952 if (fflush (qtmux->fast_start_file))
1955 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1958 /* hm, this could all take a really really long time,
1959 * but there may not be another way to get moov atom first
1960 * (somehow optimize copy?) */
1961 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1962 while (ret == GST_FLOW_OK) {
1963 const int bufsize = 4096;
1967 buf = gst_buffer_new_and_alloc (bufsize);
1968 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1969 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1971 gst_buffer_unmap (buf, &map);
1974 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1975 gst_buffer_unmap (buf, &map);
1976 if (size != bufsize)
1977 gst_buffer_set_size (buf, size);
1978 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1982 gst_buffer_unref (buf);
1984 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1986 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1994 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1995 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1996 ret = GST_FLOW_ERROR;
2001 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
2002 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
2003 ret = GST_FLOW_ERROR;
2008 /* clear descriptor so we don't remove temp file later on,
2009 * might be possible to recover */
2010 fclose (qtmux->fast_start_file);
2011 qtmux->fast_start_file = NULL;
2017 * Sends the initial mdat atom fields (size fields and fourcc type),
2018 * the subsequent buffers are considered part of it's data.
2019 * As we can't predict the amount of data that we are going to place in mdat
2020 * we need to record the position of the size field in the stream so we can
2021 * seek back to it later and update when the streams have finished.
2023 static GstFlowReturn
2024 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
2025 gboolean extended, gboolean fsync_after)
2029 gboolean mind_fast = FALSE;
2031 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
2032 "size %" G_GUINT64_FORMAT, size);
2034 /* if the qtmux state is EOS, really write the mdat, otherwise
2035 * allow size == 0 for a placeholder atom */
2036 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
2040 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
2041 /* Always write 16-bytes, but put a free atom first
2042 * if the size is < 4GB. */
2043 buf = gst_buffer_new_and_alloc (16);
2044 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2047 /* Write extended mdat header and large_size field */
2048 GST_WRITE_UINT32_BE (map.data, 1);
2049 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2050 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
2052 /* Write an empty free atom, then standard 32-bit mdat */
2053 GST_WRITE_UINT32_BE (map.data, 8);
2054 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
2055 GST_WRITE_UINT32_BE (map.data + 8, size);
2056 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2058 gst_buffer_unmap (buf, &map);
2060 buf = gst_buffer_new_and_alloc (8);
2061 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2063 /* Vanilla 32-bit mdat */
2064 GST_WRITE_UINT32_BE (map.data, size);
2065 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2066 gst_buffer_unmap (buf, &map);
2069 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2071 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2073 mind_fast = qtmux->mux_mode == GST_QT_MUX_MODE_MOOV_AT_END
2074 && !qtmux->downstream_seekable;
2076 return gst_qt_mux_send_buffer (qtmux, buf, off, mind_fast);
2080 gst_qt_mux_seek_to (GstQTMux * qtmux, guint64 position)
2084 gst_segment_init (&segment, GST_FORMAT_BYTES);
2085 segment.start = position;
2086 GST_LOG_OBJECT (qtmux, "seeking to byte position %" G_GUINT64_FORMAT,
2088 gst_aggregator_update_segment (GST_AGGREGATOR (qtmux), &segment);
2092 * We get the position of the mdat size field, seek back to it
2093 * and overwrite with the real value
2095 static GstFlowReturn
2096 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2097 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2100 /* We must have recorded the mdat position for this to work */
2101 g_assert (mdat_pos != 0);
2103 /* seek and rewrite the header */
2104 gst_qt_mux_seek_to (qtmux, mdat_pos);
2106 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2110 static GstFlowReturn
2111 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2114 guint64 size = 0, offset = 0;
2115 guint8 *data = NULL;
2117 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2119 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2120 goto serialize_error;
2122 buf = _gst_buffer_new_take_data (data, offset);
2124 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2125 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2130 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2131 ("Failed to serialize ftyp"));
2132 return GST_FLOW_ERROR;
2137 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2138 GstBuffer ** p_prefix)
2140 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2141 guint32 major, version;
2143 GstBuffer *prefix = NULL;
2144 AtomFTYP *ftyp = NULL;
2146 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2148 /* init and send context and ftyp based on current property state */
2149 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2150 &version, &comp, qtmux->moov, qtmux->longest_chunk,
2151 qtmux->fast_start_file != NULL);
2152 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2159 gst_buffer_unref (prefix);
2164 static GstFlowReturn
2165 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2167 GstFlowReturn ret = GST_FLOW_OK;
2168 GstBuffer *prefix = NULL;
2170 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2172 /* init and send context and ftyp based on current property state */
2174 atom_ftyp_free (qtmux->ftyp);
2177 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2179 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2180 if (ret != GST_FLOW_OK)
2183 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2187 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2189 GstStructure *structure;
2190 GValue array = { 0 };
2191 GValue value = { 0 };
2192 GstCaps *caps, *tcaps;
2194 tcaps = gst_pad_get_current_caps (GST_AGGREGATOR_SRC_PAD (mux));
2195 caps = gst_caps_copy (tcaps);
2196 gst_caps_unref (tcaps);
2198 structure = gst_caps_get_structure (caps, 0);
2200 g_value_init (&array, GST_TYPE_ARRAY);
2202 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2203 g_value_init (&value, GST_TYPE_BUFFER);
2204 gst_value_take_buffer (&value, gst_buffer_ref (buf));
2205 gst_value_array_append_value (&array, &value);
2206 g_value_unset (&value);
2208 gst_structure_set_value (structure, "streamheader", &array);
2209 g_value_unset (&array);
2210 gst_aggregator_set_src_caps (GST_AGGREGATOR (mux), caps);
2211 gst_caps_unref (caps);
2215 * Write out a free space atom. The offset is adjusted by the full
2216 * size, but a smaller buffer is sent
2218 static GstFlowReturn
2219 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2220 gboolean fsync_after)
2224 guint8 *data = NULL;
2225 guint64 offset = 0, bsize = 0;
2228 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2230 /* We can't make a free space atom smaller than the header */
2234 node_header = g_malloc0 (sizeof (Atom));
2235 node_header->type = FOURCC_free;
2236 node_header->size = size;
2239 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2240 goto serialize_error;
2242 buf = _gst_buffer_new_take_data (data, offset);
2243 g_free (node_header);
2246 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2248 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2249 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2254 /* Make sure downstream position ends up at the end of this free box */
2255 gst_qt_mux_seek_to (qtmux, *off);
2263 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2264 ("Not enough free reserved space"));
2265 return GST_FLOW_ERROR;
2269 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2270 ("Failed to serialize mdat"));
2271 g_free (node_header);
2272 return GST_FLOW_ERROR;
2277 gst_qt_mux_configure_moov_full (GstQTMux * qtmux, gboolean fragmented,
2280 /* inform lower layers of our property wishes, and determine duration.
2281 * Let moov take care of this using its list of traks;
2282 * so that released pads are also included */
2283 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2285 atom_moov_update_timescale (qtmux->moov, timescale);
2286 atom_moov_set_fragmented (qtmux->moov, fragmented);
2288 atom_moov_update_duration (qtmux->moov);
2292 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2294 gboolean fragmented = FALSE;
2297 GST_OBJECT_LOCK (qtmux);
2298 timescale = qtmux->timescale;
2299 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED
2300 && qtmux->fragment_mode != GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE)
2302 GST_OBJECT_UNLOCK (qtmux);
2304 gst_qt_mux_configure_moov_full (qtmux, fragmented, timescale);
2307 static GstFlowReturn
2308 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2309 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2311 guint64 offset = 0, size = 0;
2314 GstFlowReturn ret = GST_FLOW_OK;
2316 guint64 current_time = atoms_get_current_qt_time ();
2318 /* update modification times */
2319 qtmux->moov->mvhd.time_info.modification_time = current_time;
2321 GST_OBJECT_LOCK (qtmux);
2322 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2323 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
2325 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2326 qtpad->trak->tkhd.modification_time = current_time;
2328 GST_OBJECT_UNLOCK (qtmux);
2330 /* serialize moov */
2333 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2334 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2335 goto serialize_error;
2336 qtmux->last_moov_size = offset;
2338 /* Check we have enough reserved space for this and a Free atom */
2339 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2340 goto too_small_reserved;
2341 buf = _gst_buffer_new_take_data (data, offset);
2342 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2344 /* If at EOS, this is the final moov, put in the streamheader
2345 * (apparently used by a flumotion util) */
2346 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2347 gst_qt_mux_set_header_on_caps (qtmux, buf);
2350 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2351 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2353 /* Write out a free atom if needed */
2354 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2355 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2356 (guint32) (padded_moov_size - offset));
2358 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2365 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2366 ("Not enough free reserved header space"),
2367 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2368 offset + 8, padded_moov_size));
2369 return GST_FLOW_ERROR;
2374 return GST_FLOW_ERROR;
2378 /* either calculates size of extra atoms or pushes them */
2379 static GstFlowReturn
2380 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2384 guint64 loffset = 0, size = 0;
2386 GstFlowReturn ret = GST_FLOW_OK;
2388 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2389 AtomInfo *ainfo = (AtomInfo *) walk->data;
2393 if (!ainfo->copy_data_func (ainfo->atom,
2394 send ? &data : NULL, &size, &loffset))
2395 goto serialize_error;
2400 GST_DEBUG_OBJECT (qtmux,
2401 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2402 GST_FOURCC_ARGS (ainfo->atom->type));
2403 buf = _gst_buffer_new_take_data (data, loffset);
2404 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2405 if (ret != GST_FLOW_OK)
2418 return GST_FLOW_ERROR;
2423 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2425 gboolean seekable = FALSE;
2426 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2428 if (gst_pad_peer_query (GST_AGGREGATOR_SRC_PAD (qtmux), query)) {
2429 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2430 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2432 /* have to assume seeking is not supported if query not handled downstream */
2433 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2436 gst_query_unref (query);
2441 /* Must be called with object lock */
2443 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2446 gboolean fail = FALSE;
2447 AtomFTYP *ftyp = NULL;
2448 GstBuffer *prefix = NULL;
2450 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2451 qtmux->moov_recov_file_path);
2453 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2454 if (qtmux->moov_recov_file == NULL) {
2455 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2456 qtmux->moov_recov_file_path);
2460 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2462 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2463 qtmux->moov, qtmux->timescale,
2464 g_list_length (GST_ELEMENT (qtmux)->sinkpads))) {
2465 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2469 atom_ftyp_free (ftyp);
2471 gst_buffer_unref (prefix);
2473 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2474 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
2475 /* write info for each stream */
2476 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2478 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2488 fclose (qtmux->moov_recov_file);
2489 qtmux->moov_recov_file = NULL;
2493 prefill_get_block_index (GstQTMux * qtmux, GstQTMuxPad * qpad)
2495 switch (qpad->fourcc) {
2504 return qpad->sample_offset;
2507 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2508 qpad->expected_sample_duration_n,
2509 qpad->expected_sample_duration_d *
2510 atom_trak_get_timescale (qpad->trak));
2517 prefill_get_sample_size (GstQTMux * qtmux, GstQTMuxPad * qpad)
2519 switch (qpad->fourcc) {
2521 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2523 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2525 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2527 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2529 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 2160) {
2536 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2538 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2540 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2542 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2544 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 2160) {
2551 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2553 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2555 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2557 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2559 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 2160) {
2566 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2568 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2570 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2572 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2574 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 2160) {
2581 /* We always write both cdat and cdt2 atom in prefill mode */
2584 if (qpad->first_cc_sample_size == 0) {
2586 gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD (qpad));
2587 g_assert (buf != NULL);
2588 qpad->first_cc_sample_size = gst_buffer_get_size (buf);
2589 g_assert (qpad->first_cc_sample_size != 0);
2590 gst_buffer_unref (buf);
2592 return qpad->first_cc_sample_size + 8;
2597 guint64 next_sample_offset;
2599 block_idx = prefill_get_block_index (qtmux, qpad);
2600 next_sample_offset =
2601 gst_util_uint64_scale (block_idx + 1,
2602 qpad->expected_sample_duration_d *
2603 atom_trak_get_timescale (qpad->trak),
2604 qpad->expected_sample_duration_n);
2606 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2611 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2619 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTMuxPad * qpad)
2621 switch (qpad->fourcc) {
2630 return gst_util_uint64_scale (qpad->sample_offset + 1,
2631 qpad->expected_sample_duration_d * GST_SECOND,
2632 qpad->expected_sample_duration_n);
2636 guint64 next_sample_offset;
2638 block_idx = prefill_get_block_index (qtmux, qpad);
2639 next_sample_offset =
2640 gst_util_uint64_scale (block_idx + 1,
2641 qpad->expected_sample_duration_d *
2642 atom_trak_get_timescale (qpad->trak),
2643 qpad->expected_sample_duration_n);
2645 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2646 atom_trak_get_timescale (qpad->trak));
2649 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2657 prefill_raw_audio_prepare_buf_func (GstQTMuxPad * qtpad, GstBuffer * buf,
2662 GstClockTime input_timestamp;
2663 guint64 input_timestamp_distance;
2666 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2668 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2669 qtpad->expected_sample_duration_n,
2670 qtpad->expected_sample_duration_d *
2671 atom_trak_get_timescale (qtpad->trak));
2673 gst_util_uint64_scale (block_idx + 1,
2674 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2675 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2677 if ((!gst_aggregator_pad_is_eos (GST_AGGREGATOR_PAD (qtpad))
2678 && gst_adapter_available (qtpad->raw_audio_adapter) <
2679 nsamples * qtpad->sample_size)
2680 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2685 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2686 &input_timestamp_distance);
2687 if (input_timestamp != GST_CLOCK_TIME_NONE)
2689 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2690 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2693 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2694 !gst_aggregator_pad_is_eos (GST_AGGREGATOR_PAD (qtpad)) ? nsamples *
2695 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2696 GST_BUFFER_PTS (buf) = input_timestamp;
2697 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2698 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2700 qtpad->raw_audio_adapter_offset += nsamples;
2702 /* Check if we have yet another block of raw audio in the adapter */
2704 gst_util_uint64_scale (block_idx + 2,
2705 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2706 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2707 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2708 nsamples * qtpad->sample_size) {
2710 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2711 &input_timestamp_distance);
2712 if (input_timestamp != GST_CLOCK_TIME_NONE)
2714 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2715 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2716 qtpad->raw_audio_adapter_pts = input_timestamp;
2718 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2724 /* Must be called with object lock */
2726 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2730 /* Find the (first) video track and assume that we have to output
2732 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2733 GstQTMuxPad *tmp_qpad = (GstQTMuxPad *) l->data;
2735 if (tmp_qpad->trak->is_video) {
2736 *dur_n = tmp_qpad->expected_sample_duration_n;
2737 *dur_d = tmp_qpad->expected_sample_duration_d;
2743 GST_INFO_OBJECT (qtmux,
2744 "Found no video framerate, using 40ms audio buffers");
2750 /* Called when all pads are prerolled to adjust and */
2752 prefill_update_sample_size (GstQTMux * qtmux, GstQTMuxPad * qpad)
2754 switch (qpad->fourcc) {
2762 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2763 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2769 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2770 /* We need a "valid" duration */
2771 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2772 &qpad->expected_sample_duration_d);
2773 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2778 find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2779 &qpad->expected_sample_duration_d);
2780 /* Set a prepare_buf_func that ensures this */
2781 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2782 qpad->raw_audio_adapter = gst_adapter_new ();
2783 qpad->raw_audio_adapter_offset = 0;
2784 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2793 /* Only called at startup when doing the "fake" iteration of all tracks in order
2794 * to prefill the sample tables in the header. */
2795 static GstQTMuxPad *
2796 find_best_pad_prefill_start (GstQTMux * qtmux)
2798 GstQTMuxPad *best_pad = NULL;
2800 /* If interleave limits have been specified and the current pad is within
2801 * those interleave limits, pick that one, otherwise let's try to figure out
2802 * the next best one. */
2804 if (qtmux->current_pad &&
2805 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2806 (qtmux->interleave_bytes == 0
2807 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2808 && (qtmux->interleave_time == 0
2809 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2810 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED) {
2812 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2813 best_pad = qtmux->current_pad;
2816 GST_OBJECT_LOCK (qtmux);
2817 if (GST_ELEMENT_CAST (qtmux)->sinkpads->next) {
2818 /* Attempt to try another pad if we have one. Otherwise use the only pad
2820 best_pad = qtmux->current_pad = NULL;
2822 GST_OBJECT_UNLOCK (qtmux);
2825 /* The next best pad is the one which has the lowest timestamp and hasn't
2826 * exceeded the reserved max duration */
2829 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2831 GST_OBJECT_LOCK (qtmux);
2832 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2833 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
2834 GstClockTime timestamp;
2836 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2839 timestamp = qtpad->total_duration;
2841 if (best_pad == NULL ||
2842 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2844 best_time = timestamp;
2847 GST_OBJECT_UNLOCK (qtmux);
2853 /* Called when starting the file in prefill_mode to figure out all the entries
2854 * of the header based on the input stream and reserved maximum duration.
2856 * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2857 * will be updated and written on EOS. */
2859 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2863 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2865 /* Update expected sample sizes/durations as needed, this is for raw
2866 * audio where samples are actual audio samples. */
2867 GST_OBJECT_LOCK (qtmux);
2868 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2869 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
2871 if (!prefill_update_sample_size (qtmux, qpad)) {
2872 GST_OBJECT_UNLOCK (qtmux);
2876 GST_OBJECT_UNLOCK (qtmux);
2878 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
2879 qtmux->force_create_timecode_trak) {
2880 /* For the first sample check/update timecode as needed. We do that before
2881 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2882 * initial buffer directly, not with last_buf */
2883 GST_OBJECT_LOCK (qtmux);
2884 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
2885 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
2887 gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD (qpad));
2888 GstVideoTimeCodeMeta *tc_meta;
2890 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))
2891 && qpad->trak->is_video) {
2892 GstVideoTimeCode *tc = &tc_meta->tc;
2894 qpad->tc_trak = atom_trak_new (qtmux->context);
2895 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2897 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2898 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2900 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2901 qpad->trak->mdia.mdhd.time_info.timescale, tc);
2903 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2904 qtmux->mdat_size, FALSE, 0);
2906 qpad->tc_pos = qtmux->mdat_size;
2907 qpad->first_tc = gst_video_time_code_copy (tc);
2908 qpad->first_pts = GST_BUFFER_PTS (buffer);
2910 qtmux->current_chunk_offset = -1;
2911 qtmux->current_chunk_size = 0;
2912 qtmux->current_chunk_duration = 0;
2913 qtmux->mdat_size += 4;
2916 gst_buffer_unref (buffer);
2918 GST_OBJECT_UNLOCK (qtmux);
2921 while ((qpad = find_best_pad_prefill_start (qtmux))) {
2922 GstClockTime timestamp, next_timestamp, duration;
2923 guint nsamples, sample_size;
2924 guint64 chunk_offset;
2925 gint64 scaled_duration;
2926 gint64 pts_offset = 0;
2927 gboolean sync = FALSE;
2928 TrakBufferEntryInfo sample_entry;
2930 sample_size = prefill_get_sample_size (qtmux, qpad);
2932 if (sample_size == -1) {
2937 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2939 timestamp = qpad->total_duration;
2940 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2941 duration = next_timestamp - timestamp;
2943 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2944 qpad->first_ts = timestamp;
2945 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2946 qpad->first_dts = timestamp;
2948 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2949 qtmux->current_pad = qpad;
2950 if (qtmux->current_chunk_offset == -1)
2951 qtmux->current_chunk_offset = qtmux->mdat_size;
2953 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2954 qtmux->current_chunk_size = 0;
2955 qtmux->current_chunk_duration = 0;
2957 if (qpad->sample_size)
2958 nsamples = sample_size / qpad->sample_size;
2961 qpad->last_dts = timestamp;
2962 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2963 atom_trak_get_timescale (qpad->trak),
2964 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2965 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2967 qtmux->current_chunk_size += sample_size;
2968 qtmux->current_chunk_duration += duration;
2969 qpad->total_bytes += sample_size;
2971 chunk_offset = qtmux->current_chunk_offset;
2973 /* I-frame only, no frame reordering */
2977 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2978 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2979 qtmux->longest_chunk = qtmux->current_chunk_duration;
2982 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2983 sample_entry.nsamples = nsamples;
2984 sample_entry.delta = scaled_duration / nsamples;
2985 sample_entry.size = sample_size / nsamples;
2986 sample_entry.chunk_offset = chunk_offset;
2987 sample_entry.pts_offset = pts_offset;
2988 sample_entry.sync = sync;
2989 sample_entry.do_pts = TRUE;
2990 g_array_append_val (qpad->samples, sample_entry);
2991 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2992 sample_size / nsamples, chunk_offset, sync, pts_offset);
2994 qpad->total_duration = next_timestamp;
2995 qtmux->mdat_size += sample_size;
2996 qpad->sample_offset += nsamples;
3002 static GstFlowReturn
3003 gst_qt_mux_start_file (GstQTMux * qtmux)
3005 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3006 GstFlowReturn ret = GST_FLOW_OK;
3008 GstClockTime reserved_max_duration;
3009 guint reserved_bytes_per_sec_per_trak;
3012 GST_DEBUG_OBJECT (qtmux, "starting file");
3014 GST_OBJECT_LOCK (qtmux);
3015 reserved_max_duration = qtmux->reserved_max_duration;
3016 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
3017 GST_OBJECT_UNLOCK (qtmux);
3020 gst_caps_copy (gst_pad_get_pad_template_caps (GST_AGGREGATOR_SRC_PAD
3022 /* qtmux has structure with and without variant, remove all but the first */
3023 g_assert (gst_caps_truncate (caps));
3024 gst_aggregator_set_src_caps (GST_AGGREGATOR (qtmux), caps);
3025 gst_caps_unref (caps);
3027 /* Default is 'normal' mode */
3028 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
3030 /* Require a sensible fragment duration when muxing
3031 * using the ISML muxer */
3032 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
3033 qtmux->fragment_duration == 0)
3036 if (qtmux->fragment_duration > 0) {
3037 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
3038 if (qtmux->streamable
3039 && qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_DASH_OR_MSS) {
3040 qtmux->fragment_mode = GST_QT_MUX_FRAGMENT_STREAMABLE;
3042 } else if (qtmux->fast_start) {
3043 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
3044 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
3045 if (reserved_max_duration == 0) {
3046 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3047 ("reserved-max-duration of 0 is not allowed"), (NULL));
3048 return GST_FLOW_ERROR;
3050 if (qtmux->reserved_prefill)
3051 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
3053 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
3056 qtmux->downstream_seekable = gst_qt_mux_downstream_is_seekable (qtmux);
3057 switch (qtmux->mux_mode) {
3058 case GST_QT_MUX_MODE_MOOV_AT_END:
3060 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3061 /* We have to be able to seek to rewrite the mdat header, or any
3062 * moov atom we write will not be visible in the file, because an
3063 * MDAT with 0 as the size covers the rest of the file. A file
3064 * with no moov is not playable, so error out now. */
3065 if (!qtmux->downstream_seekable) {
3066 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3067 ("Downstream is not seekable - will not be able to create a playable file"),
3069 return GST_FLOW_ERROR;
3071 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3072 GST_WARNING_OBJECT (qtmux,
3073 "Robust muxing requires reserved-moov-update-period to be set");
3076 case GST_QT_MUX_MODE_FAST_START:
3077 break; /* Don't need seekability, ignore */
3078 case GST_QT_MUX_MODE_FRAGMENTED:
3079 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_STREAMABLE)
3081 if (!qtmux->downstream_seekable) {
3082 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_DASH_OR_MSS) {
3083 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
3084 "streamable=false. Will ignore that and create streamable output "
3086 qtmux->streamable = TRUE;
3087 g_object_notify (G_OBJECT (qtmux), "streamable");
3088 qtmux->fragment_mode = GST_QT_MUX_FRAGMENT_STREAMABLE;
3092 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3093 if (!qtmux->downstream_seekable) {
3094 GST_WARNING_OBJECT (qtmux,
3095 "downstream is not seekable, will not be able "
3096 "to trim samples table at the end if less than reserved-duration is "
3102 GST_OBJECT_LOCK (qtmux);
3104 if (qtmux->timescale == 0) {
3105 guint32 suggested_timescale = 0;
3107 /* Calculate a reasonable timescale for the moov:
3108 * If there is video, it is the biggest video track timescale or an even
3109 * multiple of it if it's smaller than 1800.
3110 * Otherwise it is 1800 */
3111 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3112 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
3118 if (!qpad->trak->mdia.minf.vmhd)
3121 suggested_timescale =
3122 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3125 if (suggested_timescale == 0)
3126 suggested_timescale = 1800;
3128 while (suggested_timescale < 1800)
3129 suggested_timescale *= 2;
3131 qtmux->timescale = suggested_timescale;
3134 /* Set width/height/timescale of any closed caption tracks to that of the
3135 * first video track */
3137 guint video_width = 0, video_height = 0;
3138 guint32 video_timescale = 0;
3141 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3142 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
3147 /* Not closed caption */
3148 if (qpad->trak->mdia.hdlr.handler_type != FOURCC_clcp)
3151 if (video_width == 0 || video_height == 0 || video_timescale == 0) {
3154 for (l2 = GST_ELEMENT_CAST (qtmux)->sinkpads; l2; l2 = l2->next) {
3155 GstQTMuxPad *qpad2 = (GstQTMuxPad *) l2->data;
3161 if (!qpad2->trak->mdia.minf.vmhd)
3164 video_width = qpad2->trak->tkhd.width;
3165 video_height = qpad2->trak->tkhd.height;
3166 video_timescale = qpad2->trak->mdia.mdhd.time_info.timescale;
3170 qpad->trak->tkhd.width = video_width << 16;
3171 qpad->trak->tkhd.height = video_height << 16;
3172 qpad->trak->mdia.mdhd.time_info.timescale = video_timescale;
3176 /* initialize our moov recovery file */
3177 if (qtmux->moov_recov_file_path) {
3178 gst_qt_mux_prepare_moov_recovery (qtmux);
3181 /* Make sure the first time we update the moov, we'll
3182 * include any tagsetter tags */
3183 qtmux->tags_changed = TRUE;
3185 GST_OBJECT_UNLOCK (qtmux);
3188 * send mdat header if already needed, and mark position for later update.
3189 * We don't send ftyp now if we are on fast start mode, because we can
3190 * better fine tune using the information we gather to create the whole moov
3193 switch (qtmux->mux_mode) {
3194 case GST_QT_MUX_MODE_MOOV_AT_END:
3195 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3196 if (ret != GST_FLOW_OK)
3199 /* Store this as the mdat offset for later updating
3200 * when we write the moov */
3201 qtmux->mdat_pos = qtmux->header_size;
3202 /* extended atom in case we go over 4GB while writing and need
3203 * the full 64-bit atom */
3204 if (qtmux->downstream_seekable)
3206 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3209 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3210 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3211 if (ret != GST_FLOW_OK)
3214 /* Pad ftyp out to an 8-byte boundary before starting the moov
3215 * ping pong region. It should be well less than 1 disk sector,
3216 * unless there's a bajillion compatible types listed,
3217 * but let's be sure the free atom doesn't cross a sector
3218 * boundary anyway */
3219 if (qtmux->header_size % 8) {
3220 /* Extra 8 bytes for the padding free atom header */
3221 guint padding = (guint) (16 - (qtmux->header_size % 8));
3222 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3224 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3226 if (ret != GST_FLOW_OK)
3230 /* Store this as the moov offset for later updating.
3231 * We record mdat position below */
3232 qtmux->moov_pos = qtmux->header_size;
3234 /* Set up the initial 'ping' state of the ping-pong buffers */
3235 qtmux->reserved_moov_first_active = TRUE;
3237 gst_qt_mux_configure_moov (qtmux);
3238 gst_qt_mux_setup_metadata (qtmux);
3239 /* Empty free atom to begin, starting on an 8-byte boundary */
3240 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3241 if (ret != GST_FLOW_OK)
3243 /* Moov header, not padded yet */
3244 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3245 if (ret != GST_FLOW_OK)
3247 /* The moov we just sent contains the 'base' size of the moov, before
3248 * we put in any time-dependent per-trak data. Use that to make
3249 * a good estimate of how much extra to reserve */
3250 /* Calculate how much space to reserve for our MOOV atom.
3251 * We actually reserve twice that, for ping-pong buffers */
3252 qtmux->base_moov_size = qtmux->last_moov_size;
3253 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3254 qtmux->base_moov_size);
3255 qtmux->reserved_moov_size = qtmux->base_moov_size +
3256 gst_util_uint64_scale (reserved_max_duration,
3257 reserved_bytes_per_sec_per_trak *
3258 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3260 /* Need space for at least 4 atom headers. More really, but
3261 * this as an absolute minimum */
3262 if (qtmux->reserved_moov_size < 4 * 8)
3263 goto reserved_moov_too_small;
3265 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3266 2 * qtmux->reserved_moov_size + 16);
3268 GST_OBJECT_LOCK (qtmux);
3269 qtmux->reserved_duration_remaining =
3270 gst_util_uint64_scale (qtmux->reserved_moov_size -
3271 qtmux->base_moov_size, GST_SECOND,
3272 reserved_bytes_per_sec_per_trak *
3273 atom_moov_get_trak_count (qtmux->moov));
3274 GST_OBJECT_UNLOCK (qtmux);
3276 /* Now that we know how much reserved space is targeted,
3277 * output a free atom to fill the extra reserved */
3278 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3279 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3280 if (ret != GST_FLOW_OK)
3283 /* Then a free atom containing 'pong' buffer, with an
3284 * extra 8 bytes to account for the free atom header itself */
3285 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3286 qtmux->reserved_moov_size + 8, FALSE);
3287 if (ret != GST_FLOW_OK)
3290 /* extra atoms go after the free/moov(s), before the mdat */
3292 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3293 if (ret != GST_FLOW_OK)
3296 qtmux->mdat_pos = qtmux->header_size;
3297 /* extended atom in case we go over 4GB while writing and need
3298 * the full 64-bit atom */
3300 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3303 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3307 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3308 if (ret != GST_FLOW_OK)
3311 /* Store this as the moov offset for later updating.
3312 * We record mdat position below */
3313 qtmux->moov_pos = qtmux->header_size;
3315 if (!gst_qt_mux_prefill_samples (qtmux)) {
3316 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3317 ("Unsupported codecs or configuration for prefill mode"), (NULL));
3319 return GST_FLOW_ERROR;
3322 gst_qt_mux_update_global_statistics (qtmux);
3323 gst_qt_mux_configure_moov (qtmux);
3324 gst_qt_mux_update_edit_lists (qtmux);
3325 gst_qt_mux_setup_metadata (qtmux);
3327 /* Moov header with pre-filled samples */
3328 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3329 if (ret != GST_FLOW_OK)
3332 GST_OBJECT_LOCK (qtmux);
3333 atom_size = 12 * g_list_length (GST_ELEMENT (qtmux)->sinkpads) + 8;
3334 GST_OBJECT_UNLOCK (qtmux);
3336 /* last_moov_size now contains the full size of the moov, moov_pos the
3337 * position. This allows us to rewrite it in the very end as needed */
3338 qtmux->reserved_moov_size = qtmux->last_moov_size + atom_size;
3340 /* Send an additional free atom at the end so we definitely have space
3341 * to rewrite the moov header at the end and remove the samples that
3342 * were not actually written */
3344 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, atom_size,
3346 if (ret != GST_FLOW_OK)
3349 /* extra atoms go after the free/moov(s), before the mdat */
3351 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3352 if (ret != GST_FLOW_OK)
3355 qtmux->mdat_pos = qtmux->header_size;
3357 /* And now send the mdat header */
3359 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3360 qtmux->mdat_size, TRUE, FALSE);
3362 /* chunks position is set relative to the first byte of the
3363 * MDAT atom payload. Set the overall offset into the file */
3364 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3367 gst_qt_mux_seek_to (qtmux, qtmux->moov_pos);
3369 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3370 if (ret != GST_FLOW_OK)
3373 gst_qt_mux_seek_to (qtmux, qtmux->header_size);
3376 GST_OBJECT_LOCK (qtmux);
3377 qtmux->current_chunk_size = 0;
3378 qtmux->current_chunk_duration = 0;
3379 qtmux->current_chunk_offset = -1;
3380 qtmux->mdat_size = 0;
3381 qtmux->current_pad = NULL;
3382 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3384 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3385 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3387 qtpad->total_bytes = 0;
3388 qtpad->total_duration = 0;
3389 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3390 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3391 qtpad->sample_offset = 0;
3393 GST_OBJECT_UNLOCK (qtmux);
3397 case GST_QT_MUX_MODE_FAST_START:
3398 GST_OBJECT_LOCK (qtmux);
3399 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3400 if (!qtmux->fast_start_file)
3402 GST_OBJECT_UNLOCK (qtmux);
3403 /* send a dummy buffer for preroll */
3404 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3406 case GST_QT_MUX_MODE_FRAGMENTED:
3407 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3408 if (ret != GST_FLOW_OK)
3411 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3412 qtmux->fragment_duration);
3413 qtmux->fragment_sequence = 0;
3414 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE) {
3415 /* Store this as the mdat offset for later updating
3416 * when we write the moov */
3417 qtmux->mdat_pos = qtmux->header_size;
3418 /* extended atom in case we go over 4GB while writing and need
3419 * the full 64-bit atom */
3421 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3423 if (ret != GST_FLOW_OK)
3426 /* store the moov pos so we can update the duration later
3427 * in non-streamable mode */
3428 qtmux->moov_pos = qtmux->header_size;
3430 /* prepare moov and/or tags */
3431 qtmux->fragment_sequence++;
3432 gst_qt_mux_configure_moov (qtmux);
3433 gst_qt_mux_setup_metadata (qtmux);
3435 gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3436 if (ret != GST_FLOW_OK)
3440 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size,
3442 if (ret != GST_FLOW_OK)
3445 /* prepare index if not streamable, or overwriting with moov */
3446 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_DASH_OR_MSS)
3447 qtmux->mfra = atom_mfra_new (qtmux->context);
3455 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3456 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3457 return GST_FLOW_ERROR;
3459 reserved_moov_too_small:
3461 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3462 ("Not enough reserved space for creating headers"), (NULL));
3463 return GST_FLOW_ERROR;
3467 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3468 (("Could not open temporary file \"%s\""),
3469 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3470 GST_OBJECT_UNLOCK (qtmux);
3471 return GST_FLOW_ERROR;
3475 static GstFlowReturn
3476 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3478 GstFlowReturn ret = GST_FLOW_OK;
3479 GList *sinkpads, *l;
3481 GST_OBJECT_LOCK (qtmux);
3482 sinkpads = g_list_copy_deep (GST_ELEMENT_CAST (qtmux)->sinkpads,
3483 (GCopyFunc) gst_object_ref, NULL);
3484 GST_OBJECT_UNLOCK (qtmux);
3486 for (l = sinkpads; l; l = l->next) {
3487 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3489 /* avoid add_buffer complaining if not negotiated
3490 * in which case no buffers either, so skipping */
3491 if (!qtpad->fourcc) {
3492 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3493 GST_PAD_NAME (qtpad));
3497 /* send last buffer; also flushes possibly queued buffers/ts */
3498 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3499 GST_PAD_NAME (qtpad));
3500 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3501 if (ret != GST_FLOW_OK) {
3502 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3503 "flow return: %s", GST_PAD_NAME (qtpad), gst_flow_get_name (ret));
3507 g_list_free_full (sinkpads, gst_object_unref);
3513 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3517 /* for setting some subtitles fields */
3518 guint max_width = 0;
3519 guint max_height = 0;
3521 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3523 GST_OBJECT_LOCK (qtmux);
3524 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3525 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3527 if (!qtpad->fourcc) {
3528 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3529 GST_PAD_NAME (qtpad));
3533 /* having flushed above, can check for buffers now */
3534 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3535 GstClockTime first_pts_in = qtpad->first_ts;
3536 /* it should be, since we got first_ts by adding adjustment
3537 * to a positive incoming PTS */
3538 if (qtpad->dts_adjustment <= first_pts_in)
3539 first_pts_in -= qtpad->dts_adjustment;
3540 /* determine max stream duration */
3541 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3542 || qtpad->last_dts > qtmux->last_dts) {
3543 qtmux->last_dts = qtpad->last_dts;
3545 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3546 || first_pts_in < qtmux->first_ts) {
3547 /* we need the original incoming PTS here, as this first_ts
3548 * is used in update_edit_lists to construct the edit list that arrange
3549 * for sync'ed streams. The first_ts is most likely obtained from
3550 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3551 * so it makes no difference, though it matters in other cases */
3552 qtmux->first_ts = first_pts_in;
3556 /* subtitles need to know the video width/height,
3557 * it is stored shifted 16 bits to the left according to the
3559 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3560 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3562 /* update average bitrate of streams if needed */
3564 guint32 avgbitrate = 0;
3565 guint32 maxbitrate = qtpad->max_bitrate;
3567 if (qtpad->avg_bitrate)
3568 avgbitrate = qtpad->avg_bitrate;
3569 else if (qtpad->total_duration > 0)
3570 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3571 8 * GST_SECOND, qtpad->total_duration);
3573 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3576 GST_OBJECT_UNLOCK (qtmux);
3578 /* need to update values on subtitle traks now that we know the
3579 * max width and height */
3580 GST_OBJECT_LOCK (qtmux);
3581 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3582 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3584 if (!qtpad->fourcc) {
3585 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3586 GST_PAD_NAME (qtpad));
3590 if (qtpad->fourcc == FOURCC_tx3g) {
3591 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3594 GST_OBJECT_UNLOCK (qtmux);
3597 /* Called after gst_qt_mux_update_global_statistics() updates the
3598 * first_ts tracking, to create/set edit lists for delayed streams */
3600 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3604 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3605 GST_TIME_ARGS (qtmux->first_ts));
3606 /* add/update EDTSs for late streams. configure_moov will have
3607 * set the trak durations above by summing the sample tables,
3608 * here we extend that if needing to insert an empty segment */
3609 GST_OBJECT_LOCK (qtmux);
3610 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3611 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3613 atom_trak_edts_clear (qtpad->trak);
3615 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3616 guint32 lateness = 0;
3617 guint32 duration = qtpad->trak->tkhd.duration;
3620 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3623 GstClockTime diff, trak_lateness;
3625 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3626 lateness = gst_util_uint64_scale_round (diff,
3627 qtmux->timescale, GST_SECOND);
3629 /* Allow up to 1 trak timescale unit of lateness, Such a small
3630 * timestamp/duration can't be represented by the trak-specific parts
3631 * of the headers anyway, so it's irrelevantly small */
3632 trak_lateness = gst_util_uint64_scale (diff,
3633 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3635 if (trak_lateness > 0 && diff > qtmux->start_gap_threshold) {
3636 GST_DEBUG_OBJECT (qtmux,
3637 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3638 GST_PAD_NAME (qtpad), GST_TIME_ARGS (diff));
3640 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3641 (guint32) (1 * 65536.0));
3645 /* Always write an edit list for the whole track. In general this is not
3646 * necessary except for the case of having a gap or DTS adjustment but
3647 * it allows to give the whole track's duration in the usually more
3648 * accurate media timescale
3651 GstClockTime ctts = 0;
3652 guint32 media_start;
3654 if (qtpad->first_ts > qtpad->first_dts)
3655 ctts = qtpad->first_ts - qtpad->first_dts;
3657 media_start = gst_util_uint64_scale_round (ctts,
3658 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3660 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3661 * is empty because there's no gap added above, this call
3662 * will not replace index 1, it will create the entry at index 0.
3663 * Luckily, that's exactly what we want here */
3664 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3665 (guint32) (1 * 65536.0));
3668 /* need to add the empty time to the trak duration */
3669 duration += lateness;
3670 qtpad->trak->tkhd.duration = duration;
3671 if (qtpad->tc_trak) {
3672 qtpad->tc_trak->tkhd.duration = duration;
3673 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3676 /* And possibly grow the moov duration */
3677 if (duration > qtmux->moov->mvhd.time_info.duration) {
3678 qtmux->moov->mvhd.time_info.duration = duration;
3679 qtmux->moov->mvex.mehd.fragment_duration = duration;
3683 GST_OBJECT_UNLOCK (qtmux);
3686 static GstFlowReturn
3687 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTMuxPad * qtpad)
3691 guint64 offset = qtpad->tc_pos;
3692 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3694 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT &&
3695 !qtmux->force_create_timecode_trak)
3698 g_assert (qtpad->tc_pos != -1);
3700 gst_qt_mux_seek_to (qtmux, offset);
3702 buf = gst_buffer_new_and_alloc (4);
3703 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3705 GST_WRITE_UINT32_BE (map.data,
3706 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3707 gst_buffer_unmap (buf, &map);
3709 /* Reset this value, so the timecode won't be re-rewritten */
3712 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3716 unref_buffer_if_set (GstBuffer * buffer)
3719 gst_buffer_unref (buffer);
3722 static GstFlowReturn
3723 gst_qtmux_push_mdat_stored_buffers (GstQTMux * qtmux)
3725 GstFlowReturn ret = GST_FLOW_OK;
3726 GList *l = qtmux->output_buffers;
3727 guint64 mdat_header_size = 0, size = 0;
3729 for (; l; l = g_list_next (l)) {
3730 GstBuffer *buf = (GstBuffer *) l->data;
3732 size += gst_buffer_get_size (buf);
3738 GST_DEBUG_OBJECT (qtmux, "Pushing stored buffers of size %" G_GUINT64_FORMAT
3739 " current mdat size %" G_GUINT64_FORMAT, size, qtmux->mdat_size);
3741 ret = gst_qt_mux_send_mdat_header (qtmux, &mdat_header_size, size,
3742 size > MDAT_LARGE_FILE_LIMIT, FALSE);
3744 /* reset chunking */
3745 qtmux->current_chunk_size = 0;
3746 qtmux->current_chunk_duration = 0;
3747 qtmux->current_chunk_offset = -1;
3749 /* on the first mdat, we need to offset the header by the mdat header size
3750 * as the moov offset is in relation to the first data byte inside the first
3752 if (qtmux->mdat_size == 0)
3753 qtmux->header_size += mdat_header_size;
3754 qtmux->mdat_size += mdat_header_size;
3756 l = qtmux->output_buffers;
3757 while (ret == GST_FLOW_OK && l) {
3758 GstBuffer *buf = (GstBuffer *) l->data;
3760 ret = gst_qt_mux_send_buffer (qtmux, buf, &qtmux->mdat_size, TRUE);
3763 l = g_list_next (l);
3766 g_list_free_full (qtmux->output_buffers,
3767 (GDestroyNotify) unref_buffer_if_set);
3768 qtmux->output_buffers = NULL;
3773 static GstFlowReturn
3774 gst_qt_mux_stop_file (GstQTMux * qtmux)
3776 gboolean ret = GST_FLOW_OK;
3777 guint64 offset = 0, size = 0;
3778 gboolean large_file;
3779 GList *sinkpads, *l;
3781 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3783 /* pushing last buffers for each pad */
3784 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3787 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED
3788 && qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_STREAMABLE) {
3789 /* Streamable mode; no need to write duration or MFRA */
3790 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3794 gst_qt_mux_update_global_statistics (qtmux);
3796 GST_OBJECT_LOCK (qtmux);
3797 sinkpads = g_list_copy_deep (GST_ELEMENT_CAST (qtmux)->sinkpads,
3798 (GCopyFunc) gst_object_ref, NULL);
3799 GST_OBJECT_UNLOCK (qtmux);
3801 for (l = sinkpads; l; l = l->next) {
3802 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
3804 if (qtpad->tc_pos != -1) {
3805 /* File is being stopped and timecode hasn't been updated. Update it now
3806 * with whatever we have */
3807 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3808 if (ret != GST_FLOW_OK) {
3809 g_list_free_full (sinkpads, gst_object_unref);
3815 g_list_free_full (sinkpads, gst_object_unref);
3817 switch (qtmux->mux_mode) {
3818 case GST_QT_MUX_MODE_MOOV_AT_END:{
3819 if (!qtmux->downstream_seekable) {
3820 ret = gst_qtmux_push_mdat_stored_buffers (qtmux);
3821 if (ret != GST_FLOW_OK)
3826 case GST_QT_MUX_MODE_FRAGMENTED:{
3828 GstClockTime duration;
3831 guint8 *data = NULL;
3835 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3836 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3837 goto serialize_error;
3838 buf = _gst_buffer_new_take_data (data, offset);
3839 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3840 if (ret != GST_FLOW_OK)
3844 /* only mvex duration is updated,
3845 * mvhd should be consistent with empty moov
3846 * (but TODO maybe some clients do not handle that well ?) */
3847 duration = gst_util_uint64_scale_round (qtmux->last_dts, qtmux->timescale,
3850 GST_DEBUG_OBJECT (qtmux,
3851 "writing moov with mvhd/mvex duration %" GST_TIME_FORMAT,
3852 GST_TIME_ARGS (qtmux->last_dts));
3853 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE) {
3854 /* seek and overwrite the original moov with an invalid atom */
3855 /* XXX: assumes an extended size atom is not used for the moov */
3857 qtmux->moov->mvhd.time_info.duration = duration;
3859 /* (+4) skip the skip bytes */
3860 gst_qt_mux_seek_to (qtmux, qtmux->moov_pos + 4);
3862 /* invalidate the previous moov */
3863 buf = gst_buffer_new_wrapped (g_strdup ("h"), 1);
3864 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3865 if (ret != GST_FLOW_OK)
3868 /* we want to rewrite the first mdat to cover the entire data before
3870 qtmux->mdat_size = qtmux->header_size - qtmux->mdat_pos - 16;
3872 gst_qt_mux_seek_to (qtmux, qtmux->mdat_pos);
3874 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3875 qtmux->mdat_size, NULL, FALSE);
3876 if (ret != GST_FLOW_OK)
3879 /* Then write the moov atom as in moov-at-end *without* updating the
3881 gst_qt_mux_seek_to (qtmux, qtmux->header_size);
3883 /* revert back to moov-at-end assumptions where header_size is the
3884 * size up to the first byte of data in the mdat */
3885 qtmux->header_size = qtmux->mdat_pos + 16;
3888 qtmux->moov->mvex.mehd.fragment_duration = duration;
3890 /* seek and rewrite the header */
3891 gst_qt_mux_seek_to (qtmux, qtmux->moov_pos);
3892 /* no need to seek back */
3893 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3896 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3897 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3898 if (G_UNLIKELY (ret != GST_FLOW_OK))
3900 /* Finalise by writing the final size into the mdat. Up until now
3901 * it's been 0, which means 'rest of the file'
3902 * No need to seek back after this, we won't write any more */
3903 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3904 qtmux->mdat_size, NULL, TRUE);
3906 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3908 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3910 GST_OBJECT_LOCK (qtmux);
3911 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
3912 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
3914 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3916 /* Get the block index of the last sample we wrote, not of the next
3917 * sample we would write */
3918 block_idx = prefill_get_block_index (qtmux, qpad);
3921 if (block_idx > 0) {
3923 guint64 nsamples = 0;
3926 n = atom_array_get_len (&stbl->stts.entries);
3927 for (i = 0; i < n; i++) {
3928 entry = &atom_array_index (&stbl->stts.entries, i);
3929 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3930 entry->sample_count = qpad->sample_offset - nsamples;
3931 stbl->stts.entries.len = i + 1;
3934 nsamples += entry->sample_count;
3938 stbl->stts.entries.len = 0;
3943 g_assert (stbl->stsz.entries.len == 0);
3944 stbl->stsz.table_size = qpad->sample_offset;
3950 guint64 nsamples = 0;
3951 gint chunk_index = 0;
3952 const TrakBufferEntryInfo *sample_entry;
3954 if (block_idx > 0) {
3956 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3959 n = stbl->stco64.entries.len;
3960 for (i = 0; i < n; i++) {
3961 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3963 if (*entry == sample_entry->chunk_offset) {
3964 stbl->stco64.entries.len = i + 1;
3965 chunk_index = i + 1;
3970 g_assert (chunk_index > 0);
3972 n = stbl->stsc.entries.len;
3973 for (i = 0; i < n; i++) {
3974 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3976 if (entry->first_chunk >= chunk_index)
3981 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3983 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3984 i - 1).samples_per_chunk;
3990 STSCEntry *prev_entry =
3991 &atom_array_index (&stbl->stsc.entries, i - 1);
3994 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3995 if (qpad->sample_offset - nsamples > 0) {
3996 stbl->stsc.entries.len = i;
3997 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3998 qpad->sample_offset - nsamples, stbl->stsd.n_entries);
4000 stbl->stsc.entries.len = i;
4001 stbl->stco64.entries.len--;
4004 /* Everything in a single chunk */
4005 stbl->stsc.entries.len = 0;
4006 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
4007 qpad->sample_offset, stbl->stsd.n_entries);
4010 stbl->stco64.entries.len = 0;
4011 stbl->stsc.entries.len = 0;
4018 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
4019 AtomTREX *trex = walk2->data;
4021 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
4022 trex->track_ID = next_track_id;
4027 qpad->trak->tkhd.track_ID = next_track_id++;
4030 GST_OBJECT_UNLOCK (qtmux);
4032 qtmux->moov->mvhd.next_track_id = next_track_id;
4034 gst_qt_mux_update_global_statistics (qtmux);
4035 gst_qt_mux_configure_moov (qtmux);
4037 gst_qt_mux_update_edit_lists (qtmux);
4039 /* Check if any gap edit lists were added. We don't have any space
4040 * reserved for this in the moov and the pre-finalized moov would have
4041 * broken A/V synchronization. Error out here now
4043 GST_OBJECT_LOCK (qtmux);
4044 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
4045 GstQTMuxPad *qpad = (GstQTMuxPad *) l->data;
4047 if (qpad->trak->edts
4048 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
4049 GST_OBJECT_UNLOCK (qtmux);
4050 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4051 ("Can't support gaps in prefill mode"));
4053 return GST_FLOW_ERROR;
4056 GST_OBJECT_UNLOCK (qtmux);
4058 gst_qt_mux_setup_metadata (qtmux);
4059 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4062 gst_qt_mux_seek_to (qtmux, qtmux->moov_pos);
4065 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4067 if (ret != GST_FLOW_OK)
4070 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
4072 gst_qt_mux_send_free_atom (qtmux, NULL,
4073 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
4076 if (ret != GST_FLOW_OK)
4080 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
4081 qtmux->mdat_size, NULL, FALSE);
4088 /* Moov-at-end or fast-start mode from here down */
4089 gst_qt_mux_configure_moov (qtmux);
4091 gst_qt_mux_update_edit_lists (qtmux);
4093 /* tags into file metadata */
4094 gst_qt_mux_setup_metadata (qtmux);
4096 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
4098 switch (qtmux->mux_mode) {
4099 case GST_QT_MUX_MODE_FAST_START:{
4100 /* if faststart, update the offset of the atoms in the movie with the offset
4101 * that the movie headers before mdat will cause.
4102 * Also, send the ftyp */
4105 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
4106 if (ret != GST_FLOW_OK) {
4109 /* copy into NULL to obtain size */
4110 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
4111 goto serialize_error;
4112 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
4114 offset += qtmux->header_size + (large_file ? 16 : 8);
4116 /* sum up with the extra atoms size */
4117 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
4118 if (ret != GST_FLOW_OK)
4123 offset = qtmux->header_size;
4127 /* Now that we know the size of moov + extra atoms, we can adjust
4128 * the chunk offsets stored into the moov */
4129 atom_moov_chunks_set_offset (qtmux->moov, offset);
4131 /* write out moov and extra atoms */
4132 /* note: as of this point, we no longer care about tracking written data size,
4133 * since there is no more use for it anyway */
4134 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
4135 if (ret != GST_FLOW_OK)
4139 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
4140 if (ret != GST_FLOW_OK)
4143 switch (qtmux->mux_mode) {
4144 case GST_QT_MUX_MODE_MOOV_AT_END:
4146 if (qtmux->downstream_seekable) {
4147 /* mdat needs update iff not using faststart */
4148 GST_DEBUG_OBJECT (qtmux, "updating mdat size at position %"
4149 G_GUINT64_FORMAT " to size %" G_GUINT64_FORMAT, qtmux->mdat_pos,
4151 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
4152 qtmux->mdat_size, NULL, FALSE);
4153 /* note; no seeking back to the end of file is done,
4154 * since we no longer write anything anyway */
4158 case GST_QT_MUX_MODE_FAST_START:
4160 /* send mdat atom and move buffered data into it */
4161 /* mdat_size = accumulated (buffered data) */
4162 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
4164 if (ret != GST_FLOW_OK)
4166 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
4167 if (ret != GST_FLOW_OK)
4171 case GST_QT_MUX_MODE_FRAGMENTED:
4172 g_assert (qtmux->fragment_mode ==
4173 GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE);
4176 g_assert_not_reached ();
4184 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4185 ("Failed to serialize moov"));
4186 return GST_FLOW_ERROR;
4190 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
4191 return GST_FLOW_ERROR;
4196 gst_qtmux_pad_update_fragment_duration (GstElement * element, GstPad * pad,
4199 GstQTMux *qtmux = (GstQTMux *) element;
4200 GstQTMuxPad *qt_pad = GST_QT_MUX_PAD (pad);
4202 qt_pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4203 atom_trak_get_timescale (qt_pad->trak), 1000);
4209 gst_qtmux_pad_collect_traf (GstElement * element, GstPad * pad,
4212 GstQTMuxPad *qt_pad = GST_QT_MUX_PAD (pad);
4213 AtomMOOF *moof = user_data;
4215 GST_TRACE_OBJECT (pad, "adding traf %p to moof %p", qt_pad->traf, moof);
4217 /* takes ownership */
4219 atom_moof_add_traf (moof, qt_pad->traf);
4220 qt_pad->traf = NULL;
4225 static GstFlowReturn
4226 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTMuxPad * pad,
4227 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
4228 guint32 delta, guint32 size, guint64 chunk_offset, gboolean sync,
4231 GstFlowReturn ret = GST_FLOW_OK;
4234 GST_LOG_OBJECT (pad, "%p %u %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT,
4235 pad->traf, force, qtmux->current_chunk_offset, chunk_offset);
4237 /* setup if needed */
4238 if (G_UNLIKELY (!pad->traf || force))
4242 /* flush pad fragment if threshold reached,
4243 * or at new keyframe if we should be minding those in the first place */
4244 if (G_UNLIKELY (force || (sync && pad->sync) ||
4245 pad->fragment_duration < (gint64) delta)) {
4247 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE) {
4248 if (qtmux->fragment_sequence == 0) {
4249 /* the first fragment which we write as a moov */
4250 guint64 orig_offset;
4251 guint64 offset = orig_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4252 guint64 chunk_increase, buf_size;
4255 GST_LOG_OBJECT (qtmux, "current file offset calculated to be %"
4256 G_GUINT64_FORMAT " based on mdat pos %" G_GUINT64_FORMAT
4257 " and size %" G_GUINT64_FORMAT, offset, qtmux->mdat_pos,
4260 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
4261 gst_element_foreach_sink_pad (GST_ELEMENT (qtmux),
4262 gst_qtmux_pad_collect_traf, moof);
4263 atom_moof_free (moof);
4265 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
4266 qtmux->mdat_size, NULL, FALSE);
4267 if (ret != GST_FLOW_OK)
4270 /* seek back to the end of the file */
4271 qtmux->moov_pos = offset;
4272 gst_qt_mux_seek_to (qtmux, qtmux->moov_pos);
4274 /* update moov data */
4275 gst_qt_mux_update_global_statistics (qtmux);
4276 gst_qt_mux_configure_moov_full (qtmux, TRUE, qtmux->timescale);
4277 gst_qt_mux_update_edit_lists (qtmux);
4278 gst_qt_mux_setup_metadata (qtmux);
4279 /* chunk offset is the offset to the first byte inside the mdat */
4280 atom_moov_chunks_set_offset (qtmux->moov, qtmux->mdat_pos + 16);
4282 ret = gst_qt_mux_send_moov (qtmux, &offset, 0, TRUE, FALSE);
4283 if (ret != GST_FLOW_OK)
4286 /* for the continuation in fragments, header_size is the tracking write
4288 qtmux->header_size = offset;
4289 qtmux->moof_mdat_pos = 0;
4291 buf_size = (buf ? gst_buffer_get_size (buf) : 0);
4293 chunk_increase = offset - orig_offset + 16;
4294 /* we need to undo the addition to qtmux->current_chunk_size of this
4295 * buffer performed in gst_qt_mux_register_buffer_in_chunk() */
4296 chunk_increase += qtmux->current_chunk_size - buf_size;
4297 GST_LOG_OBJECT (qtmux, "We think we have written %" G_GUINT64_FORMAT
4298 " including a moov and mdat header of %" G_GUINT64_FORMAT
4299 ". mangling this buffer's chunk offset from %" G_GUINT64_FORMAT
4300 " to %" G_GUINT64_FORMAT, qtmux->header_size,
4301 offset - orig_offset + 16, chunk_offset,
4302 chunk_offset + chunk_increase);
4303 /* this is the offset for the current chunk that is applied to all subsequent chunks */
4304 chunk_offset += chunk_increase;
4305 qtmux->current_chunk_offset += chunk_increase;
4306 qtmux->current_chunk_size = buf_size;
4307 GST_LOG_OBJECT (qtmux, "change next chunk offset to %" G_GUINT64_FORMAT
4308 " and size to %" G_GUINT64_FORMAT, qtmux->current_chunk_offset,
4309 qtmux->current_chunk_size);
4311 gst_element_foreach_sink_pad (GST_ELEMENT (qtmux),
4312 gst_qtmux_pad_update_fragment_duration, NULL);
4315 guint64 size = 0, offset = 0;
4316 guint8 *data = NULL;
4317 GstBuffer *moof_buffer;
4318 guint64 moof_size = 0, buf_size;
4319 guint64 chunk_increase;
4321 /* rewrite the mdat header */
4322 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->moof_mdat_pos,
4323 qtmux->header_size - qtmux->moof_mdat_pos - 16, NULL, FALSE);
4324 if (ret != GST_FLOW_OK)
4327 /* reseek back to the current position */
4328 gst_qt_mux_seek_to (qtmux, qtmux->header_size);
4330 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
4331 gst_element_foreach_sink_pad (GST_ELEMENT (qtmux),
4332 gst_qtmux_pad_collect_traf, moof);
4333 atom_moof_set_base_offset (moof, qtmux->moof_mdat_pos);
4334 atom_moof_copy_data (moof, &data, &size, &offset);
4335 moof_buffer = _gst_buffer_new_take_data (data, offset);
4336 moof_size = gst_buffer_get_size (moof_buffer);
4338 atom_moof_free (moof);
4339 /* now we know where moof ends up, update offset in tfra */
4341 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
4343 GST_LOG_OBJECT (qtmux, "writing moof of size %" G_GUINT64_FORMAT,
4346 gst_qt_mux_send_buffer (qtmux, moof_buffer, &qtmux->header_size,
4348 if (ret != GST_FLOW_OK)
4349 goto moof_send_error;
4350 qtmux->moof_mdat_pos = 0;
4352 /* if we are writing a final moov, then we need to increase our chunk
4353 * offsets to include the moof/mdat headers that were just written so
4354 * so that they are correctly skipped over.
4356 buf_size = (buf ? gst_buffer_get_size (buf) : 0);
4357 chunk_increase = moof_size + 16;
4358 /* we need to undo the addition to qtmux->current_chunk_size of this
4359 * buffer performed in gst_qt_mux_register_buffer_in_chunk() */
4360 chunk_increase += qtmux->current_chunk_size - buf_size;
4361 GST_LOG_OBJECT (qtmux, "We think we have currently written %"
4362 G_GUINT64_FORMAT " including a moof of %" G_GUINT64_FORMAT
4363 " mangling this buffer's chunk offset from %" G_GUINT64_FORMAT
4364 " to %" G_GUINT64_FORMAT, qtmux->header_size, moof_size,
4365 chunk_offset, chunk_offset + chunk_increase);
4366 chunk_offset += chunk_increase;
4367 /* this is the offset for the next chunk */
4368 qtmux->current_chunk_offset += chunk_increase;
4369 qtmux->current_chunk_size = buf_size;
4370 GST_LOG_OBJECT (qtmux, "change next chunk offset to %" G_GUINT64_FORMAT
4371 " and size to %" G_GUINT64_FORMAT, qtmux->current_chunk_offset,
4372 qtmux->current_chunk_size);
4374 /* if we are are generating a moof, it is for all streams */
4375 gst_element_foreach_sink_pad (GST_ELEMENT (qtmux),
4376 gst_qtmux_pad_update_fragment_duration, NULL);
4379 /* not moov-related. writes out moof then mdat for a single stream only */
4381 guint64 size = 0, offset = 0;
4382 guint8 *data = NULL;
4383 GstBuffer *moof_buffer;
4384 guint i, total_size;
4385 AtomTRUN *first_trun;
4388 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4390 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
4393 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
4394 /* takes ownership */
4395 atom_moof_add_traf (moof, pad->traf);
4396 /* write the offset into the first 'trun'. All other truns are assumed
4397 * to follow on from this trun. Skip over the mdat header (+12) */
4398 atom_moof_copy_data (moof, &data, &size, &offset);
4399 first_trun = (AtomTRUN *) pad->traf->truns->data;
4400 atom_trun_set_offset (first_trun, offset + 12);
4403 atom_moof_copy_data (moof, &data, &size, &offset);
4404 moof_buffer = _gst_buffer_new_take_data (data, offset);
4406 atom_moof_free (moof);
4408 /* now we know where moof ends up, update offset in tfra */
4410 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
4412 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
4413 gst_buffer_get_size (moof_buffer));
4415 gst_qt_mux_send_buffer (qtmux, moof_buffer, &qtmux->header_size,
4417 if (ret != GST_FLOW_OK)
4418 goto moof_send_error;
4420 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
4421 atom_array_get_len (&pad->fragment_buffers), total_size);
4423 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
4425 if (ret != GST_FLOW_OK)
4426 goto mdat_header_send_error;
4428 for (index = 0; index < atom_array_get_len (&pad->fragment_buffers);
4430 GST_DEBUG_OBJECT (qtmux, "sending fragment %p",
4431 atom_array_index (&pad->fragment_buffers, index));
4433 gst_qt_mux_send_buffer (qtmux,
4434 atom_array_index (&pad->fragment_buffers, index),
4435 &qtmux->header_size, FALSE);
4436 if (ret != GST_FLOW_OK)
4437 goto fragment_buf_send_error;
4441 atom_array_clear (&pad->fragment_buffers);
4442 qtmux->fragment_sequence++;
4447 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE
4448 && qtmux->fragment_sequence == 0) {
4449 atom_trak_add_samples (pad->trak, nsamples, (gint32) delta, size,
4450 chunk_offset, sync, pts_offset);
4452 ret = gst_qt_mux_send_buffer (qtmux, buf, &qtmux->mdat_size, TRUE);
4453 if (ret != GST_FLOW_OK)
4457 if (G_UNLIKELY (force))
4461 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4462 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4463 atom_trak_get_timescale (pad->trak), 1000);
4465 pad->fragment_duration -= delta;
4468 } else if (G_UNLIKELY (!pad->traf)) {
4469 GstClockTime first_dts = 0, current_dts;
4470 gint64 first_qt_dts;
4471 GST_LOG_OBJECT (pad, "setting up new fragment");
4472 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4473 atom_array_init (&pad->fragment_buffers, 512);
4474 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4475 atom_trak_get_timescale (pad->trak), 1000);
4477 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
4478 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
4479 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
4481 if (GST_CLOCK_TIME_IS_VALID (pad->first_dts))
4482 first_dts = pad->first_dts;
4485 gst_util_uint64_scale (dts, GST_SECOND,
4486 atom_trak_get_timescale (pad->trak));
4488 gst_util_uint64_scale (first_dts, atom_trak_get_timescale (pad->trak),
4490 GST_DEBUG_OBJECT (pad, "calculating base decode time with first dts %"
4491 G_GINT64_FORMAT " (%" GST_TIME_FORMAT ") and current dts %"
4492 G_GINT64_FORMAT " (%" GST_TIME_FORMAT ") of %" G_GINT64_FORMAT " (%"
4493 GST_STIME_FORMAT ")", first_qt_dts, GST_TIME_ARGS (first_dts), dts,
4494 GST_TIME_ARGS (current_dts), dts - first_qt_dts,
4495 GST_STIME_ARGS (current_dts - first_dts));
4496 atom_traf_set_base_decode_time (pad->traf, dts - first_qt_dts);
4499 if (qtmux->fragment_mode == GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE) {
4500 if (qtmux->fragment_sequence > 0 && !force) {
4501 if (qtmux->moof_mdat_pos == 0) {
4502 /* send temporary mdat */
4503 qtmux->moof_mdat_pos = qtmux->header_size;
4504 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0,
4506 if (ret != GST_FLOW_OK)
4507 goto mdat_header_send_error;
4511 atom_trak_add_samples (pad->trak, nsamples, (gint32) delta, size,
4512 chunk_offset, sync, pts_offset);
4513 atom_traf_add_samples (pad->traf, nsamples, delta, size,
4514 qtmux->header_size - qtmux->moof_mdat_pos, sync, pts_offset,
4517 ret = gst_qt_mux_send_buffer (qtmux, buf, &qtmux->header_size, TRUE);
4518 if (ret != GST_FLOW_OK)
4524 /* add buffer and metadata */
4525 atom_traf_add_samples (pad->traf, nsamples, delta, size, 0, sync,
4526 pts_offset, pad->sync && sync);
4527 GST_LOG_OBJECT (qtmux, "adding buffer %p to fragments", buf);
4528 atom_array_append (&pad->fragment_buffers, g_steal_pointer (&buf), 256);
4530 pad->fragment_duration -= delta;
4533 guint32 sn = atom_traf_get_sample_num (pad->traf);
4535 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
4536 atom_tfra_add_entry (pad->tfra, dts, sn);
4539 if (G_UNLIKELY (force))
4548 GST_ERROR_OBJECT (qtmux, "Failed to send moof buffer");
4549 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++)
4550 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4551 atom_array_clear (&pad->fragment_buffers);
4552 gst_clear_buffer (&buf);
4557 mdat_header_send_error:
4561 GST_ERROR_OBJECT (qtmux, "Failed to send mdat header");
4562 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++)
4563 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4564 atom_array_clear (&pad->fragment_buffers);
4565 gst_clear_buffer (&buf);
4570 fragment_buf_send_error:
4574 GST_ERROR_OBJECT (qtmux, "Failed to send fragment");
4575 for (i = index + 1; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4576 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4578 atom_array_clear (&pad->fragment_buffers);
4579 gst_clear_buffer (&buf);
4585 /* Here's the clever bit of robust recording: Updating the moov
4586 * header is done using a ping-pong scheme inside 2 blocks of size
4587 * 'reserved_moov_size' at the start of the file, in such a way that the
4588 * file on-disk is always valid if interrupted.
4589 * Inside the reserved space, we have 2 pairs of free + moov atoms
4590 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4591 * at offset "reserved_moov_size".
4593 * 1. Free-A has 0 size payload, moov-A immediately after is
4594 * active/current, and is padded with an internal Free atom to
4595 * end at reserved_space/2. Free-B is at reserved_space/2, sized
4596 * to cover the remaining free space (including moov-B).
4597 * 2. We write moov-B (which is invisible inside free-B), and pad it to
4598 * end at the end of free space. Then, we update free-A to size
4599 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
4600 * free-B header, and makes moov-B active.
4601 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4602 * Change the size of free-A to make moov-A active again.
4603 * 4. Rinse and repeat.
4606 static GstFlowReturn
4607 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4610 guint64 freeA_offset;
4611 guint32 new_freeA_size;
4612 guint64 new_moov_offset;
4614 /* Update moov info, then seek and rewrite the MOOV atom */
4615 gst_qt_mux_update_global_statistics (qtmux);
4616 gst_qt_mux_configure_moov (qtmux);
4618 gst_qt_mux_update_edit_lists (qtmux);
4620 /* tags into file metadata */
4621 gst_qt_mux_setup_metadata (qtmux);
4623 /* chunks position is set relative to the first byte of the
4624 * MDAT atom payload. Set the overall offset into the file */
4625 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4627 /* Calculate which moov to rewrite. qtmux->moov_pos points to
4628 * the start of the free-A header */
4629 freeA_offset = qtmux->moov_pos;
4630 if (qtmux->reserved_moov_first_active) {
4631 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4632 /* After this, freeA will include itself, moovA, plus the freeB
4634 new_freeA_size = qtmux->reserved_moov_size + 16;
4636 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4639 /* the moov we update is after free-A, calculate its offset */
4640 new_moov_offset = freeA_offset + new_freeA_size;
4642 /* Swap ping-pong cadence marker */
4643 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4645 /* seek and rewrite the MOOV atom */
4646 gst_qt_mux_seek_to (qtmux, new_moov_offset);
4649 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4651 if (ret != GST_FLOW_OK)
4654 /* Update the estimated recording space remaining, based on amount used so
4655 * far and duration muxed so far */
4656 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4657 GstClockTime remain;
4658 GstClockTime time_muxed = qtmux->last_dts;
4661 gst_util_uint64_scale (qtmux->reserved_moov_size -
4662 qtmux->last_moov_size, time_muxed,
4663 qtmux->last_moov_size - qtmux->base_moov_size);
4664 /* Always under-estimate slightly, so users
4665 * have time to stop muxing before we run out */
4666 if (remain < GST_SECOND / 2)
4669 remain -= GST_SECOND / 2;
4671 GST_INFO_OBJECT (qtmux,
4672 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4673 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4674 qtmux->reserved_moov_size, qtmux->last_moov_size,
4675 GST_TIME_ARGS (qtmux->last_dts),
4676 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4678 GST_OBJECT_LOCK (qtmux);
4679 qtmux->reserved_duration_remaining = remain;
4680 qtmux->muxed_since_last_update = 0;
4681 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4682 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4683 GST_OBJECT_UNLOCK (qtmux);
4687 /* Now update the moov-A size. Don't pass offset, since we don't need
4688 * send_free_atom() to seek for us - all our callers seek back to
4689 * where they need after this, or they don't need it */
4690 gst_qt_mux_seek_to (qtmux, freeA_offset);
4692 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4697 static GstFlowReturn
4698 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4700 GstFlowReturn flow_ret;
4702 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4704 GST_OBJECT_LOCK (qtmux);
4706 /* Update the offset of how much we've muxed, so the
4707 * report of remaining space keeps counting down */
4708 if (position > qtmux->last_moov_update &&
4709 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4710 GST_LOG_OBJECT (qtmux,
4711 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4712 qtmux->muxed_since_last_update);
4713 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4716 /* Next, check if we're supposed to send periodic moov updates downstream */
4717 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4718 GST_OBJECT_UNLOCK (qtmux);
4722 /* Update if position is > the threshold or there's been no update yet */
4723 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4724 (position <= qtmux->last_moov_update ||
4725 (position - qtmux->last_moov_update) <
4726 qtmux->reserved_moov_update_period)) {
4727 GST_OBJECT_UNLOCK (qtmux);
4728 return GST_FLOW_OK; /* No update needed yet */
4731 qtmux->last_moov_update = position;
4732 GST_OBJECT_UNLOCK (qtmux);
4734 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4735 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4736 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4738 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4739 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4742 /* Seek back to previous position */
4743 gst_qt_mux_seek_to (qtmux, mdat_offset);
4748 static GstFlowReturn
4749 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTMuxPad * pad,
4750 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4751 gint64 last_dts, gint64 scaled_duration, guint sample_size,
4752 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4754 GstFlowReturn ret = GST_FLOW_OK;
4756 /* note that a new chunk is started each time (not fancy but works) */
4757 if (qtmux->moov_recov_file) {
4758 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4759 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4760 do_pts, pts_offset)) {
4761 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4762 "recovery file, disabling recovery");
4763 fclose (qtmux->moov_recov_file);
4764 qtmux->moov_recov_file = NULL;
4768 switch (qtmux->mux_mode) {
4769 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4770 const TrakBufferEntryInfo *sample_entry;
4771 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4773 if (block_idx >= pad->samples->len) {
4774 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4775 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4776 block_idx, pad->samples->len));
4777 gst_buffer_unref (buffer);
4778 return GST_FLOW_ERROR;
4781 /* Check if all values are as expected */
4783 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4785 /* Allow +/- 1 difference for the scaled_duration to allow
4786 * for some rounding errors
4788 if (sample_entry->nsamples != nsamples
4789 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4790 || sample_entry->size != sample_size
4791 || sample_entry->chunk_offset != chunk_offset
4792 || sample_entry->pts_offset != pts_offset
4793 || sample_entry->sync != sync) {
4794 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4795 ("Unexpected values in sample %" G_GUINT64_FORMAT,
4796 pad->sample_offset + 1));
4797 GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4798 "chunk offset %" G_GUINT64_FORMAT ", "
4799 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4800 sample_entry->nsamples,
4801 sample_entry->delta,
4803 sample_entry->chunk_offset,
4804 sample_entry->pts_offset, sample_entry->sync);
4805 GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4806 "chunk offset %" G_GUINT64_FORMAT ", "
4807 "pts offset %" G_GUINT64_FORMAT ", sync %d",
4809 (guint) scaled_duration,
4810 sample_size, chunk_offset, pts_offset, sync);
4812 gst_buffer_unref (buffer);
4813 return GST_FLOW_ERROR;
4816 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4819 case GST_QT_MUX_MODE_MOOV_AT_END:
4820 case GST_QT_MUX_MODE_FAST_START:
4821 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4822 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4823 sample_size, chunk_offset, sync, pts_offset);
4824 if (qtmux->mux_mode == GST_QT_MUX_MODE_MOOV_AT_END
4825 && !qtmux->downstream_seekable) {
4826 qtmux->output_buffers = g_list_append (qtmux->output_buffers, buffer);
4829 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4831 /* Check if it's time to re-write the headers in robust-recording mode */
4832 if (ret == GST_FLOW_OK
4833 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4834 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4836 case GST_QT_MUX_MODE_FRAGMENTED:
4837 /* ensure that always sync samples are marked as such */
4838 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4839 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4840 sample_size, chunk_offset, !pad->sync || sync, pts_offset);
4848 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTMuxPad * pad,
4849 guint buffer_size, GstClockTime duration)
4851 /* not that much happens here,
4852 * but updating any of this very likely needs to happen all in sync,
4853 * unless there is a very good reason not to */
4855 /* for computing the avg bitrate */
4856 pad->total_bytes += buffer_size;
4857 pad->total_duration += duration;
4858 /* for keeping track of where we are in chunk;
4859 * ensures that data really is located as recorded in atoms */
4861 qtmux->current_chunk_size += buffer_size;
4862 qtmux->current_chunk_duration += duration;
4865 static GstFlowReturn
4866 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTMuxPad * pad,
4867 GstBuffer * buf, GstFlowReturn ret)
4869 GstVideoTimeCodeMeta *tc_meta;
4870 GstVideoTimeCode *tc;
4873 guint32 frames_since_daily_jam;
4874 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4876 if (!pad->trak->is_video)
4879 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT &&
4880 !qtmux->force_create_timecode_trak)
4883 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4886 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4892 /* This means we never got a timecode before */
4893 if (pad->first_tc == NULL) {
4896 #ifndef GST_DISABLE_GST_DEBUG
4897 gchar *tc_str = gst_video_time_code_to_string (tc);
4898 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4901 g_assert (pad->tc_trak == NULL);
4902 pad->first_tc = gst_video_time_code_copy (tc);
4904 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED
4905 && qtmux->fragment_sequence > 0) {
4906 offset = &qtmux->header_size;
4908 offset = &qtmux->mdat_size;
4910 /* If frames are out of order, the frame we're currently getting might
4911 * not be the first one. Just write a 0 timecode for now and wait
4912 * until we receive a timecode that's lower than the current one */
4913 if (pad->is_out_of_order) {
4914 pad->first_pts = GST_BUFFER_PTS (buf);
4915 frames_since_daily_jam = 0;
4916 /* Position to rewrite */
4917 pad->tc_pos = *offset;
4919 frames_since_daily_jam =
4920 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4921 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4923 /* Write the timecode trak now */
4924 pad->tc_trak = atom_trak_new (qtmux->context);
4925 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4927 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4928 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4930 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4931 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4933 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4934 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4935 g_assert (szret == 4);
4937 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, *offset, FALSE, 0);
4939 if (qtmux->mux_mode == GST_QT_MUX_MODE_MOOV_AT_END
4940 && !qtmux->downstream_seekable) {
4941 ret = gst_qtmux_push_mdat_stored_buffers (qtmux);
4942 qtmux->output_buffers = g_list_append (qtmux->output_buffers, tc_buf);
4945 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, offset, TRUE);
4948 /* Need to reset the current chunk (of the previous pad) here because
4949 * some other data was written now above, and the pad has to start a
4951 qtmux->current_chunk_offset = -1;
4952 qtmux->current_chunk_size = 0;
4953 qtmux->current_chunk_duration = 0;
4954 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4955 frames_since_daily_jam =
4956 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4957 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4959 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4960 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4961 g_assert (szret == 4);
4963 if (qtmux->mux_mode == GST_QT_MUX_MODE_MOOV_AT_END
4964 && !qtmux->downstream_seekable) {
4965 ret = gst_qtmux_push_mdat_stored_buffers (qtmux);
4966 qtmux->output_buffers = g_list_append (qtmux->output_buffers, tc_buf);
4969 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4973 qtmux->current_chunk_offset = -1;
4974 qtmux->current_chunk_size = 0;
4975 qtmux->current_chunk_duration = 0;
4976 } else if (pad->is_out_of_order) {
4977 /* Check for a lower timecode than the one stored */
4978 g_assert (pad->tc_trak != NULL);
4979 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4980 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4981 gst_video_time_code_free (pad->first_tc);
4982 pad->first_tc = gst_video_time_code_copy (tc);
4985 guint64 bk_size = qtmux->mdat_size;
4986 /* If this frame's DTS is after the first PTS received, it means
4987 * we've already received the first frame to be presented. Otherwise
4988 * the decoder would need to go back in time */
4989 gst_qt_mux_update_timecode (qtmux, pad);
4991 /* Reset writing position */
4992 gst_qt_mux_seek_to (qtmux, bk_size);
5000 * Here we push the buffer and update the tables in the track atoms
5002 static GstFlowReturn
5003 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTMuxPad * pad, GstBuffer * buf)
5005 GstBuffer *last_buf = NULL;
5006 GstClockTime duration;
5007 guint nsamples, sample_size;
5008 guint64 chunk_offset;
5009 gint64 last_dts, scaled_duration;
5010 gint64 pts_offset = 0;
5011 gboolean sync = FALSE;
5012 GstFlowReturn ret = GST_FLOW_OK;
5015 /* GAP event, nothing to do */
5016 if (buf && gst_buffer_get_size (buf) == 0 &&
5017 GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_GAP)) {
5018 gst_buffer_unref (buf);
5023 goto not_negotiated;
5025 /* if this pad has a prepare function, call it */
5026 if (pad->prepare_buf_func != NULL) {
5029 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
5030 if (buf && !new_buf)
5035 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
5036 if (ret != GST_FLOW_OK) {
5038 gst_buffer_unref (buf);
5042 last_buf = pad->last_buf;
5043 pad->last_buf = buf;
5045 if (last_buf == NULL) {
5046 #ifndef GST_DISABLE_GST_DEBUG
5048 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
5049 "received NULL buffer, doing nothing", GST_PAD_NAME (pad));
5051 GST_LOG_OBJECT (qtmux,
5052 "Pad %s has no previous buffer stored, storing now",
5053 GST_PAD_NAME (pad));
5059 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
5062 /* if this is the first buffer, store the timestamp */
5063 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
5064 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
5065 pad->first_ts = GST_BUFFER_PTS (last_buf);
5066 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
5067 pad->first_ts = GST_BUFFER_DTS (last_buf);
5070 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
5071 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
5072 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
5073 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
5076 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
5077 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
5079 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
5080 "using 0 as first timestamp", GST_PAD_NAME (pad));
5081 pad->first_ts = pad->first_dts = 0;
5083 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
5084 GST_TIME_FORMAT, GST_PAD_NAME (pad), GST_TIME_ARGS (pad->first_ts));
5087 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
5088 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
5089 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
5090 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
5091 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
5092 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
5093 pad->last_buf = buf = gst_buffer_make_writable (buf);
5094 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
5097 buffer_size = gst_buffer_get_size (last_buf);
5099 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
5100 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
5101 guint fill_size = required_buffer_size - buffer_size;
5105 if (required_buffer_size < buffer_size) {
5106 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5107 ("Sample size %u bigger than expected maximum %u", buffer_size,
5108 required_buffer_size));
5112 if (fill_size > 0) {
5113 GST_DEBUG_OBJECT (qtmux,
5114 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
5115 required_buffer_size);
5116 mem = gst_allocator_alloc (NULL, fill_size, NULL);
5117 gst_memory_map (mem, &map, GST_MAP_WRITE);
5118 memset (map.data, 0, map.size);
5119 gst_memory_unmap (mem, &map);
5120 last_buf = gst_buffer_make_writable (last_buf);
5121 gst_buffer_append_memory (last_buf, mem);
5122 buffer_size = required_buffer_size;
5126 /* duration actually means time delta between samples, so we calculate
5127 * the duration based on the difference in DTS or PTS, falling back
5128 * to DURATION if the other two don't exist, such as with the last
5129 * sample before EOS. Or use 0 if nothing else is available,
5130 * making sure that duration doesn't go negative and wraparound. */
5131 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
5132 duration = GST_BUFFER_DURATION (last_buf);
5136 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
5137 && GST_BUFFER_DTS_IS_VALID (last_buf)) {
5138 if (GST_BUFFER_DTS (buf) >= GST_BUFFER_DTS (last_buf))
5139 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
5140 } else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
5141 && GST_BUFFER_PTS_IS_VALID (last_buf)) {
5142 if (GST_BUFFER_PTS (buf) >= GST_BUFFER_PTS (last_buf))
5143 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
5145 if (duration == 0 && !pad->warned_empty_duration) {
5146 GST_WARNING_OBJECT (qtmux,
5147 "Sample with zero duration on pad %" GST_PTR_FORMAT
5148 " due to missing or backward timestamps on the input stream", pad);
5149 pad->warned_empty_duration = TRUE;
5153 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
5154 GST_DEBUG_OBJECT (qtmux,
5155 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
5156 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
5157 GST_DEBUG_PAD_NAME (pad), qtmux->current_chunk_offset,
5158 qtmux->current_chunk_size,
5159 GST_TIME_ARGS (qtmux->current_chunk_duration));
5160 qtmux->current_pad = pad;
5161 if (qtmux->current_chunk_offset == -1)
5162 qtmux->current_chunk_offset = qtmux->mdat_size;
5164 qtmux->current_chunk_offset += qtmux->current_chunk_size;
5165 qtmux->current_chunk_size = 0;
5166 qtmux->current_chunk_duration = 0;
5169 last_dts = gst_util_uint64_scale_round (pad->last_dts,
5170 atom_trak_get_timescale (pad->trak), GST_SECOND);
5172 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
5173 if (pad->sample_size && (qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
5174 || qtmux->fragment_mode ==
5175 GST_QT_MUX_FRAGMENT_FIRST_MOOV_THEN_FINALISE)) {
5176 GstClockTime expected_timestamp;
5178 /* Constant size packets: usually raw audio (with many samples per
5179 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
5181 sample_size = pad->sample_size;
5182 if (buffer_size % sample_size != 0)
5183 goto fragmented_sample;
5185 /* note: qt raw audio storage warps it implicitly into a timewise
5186 * perfect stream, discarding buffer times.
5187 * If the difference between the current PTS and the expected one
5188 * becomes too big, we error out: there was a gap and we have no way to
5189 * represent that, causing A/V sync to be off */
5190 expected_timestamp =
5191 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
5192 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
5193 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
5194 expected_timestamp) > qtmux->max_raw_audio_drift)
5195 goto raw_audio_timestamp_drift;
5197 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
5198 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
5199 atom_trak_get_timescale (pad->trak), GST_SECOND);
5200 duration = GST_BUFFER_DURATION (last_buf);
5202 nsamples = buffer_size / sample_size;
5204 gst_util_uint64_scale_round (nsamples, GST_SECOND,
5205 atom_trak_get_timescale (pad->trak));
5208 /* timescale = samplerate */
5209 scaled_duration = 1;
5211 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
5212 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
5215 sample_size = buffer_size;
5216 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
5217 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
5219 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
5220 pad->last_dts = GST_BUFFER_DTS (buf);
5222 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
5224 if ((gint64) (pad->last_dts) < 0) {
5225 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
5226 atom_trak_get_timescale (pad->trak), GST_SECOND);
5228 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
5229 atom_trak_get_timescale (pad->trak), GST_SECOND);
5231 scaled_duration = scaled_dts - last_dts;
5232 last_dts = scaled_dts;
5234 /* first convert intended timestamp (in GstClockTime resolution) to
5235 * trak timescale, then derive delta;
5236 * this ensures sums of (scale)delta add up to converted timestamp,
5237 * which only deviates at most 1/scale from timestamp itself */
5238 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
5239 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
5240 pad->last_dts += duration;
5244 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
5246 chunk_offset = qtmux->current_chunk_offset;
5248 GST_LOG_OBJECT (qtmux,
5249 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
5250 GST_PAD_NAME (pad), GST_TIME_ARGS (pad->last_dts));
5251 GST_LOG_OBJECT (qtmux,
5252 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
5253 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
5254 nsamples, scaled_duration, sample_size, chunk_offset);
5256 /* might be a sync sample */
5258 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
5259 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
5260 GST_PAD_NAME (pad));
5264 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
5265 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
5266 atom_trak_get_timescale (pad->trak), GST_SECOND);
5268 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
5269 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
5272 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
5273 atom_trak_get_timescale (pad->trak), GST_SECOND);
5275 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
5276 " timebase_dts: %d pts_offset: %d",
5277 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
5278 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
5279 (int) (last_dts), (int) (pts_offset));
5281 if (GST_CLOCK_TIME_IS_VALID (duration)
5282 && (qtmux->current_chunk_duration > qtmux->longest_chunk
5283 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
5284 GST_DEBUG_OBJECT (qtmux,
5285 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
5286 GST_TIME_ARGS (qtmux->current_chunk_duration), GST_PAD_NAME (pad));
5287 qtmux->longest_chunk = qtmux->current_chunk_duration;
5290 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
5291 const TrakBufferEntryInfo *sample_entry;
5292 guint64 block_idx = prefill_get_block_index (qtmux, pad);
5294 if (block_idx >= pad->samples->len) {
5295 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5296 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
5297 block_idx, pad->samples->len));
5301 /* Check if all values are as expected */
5303 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
5305 if (chunk_offset < sample_entry->chunk_offset) {
5306 guint fill_size = sample_entry->chunk_offset - chunk_offset;
5307 GstBuffer *fill_buf;
5309 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
5310 gst_buffer_memset (fill_buf, 0, 0, fill_size);
5312 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
5313 if (ret != GST_FLOW_OK)
5315 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
5316 qtmux->current_chunk_size = buffer_size;
5317 qtmux->current_chunk_duration = duration;
5318 } else if (chunk_offset != sample_entry->chunk_offset) {
5319 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5320 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
5321 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
5326 /* now we go and register this buffer/sample all over */
5327 pad->flow_status = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
5328 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
5329 chunk_offset, sync, TRUE, pts_offset);
5330 if (pad->flow_status != GST_FLOW_OK)
5333 pad->sample_offset += nsamples;
5335 /* if this is sparse and we have a next buffer, check if there is any gap
5336 * between them to insert an empty sample */
5337 if (pad->sparse && buf) {
5338 if (pad->create_empty_buffer) {
5339 GstBuffer *empty_buf;
5340 gint64 empty_duration =
5341 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
5342 gint64 empty_duration_scaled;
5345 empty_buf = pad->create_empty_buffer (pad, empty_duration);
5347 pad->last_dts = GST_BUFFER_PTS (buf);
5348 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
5349 atom_trak_get_timescale (pad->trak), GST_SECOND)
5350 - (last_dts + scaled_duration);
5351 empty_size = gst_buffer_get_size (empty_buf);
5353 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
5357 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
5358 last_dts + scaled_duration, empty_duration_scaled,
5359 empty_size, chunk_offset, sync, TRUE, 0);
5360 } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
5361 /* This assert is kept here to make sure implementors of new
5362 * sparse input format decide whether there needs to be special
5363 * gap handling or not */
5364 g_assert_not_reached ();
5365 GST_WARNING_OBJECT (qtmux,
5366 "no empty buffer creation function found for pad %s",
5367 GST_PAD_NAME (pad));
5378 gst_buffer_unref (last_buf);
5379 return GST_FLOW_ERROR;
5383 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5384 ("Audio buffer contains fragmented sample."));
5387 raw_audio_timestamp_drift:
5389 /* TODO: Could in theory be implemented with edit lists */
5390 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5391 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
5392 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
5393 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
5394 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
5396 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
5401 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
5406 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
5407 ("format wasn't negotiated before buffer flow on pad %s",
5408 GST_PAD_NAME (pad)));
5410 gst_buffer_unref (buf);
5411 return GST_FLOW_NOT_NEGOTIATED;
5415 /* Only post an error message for actual errors that are not flushing */
5416 if (pad->flow_status < GST_FLOW_OK && pad->flow_status != GST_FLOW_FLUSHING)
5417 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
5418 ("Failed to push sample."));
5419 return pad->flow_status;
5424 * DTS running time can be negative. There is no way to represent that in
5425 * MP4 however, thus we need to offset DTS so that it starts from 0.
5428 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTMuxPad * pad,
5434 pts = GST_BUFFER_PTS (*buf);
5437 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
5438 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (pad),
5439 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
5441 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
5442 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
5443 pad->dts_adjustment = -dts;
5445 pad->dts_adjustment = 0;
5448 if (pad->dts_adjustment > 0) {
5449 *buf = gst_buffer_make_writable (*buf);
5451 dts += pad->dts_adjustment;
5453 if (GST_CLOCK_TIME_IS_VALID (pts))
5454 pts += pad->dts_adjustment;
5456 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
5457 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
5462 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
5466 GST_BUFFER_PTS (*buf) = pts;
5467 GST_BUFFER_DTS (*buf) = dts;
5469 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
5470 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
5474 static GstQTMuxPad *
5475 find_best_pad (GstQTMux * qtmux)
5478 GstQTMuxPad *best_pad = NULL;
5480 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
5481 guint64 smallest_offset = G_MAXUINT64;
5482 guint64 chunk_offset = 0;
5484 GST_OBJECT_LOCK (qtmux);
5485 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
5486 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
5487 const TrakBufferEntryInfo *sample_entry;
5488 guint64 block_idx, current_block_idx;
5489 guint64 chunk_offset_offset = 0;
5490 GstBuffer *tmp_buf =
5491 gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD (qtpad));
5493 /* Check for EOS pads and just skip them */
5494 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
5495 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
5498 gst_buffer_unref (tmp_buf);
5500 /* Find the exact offset where the next sample of this track is supposed
5501 * to be written at */
5502 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
5503 if (!qtpad->samples || block_idx >= qtpad->samples->len) {
5504 GST_OBJECT_UNLOCK (qtmux);
5505 GST_ELEMENT_ERROR (qtmux, RESOURCE, SETTINGS,
5506 ("Failed to create samples in prefill mode"), (NULL));
5511 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
5512 while (block_idx > 0) {
5513 const TrakBufferEntryInfo *tmp =
5514 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
5516 if (tmp->chunk_offset != sample_entry->chunk_offset)
5518 chunk_offset_offset += tmp->size * tmp->nsamples;
5522 /* Except for the previously selected pad being EOS we always have
5523 * qtmux->current_chunk_offset + qtmux->current_chunk_size
5525 * sample_entry->chunk_offset + chunk_offset_offset
5526 * for the best pad. Instead of checking that, we just return the
5527 * pad that has the smallest offset for the next to-be-written sample.
5529 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
5530 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
5532 chunk_offset = sample_entry->chunk_offset;
5535 GST_OBJECT_UNLOCK (qtmux);
5537 if (chunk_offset != qtmux->current_chunk_offset) {
5538 qtmux->current_pad = NULL;
5544 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
5545 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
5546 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
5547 && (qtmux->interleave_time == 0
5548 || qtmux->current_chunk_duration <= qtmux->interleave_time)
5549 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED) {
5550 GstBuffer *tmp_buf =
5551 gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD
5552 (qtmux->current_pad));
5554 if (tmp_buf || qtmux->current_pad->last_buf) {
5555 best_pad = qtmux->current_pad;
5557 gst_buffer_unref (tmp_buf);
5558 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
5559 GST_DEBUG_PAD_NAME (best_pad));
5562 gboolean push_stored = FALSE;
5564 GST_OBJECT_LOCK (qtmux);
5565 if ((GST_ELEMENT (qtmux)->sinkpads && GST_ELEMENT (qtmux)->sinkpads->next)
5566 || qtmux->force_chunks) {
5567 /* Only switch pads if we have more than one, otherwise
5568 * we can just put everything into a single chunk and save
5569 * a few bytes of offsets.
5571 * Various applications and the Apple ProRes spec require chunking even
5572 * in case of single stream files.
5574 if (qtmux->current_pad)
5575 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
5576 GST_DEBUG_PAD_NAME (qtmux->current_pad));
5577 best_pad = qtmux->current_pad = NULL;
5580 GST_OBJECT_UNLOCK (qtmux);
5583 gst_qtmux_push_mdat_stored_buffers (qtmux);
5587 GstClockTime best_time = GST_CLOCK_TIME_NONE;
5589 GST_OBJECT_LOCK (qtmux);
5590 for (l = GST_ELEMENT_CAST (qtmux)->sinkpads; l; l = l->next) {
5591 GstQTMuxPad *qtpad = (GstQTMuxPad *) l->data;
5593 GstClockTime timestamp;
5595 tmp_buf = gst_aggregator_pad_peek_buffer (GST_AGGREGATOR_PAD (qtpad));;
5597 /* This one is newly EOS now, finish it for real */
5598 if (qtpad->last_buf) {
5599 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5604 if (qtpad->last_buf)
5605 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5607 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
5610 if (best_pad == NULL ||
5611 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
5613 best_time = timestamp;
5617 gst_buffer_unref (tmp_buf);
5619 GST_OBJECT_UNLOCK (qtmux);
5622 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
5623 GST_DEBUG_PAD_NAME (best_pad));
5625 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
5633 gst_qt_mux_are_all_pads_eos (GstQTMux * mux)
5636 gboolean ret = TRUE;
5638 GST_OBJECT_LOCK (mux);
5639 for (l = GST_ELEMENT_CAST (mux)->sinkpads; l; l = l->next) {
5640 if (!gst_aggregator_pad_is_eos (GST_AGGREGATOR_PAD (l->data))) {
5645 GST_OBJECT_UNLOCK (mux);
5650 static GstFlowReturn
5651 gst_qt_mux_aggregate (GstAggregator * agg, gboolean timeout)
5653 GstFlowReturn ret = GST_FLOW_OK;
5654 GstQTMux *qtmux = GST_QT_MUX_CAST (agg);
5655 GstQTMuxPad *best_pad = NULL;
5657 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
5658 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
5661 qtmux->state = GST_QT_MUX_STATE_DATA;
5664 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
5665 return GST_FLOW_EOS;
5667 best_pad = find_best_pad (qtmux);
5669 /* clipping already converted to running time */
5670 if (best_pad != NULL) {
5671 GstBuffer *buf = NULL;
5673 /* FIXME: the function should always return flow_status information, that
5674 * is supposed to be stored each time buffers (collected from the pads)
5676 if (best_pad->flow_status != GST_FLOW_OK)
5677 return best_pad->flow_status;
5679 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
5680 best_pad->raw_audio_adapter == NULL ||
5681 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
5682 buf = gst_aggregator_pad_pop_buffer (GST_AGGREGATOR_PAD (best_pad));
5684 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
5685 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
5688 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad, &buf);
5690 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5691 } else if (gst_qt_mux_are_all_pads_eos (qtmux)) {
5693 qtmux->state = GST_QT_MUX_STATE_EOS;
5694 ret = gst_qt_mux_stop_file (qtmux);
5695 if (ret == GST_FLOW_OK) {
5696 GST_DEBUG_OBJECT (qtmux, "We are eos");
5699 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5700 gst_flow_get_name (ret));
5708 field_is_in (GQuark field_id, const gchar * fieldname, ...)
5711 gchar *name = (gchar *) fieldname;
5713 va_start (varargs, fieldname);
5715 if (field_id == g_quark_from_static_string (name)) {
5721 name = va_arg (varargs, char *);
5729 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5731 GstStructure *structure = (GstStructure *) user_data;
5732 const GValue *other = gst_structure_id_get_value (structure, field_id);
5733 const gchar *name = gst_structure_get_name (structure);
5735 if (g_str_has_prefix (name, "video/")) {
5736 /* ignore framerate with video caps */
5737 if (g_strcmp0 (g_quark_to_string (field_id), "framerate") == 0)
5741 if (g_strcmp0 (name, "video/x-h264") == 0 ||
5742 g_strcmp0 (name, "video/x-h265") == 0) {
5743 /* We support muxing multiple codec_data structures, and the new SPS
5744 * will contain updated tier / level / profiles, which means we do
5745 * not need to fail renegotiation when those change.
5747 if (field_is_in (field_id,
5748 "codec_data", "tier", "level", "profile",
5749 "chroma-site", "chroma-format", "bit-depth-luma", "colorimetry",
5750 /* TODO: this may require a separate track but gst, vlc, ffmpeg and
5751 * browsers work with this so... */
5752 "width", "height", NULL)) {
5758 if (other == NULL) {
5759 if (field_is_in (field_id, "interlace-mode", NULL) &&
5760 !g_strcmp0 (g_value_get_string (value), "progressive")) {
5766 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5770 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5773 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5774 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5776 if (!gst_structure_has_name (sup_s, gst_structure_get_name (sub_s)))
5779 return gst_structure_foreach (sub_s, check_field, sup_s);
5782 /* will unref @qtmux */
5784 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5786 GstQTMuxPad *qtmuxpad = GST_QT_MUX_PAD_CAST (pad);
5788 /* does not go well to renegotiate stream mid-way, unless
5789 * the old caps are a subset of the new one (this means upstream
5790 * added more info to the caps, as both should be 'fixed' caps) */
5792 if (!qtmuxpad->configured_caps) {
5793 GST_DEBUG_OBJECT (qtmux, "pad %s accepted caps %" GST_PTR_FORMAT,
5794 GST_PAD_NAME (pad), caps);
5798 g_assert (caps != NULL);
5800 if (!gst_qtmux_caps_is_subset_full (qtmux, qtmuxpad->configured_caps, caps)) {
5801 GST_WARNING_OBJECT (qtmux,
5802 "pad %s refused renegotiation to %" GST_PTR_FORMAT " from %"
5803 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, qtmuxpad->configured_caps);
5807 GST_DEBUG_OBJECT (qtmux,
5808 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5809 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, qtmuxpad->configured_caps);
5815 gst_qt_mux_audio_sink_set_caps (GstQTMuxPad * qtpad, GstCaps * caps)
5817 GstPad *pad = GST_PAD (qtpad);
5818 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5819 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5820 GstStructure *structure;
5821 const gchar *mimetype;
5822 gint rate, channels;
5823 const GValue *value = NULL;
5824 const GstBuffer *codec_data = NULL;
5825 GstQTMuxFormat format;
5826 AudioSampleEntry entry = { 0, };
5827 AtomInfo *ext_atom = NULL;
5828 gint constant_size = 0;
5829 const gchar *stream_format;
5832 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5833 GST_DEBUG_PAD_NAME (pad), caps);
5835 qtpad->prepare_buf_func = NULL;
5837 format = qtmux_klass->format;
5838 structure = gst_caps_get_structure (caps, 0);
5839 mimetype = gst_structure_get_name (structure);
5842 if (!gst_structure_get_int (structure, "channels", &channels) ||
5843 !gst_structure_get_int (structure, "rate", &rate)) {
5848 value = gst_structure_get_value (structure, "codec_data");
5850 codec_data = gst_value_get_buffer (value);
5852 qtpad->is_out_of_order = FALSE;
5854 /* set common properties */
5855 entry.sample_rate = rate;
5856 entry.channels = channels;
5858 entry.sample_size = 16;
5859 /* this is the typical compressed case */
5860 if (format == GST_QT_MUX_FORMAT_QT) {
5862 entry.compression_id = -2;
5865 /* now map onto a fourcc, and some extra properties */
5866 if (strcmp (mimetype, "audio/mpeg") == 0) {
5867 gint mpegversion = 0, mpegaudioversion = 0;
5870 gst_structure_get_int (structure, "mpegversion", &mpegversion);
5871 switch (mpegversion) {
5873 gst_structure_get_int (structure, "layer", &layer);
5874 gst_structure_get_int (structure, "mpegaudioversion",
5878 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5879 if (format == GST_QT_MUX_FORMAT_QT)
5880 entry.fourcc = FOURCC__mp3;
5882 entry.fourcc = FOURCC_mp4a;
5884 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5885 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5886 qtpad->max_bitrate);
5889 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5890 || format == GST_QT_MUX_FORMAT_QT);
5891 entry.samples_per_packet = 384;
5892 } else if (layer == 2) {
5893 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5894 || format == GST_QT_MUX_FORMAT_QT);
5895 entry.samples_per_packet = 1152;
5897 g_warn_if_fail (layer == 3);
5898 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5900 entry.bytes_per_sample = 2;
5904 /* check stream-format */
5905 stream_format = gst_structure_get_string (structure, "stream-format");
5906 if (stream_format) {
5907 if (strcmp (stream_format, "raw") != 0) {
5908 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5909 "please use 'raw'", stream_format);
5913 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5917 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5918 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5923 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5924 /* warn if not Low Complexity profile */
5927 GST_WARNING_OBJECT (qtmux,
5928 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5932 entry.fourcc = FOURCC_mp4a;
5934 if (format == GST_QT_MUX_FORMAT_QT)
5935 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5936 qtpad->avg_bitrate, qtpad->max_bitrate);
5939 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5940 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5941 qtpad->max_bitrate);
5946 } else if (strcmp (mimetype, "audio/AMR") == 0) {
5947 entry.fourcc = FOURCC_samr;
5948 entry.sample_size = 16;
5949 entry.samples_per_packet = 160;
5950 entry.bytes_per_sample = 2;
5951 ext_atom = build_amr_extension ();
5952 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5953 entry.fourcc = FOURCC_sawb;
5954 entry.sample_size = 16;
5955 entry.samples_per_packet = 320;
5956 entry.bytes_per_sample = 2;
5957 ext_atom = build_amr_extension ();
5958 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5961 gst_audio_info_init (&info);
5962 if (!gst_audio_info_from_caps (&info, caps))
5965 /* spec has no place for a distinction in these */
5966 if (info.finfo->width != info.finfo->depth) {
5967 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5971 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5972 if (info.finfo->endianness == G_LITTLE_ENDIAN)
5973 entry.fourcc = FOURCC_sowt;
5974 else if (info.finfo->endianness == G_BIG_ENDIAN)
5975 entry.fourcc = FOURCC_twos;
5977 entry.fourcc = FOURCC_sowt;
5978 /* maximum backward compatibility; only new version for > 16 bit */
5979 if (info.finfo->depth <= 16)
5981 /* not compressed in any case */
5982 entry.compression_id = 0;
5983 /* QT spec says: max at 16 bit even if sample size were actually larger,
5984 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5985 entry.sample_size = info.finfo->depth;
5986 entry.bytes_per_sample = info.finfo->depth / 8;
5987 entry.samples_per_packet = 1;
5988 entry.bytes_per_packet = info.finfo->depth / 8;
5989 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5991 if (info.finfo->width == 8 && info.finfo->depth == 8) {
5992 /* fall back to old 8-bit version */
5993 entry.fourcc = FOURCC_raw_;
5995 entry.compression_id = 0;
5996 entry.sample_size = 8;
5998 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
6002 constant_size = (info.finfo->depth / 8) * info.channels;
6003 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
6004 entry.fourcc = FOURCC_alaw;
6005 entry.samples_per_packet = 1023;
6006 entry.bytes_per_sample = 2;
6007 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
6008 entry.fourcc = FOURCC_ulaw;
6009 entry.samples_per_packet = 1023;
6010 entry.bytes_per_sample = 2;
6011 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
6013 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
6014 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
6017 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
6019 entry.fourcc = MS_WAVE_FOURCC (0x11);
6020 /* 4 byte header per channel (including one sample). 2 samples per byte
6021 remaining. Simplifying gives the following (samples per block per
6023 entry.samples_per_packet = 2 * blocksize / channels - 7;
6024 entry.bytes_per_sample = 2;
6026 entry.bytes_per_frame = blocksize;
6027 entry.bytes_per_packet = blocksize / channels;
6028 /* ADPCM has constant size packets */
6030 /* TODO: I don't really understand why this helps, but it does! Constant
6031 * size and compression_id of -2 seem to be incompatible, and other files
6032 * in the wild use this too. */
6033 entry.compression_id = -1;
6035 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
6036 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
6037 GstBuffer *codec_config;
6041 entry.fourcc = FOURCC_alac;
6042 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
6043 /* let's check if codec data already comes with 'alac' atom prefix */
6044 if (!codec_data || (len = map.size) < 28) {
6045 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
6046 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
6049 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
6052 gst_buffer_copy_region ((GstBuffer *) codec_data,
6053 GST_BUFFER_COPY_MEMORY, 8, len);
6055 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
6057 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
6059 /* does not look good, but perhaps some trailing unneeded stuff */
6060 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
6062 if (format == GST_QT_MUX_FORMAT_QT)
6063 ext_atom = build_mov_alac_extension (codec_config);
6065 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
6066 /* set some more info */
6067 gst_buffer_map (codec_config, &map, GST_MAP_READ);
6068 entry.bytes_per_sample = 2;
6069 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
6070 gst_buffer_unmap (codec_config, &map);
6071 gst_buffer_unref (codec_config);
6072 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
6073 entry.fourcc = FOURCC_ac_3;
6075 /* Fixed values according to TS 102 366 but it also mentions that
6076 * they should be ignored */
6078 entry.sample_size = 16;
6080 /* AC-3 needs an extension atom but its data can only be obtained from
6081 * the stream itself. Abuse the prepare_buf_func so we parse a frame
6082 * and get the needed data */
6083 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
6084 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
6085 /* Based on the specification defined in:
6086 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
6087 guint8 channels, mapping_family, stream_count, coupled_count;
6091 guint8 channel_mapping[256];
6092 const GValue *streamheader;
6093 const GValue *first_element;
6096 entry.fourcc = FOURCC_opus;
6097 entry.sample_size = 16;
6099 streamheader = gst_structure_get_value (structure, "streamheader");
6100 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
6101 gst_value_array_get_size (streamheader) != 0) {
6102 first_element = gst_value_array_get_value (streamheader, 0);
6103 header = gst_value_get_buffer (first_element);
6104 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
6105 &mapping_family, &stream_count, &coupled_count, channel_mapping,
6106 &pre_skip, &output_gain)) {
6107 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
6111 GST_WARNING_OBJECT (qtmux,
6112 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
6114 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
6115 &mapping_family, &stream_count, &coupled_count,
6117 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
6124 entry.channels = channels;
6125 ext_atom = build_opus_extension (rate, channels, mapping_family,
6126 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
6132 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6133 if (!timescale && qtmux->trak_timescale)
6134 timescale = qtmux->trak_timescale;
6135 else if (!timescale)
6136 timescale = entry.sample_rate;
6138 /* ok, set the pad info accordingly */
6139 qtpad->fourcc = entry.fourcc;
6140 qtpad->sample_size = constant_size;
6142 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
6143 qtmux->context, &entry, timescale, ext_atom, constant_size);
6145 gst_object_unref (qtmux);
6151 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6152 GST_PAD_NAME (pad), caps);
6153 gst_object_unref (qtmux);
6159 gst_qt_mux_video_sink_set_caps (GstQTMuxPad * qtpad, GstCaps * caps)
6161 GstPad *pad = GST_PAD (qtpad);
6162 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6163 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6164 GstStructure *structure;
6165 const gchar *mimetype;
6166 gint width, height, depth = -1;
6167 gint framerate_num, framerate_den;
6169 const GValue *value = NULL;
6170 const GstBuffer *codec_data = NULL;
6171 VisualSampleEntry entry = { 0, };
6172 GstQTMuxFormat format;
6173 AtomInfo *ext_atom = NULL;
6174 GList *ext_atom_list = NULL;
6175 gboolean sync = FALSE;
6176 int par_num, par_den;
6177 const gchar *multiview_mode;
6179 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6180 GST_DEBUG_PAD_NAME (pad), caps);
6182 qtpad->prepare_buf_func = NULL;
6184 format = qtmux_klass->format;
6185 structure = gst_caps_get_structure (caps, 0);
6186 mimetype = gst_structure_get_name (structure);
6188 /* required parts */
6189 if (!gst_structure_get_int (structure, "width", &width) ||
6190 !gst_structure_get_int (structure, "height", &height))
6195 /* works as a default timebase */
6196 framerate_num = 10000;
6198 gst_structure_get_fraction (structure, "framerate", &framerate_num,
6200 gst_structure_get_int (structure, "depth", &depth);
6201 value = gst_structure_get_value (structure, "codec_data");
6203 codec_data = gst_value_get_buffer (value);
6207 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
6210 qtpad->is_out_of_order = FALSE;
6212 /* bring frame numerator into a range that ensures both reasonable resolution
6213 * as well as a fair duration */
6214 qtpad->expected_sample_duration_n = framerate_num;
6215 qtpad->expected_sample_duration_d = framerate_den;
6217 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6218 if (!rate && qtmux->trak_timescale)
6219 rate = qtmux->trak_timescale;
6221 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
6223 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
6226 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
6227 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
6228 GstVideoMultiviewMode mode;
6229 GstVideoMultiviewFlags flags = 0;
6231 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
6232 gst_structure_get_flagset (structure,
6233 "multiview-flags", (guint *) & flags, NULL);
6235 case GST_VIDEO_MULTIVIEW_MODE_MONO:
6236 /* Nothing to do for mono, just don't warn about it */
6238 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
6239 qtpad->trak->mdia.minf.stbl.svmi =
6241 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
6243 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
6244 qtpad->trak->mdia.minf.stbl.svmi =
6246 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
6248 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
6249 qtpad->trak->mdia.minf.stbl.svmi =
6251 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
6254 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
6260 /* set common properties */
6261 entry.width = width;
6262 entry.height = height;
6263 entry.par_n = par_num;
6264 entry.par_d = par_den;
6265 /* should be OK according to qt and iso spec, override if really needed */
6266 entry.color_table_id = -1;
6267 entry.frame_count = 1;
6270 /* sync entries by default */
6273 /* now map onto a fourcc, and some extra properties */
6274 if (strcmp (mimetype, "video/x-raw") == 0) {
6275 const gchar *format;
6277 const GstVideoFormatInfo *vinfo;
6279 format = gst_structure_get_string (structure, "format");
6280 fmt = gst_video_format_from_string (format);
6281 vinfo = gst_video_format_get_info (fmt);
6284 case GST_VIDEO_FORMAT_UYVY:
6287 entry.fourcc = FOURCC_2vuy;
6288 entry.depth = depth;
6291 case GST_VIDEO_FORMAT_v210:
6294 entry.fourcc = FOURCC_v210;
6295 entry.depth = depth;
6299 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
6300 entry.fourcc = FOURCC_raw_;
6301 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
6306 } else if (strcmp (mimetype, "video/x-h263") == 0) {
6308 if (format == GST_QT_MUX_FORMAT_QT)
6309 entry.fourcc = FOURCC_h263;
6311 entry.fourcc = FOURCC_s263;
6312 ext_atom = build_h263_extension ();
6313 if (ext_atom != NULL)
6314 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6315 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
6316 strcmp (mimetype, "video/mpeg") == 0) {
6319 if (strcmp (mimetype, "video/x-divx") == 0) {
6320 gst_structure_get_int (structure, "divxversion", &version);
6321 version = version == 5 ? 1 : 0;
6323 gst_structure_get_int (structure, "mpegversion", &version);
6324 version = version == 4 ? 1 : 0;
6327 entry.fourcc = FOURCC_mp4v;
6329 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
6330 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
6331 qtpad->max_bitrate);
6332 if (ext_atom != NULL)
6333 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6335 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
6336 "output might not play in Apple QuickTime (try global-headers?)");
6338 } else if (strcmp (mimetype, "video/x-h264") == 0) {
6339 const gchar *stream_format;
6342 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
6346 stream_format = gst_structure_get_string (structure, "stream-format");
6348 if (!g_strcmp0 (stream_format, "avc")) {
6349 entry.fourcc = FOURCC_avc1;
6350 } else if (!g_strcmp0 (stream_format, "avc3")) {
6351 entry.fourcc = FOURCC_avc3;
6353 g_assert_not_reached ();
6356 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
6357 if (ext_atom != NULL)
6358 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6359 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
6360 if (ext_atom != NULL)
6361 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6362 } else if (strcmp (mimetype, "video/x-h265") == 0) {
6363 const gchar *format;
6366 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
6370 format = gst_structure_get_string (structure, "stream-format");
6371 if (strcmp (format, "hvc1") == 0)
6372 entry.fourcc = FOURCC_hvc1;
6373 else if (strcmp (format, "hev1") == 0)
6374 entry.fourcc = FOURCC_hev1;
6376 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
6377 if (ext_atom != NULL)
6378 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6380 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
6381 if (ext_atom != NULL)
6382 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6384 } else if (strcmp (mimetype, "video/x-svq") == 0) {
6386 const GstBuffer *seqh = NULL;
6387 const GValue *seqh_value;
6390 gst_structure_get_int (structure, "svqversion", &version);
6392 entry.fourcc = FOURCC_SVQ3;
6396 seqh_value = gst_structure_get_value (structure, "seqh");
6398 seqh = gst_value_get_buffer (seqh_value);
6399 ext_atom = build_SMI_atom (seqh);
6401 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6404 /* we need to add the gamma anyway because quicktime might crash
6405 * when it doesn't find it */
6406 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
6407 /* it seems that using 0 here makes it ignored */
6410 ext_atom = build_gama_atom (gamma);
6412 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6414 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
6415 "a bug at http://bugzilla.gnome.org", version);
6417 } else if (strcmp (mimetype, "video/x-dv") == 0) {
6419 gboolean pal = TRUE;
6422 if (framerate_num != 25 || framerate_den != 1)
6424 gst_structure_get_int (structure, "dvversion", &version);
6425 /* fall back to typical one */
6431 entry.fourcc = FOURCC_dvcp;
6433 entry.fourcc = FOURCC_dvc_;
6437 entry.fourcc = FOURCC_dv5p;
6439 entry.fourcc = FOURCC_dv5n;
6442 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
6445 } else if (strcmp (mimetype, "image/jpeg") == 0) {
6446 entry.fourcc = FOURCC_jpeg;
6448 } else if (strcmp (mimetype, "image/png") == 0) {
6449 entry.fourcc = FOURCC_png;
6451 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
6452 strcmp (mimetype, "image/x-jpc") == 0) {
6453 const gchar *colorspace;
6454 const GValue *cmap_array;
6455 const GValue *cdef_array;
6458 if (strcmp (mimetype, "image/x-jpc") == 0) {
6459 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
6462 gst_structure_get_int (structure, "num-components", &ncomp);
6463 cmap_array = gst_structure_get_value (structure, "component-map");
6464 cdef_array = gst_structure_get_value (structure, "channel-definitions");
6467 entry.fourcc = FOURCC_mjp2;
6470 colorspace = gst_structure_get_string (structure, "colorspace");
6473 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
6474 cdef_array)) != NULL) {
6475 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6477 ext_atom = build_jp2x_extension (codec_data);
6479 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6481 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
6484 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
6485 entry.fourcc = FOURCC_vp08;
6486 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
6487 const char *profile_str, *chroma_format_str, *colorimetry_str;
6488 guint bitdepth_luma, bitdepth_chroma;
6489 guint8 profile = -1, chroma_format = -1;
6490 gboolean video_full_range;
6491 GstVideoColorimetry cinfo = { 0, };
6493 entry.fourcc = FOURCC_vp09;
6495 profile_str = gst_structure_get_string (structure, "profile");
6496 if (g_strcmp0 (profile_str, "0") == 0) {
6498 } else if (g_strcmp0 (profile_str, "1") == 0) {
6500 } else if (g_strcmp0 (profile_str, "2") == 0) {
6502 } else if (g_strcmp0 (profile_str, "3") == 0) {
6506 colorimetry_str = gst_structure_get_string (structure, "colorimetry");
6507 gst_video_colorimetry_from_string (&cinfo, colorimetry_str);
6508 video_full_range = cinfo.range == GST_VIDEO_COLOR_RANGE_0_255;
6510 chroma_format_str = gst_structure_get_string (structure, "chroma-format");
6511 if (g_strcmp0 (chroma_format_str, "4:2:0") == 0) {
6512 const char *chroma_site_str;
6513 GstVideoChromaSite chroma_site;
6515 chroma_site_str = gst_structure_get_string (structure, "chroma-site");
6516 chroma_site = gst_video_chroma_site_from_string (chroma_site_str);
6517 if (chroma_site == GST_VIDEO_CHROMA_SITE_V_COSITED) {
6519 } else if (chroma_site == GST_VIDEO_CHROMA_SITE_COSITED) {
6524 } else if (g_strcmp0 (chroma_format_str, "4:2:2") == 0) {
6526 } else if (g_strcmp0 (chroma_format_str, "4:4:4") == 0) {
6530 gst_structure_get (structure, "bit-depth-luma", G_TYPE_UINT,
6531 &bitdepth_luma, "bit-depth-chroma", G_TYPE_UINT, &bitdepth_chroma,
6534 if (profile == 0xFF || chroma_format == 0xFF
6535 || bitdepth_luma != bitdepth_chroma || bitdepth_luma == 0) {
6536 GST_WARNING_OBJECT (qtmux, "cannot construct vpcC atom from "
6539 ext_atom = build_vpcC_extension (profile, /* XXX: level */ 10,
6540 bitdepth_luma, chroma_format, video_full_range,
6541 gst_video_color_primaries_to_iso (cinfo.primaries),
6542 gst_video_transfer_function_to_iso (cinfo.transfer),
6543 gst_video_color_matrix_to_iso (cinfo.matrix));
6545 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6547 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
6548 entry.fourcc = FOURCC_drac;
6549 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
6552 gst_structure_get_uint (structure, "format", &fourcc);
6553 entry.fourcc = fourcc;
6554 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
6557 gst_structure_get_uint (structure, "format", &fourcc);
6558 entry.fourcc = fourcc;
6559 } else if (strcmp (mimetype, "video/x-prores") == 0) {
6560 const gchar *variant;
6562 variant = gst_structure_get_string (structure, "variant");
6563 if (!variant || !g_strcmp0 (variant, "standard"))
6564 entry.fourcc = FOURCC_apcn;
6565 else if (!g_strcmp0 (variant, "lt"))
6566 entry.fourcc = FOURCC_apcs;
6567 else if (!g_strcmp0 (variant, "hq"))
6568 entry.fourcc = FOURCC_apch;
6569 else if (!g_strcmp0 (variant, "proxy"))
6570 entry.fourcc = FOURCC_apco;
6571 else if (!g_strcmp0 (variant, "4444"))
6572 entry.fourcc = FOURCC_ap4h;
6573 else if (!g_strcmp0 (variant, "4444xq"))
6574 entry.fourcc = FOURCC_ap4x;
6578 if (!qtmux->interleave_time_set)
6579 qtmux->interleave_time = 500 * GST_MSECOND;
6580 if (!qtmux->interleave_bytes_set)
6581 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
6582 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
6583 entry.fourcc = FOURCC_cfhd;
6585 } else if (strcmp (mimetype, "video/x-av1") == 0) {
6586 gint presentation_delay;
6587 guint8 presentation_delay_byte = 0;
6588 GstBuffer *av1_codec_data;
6590 if (gst_structure_get_int (structure, "presentation-delay",
6591 &presentation_delay)) {
6592 presentation_delay_byte = 1 << 5;
6593 presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
6597 av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
6598 /* Fill version and 3 bytes of flags to 0 */
6599 gst_buffer_memset (av1_codec_data, 0, 0, 4);
6600 gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
6602 av1_codec_data = gst_buffer_append (av1_codec_data,
6603 gst_buffer_ref ((GstBuffer *) codec_data));
6605 entry.fourcc = FOURCC_av01;
6607 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
6608 if (ext_atom != NULL)
6609 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6610 ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
6611 if (ext_atom != NULL)
6612 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
6613 gst_buffer_unref (av1_codec_data);
6619 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
6620 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
6622 GstVideoColorimetry colorimetry;
6624 s = gst_structure_get_string (structure, "colorimetry");
6625 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
6627 build_colr_extension (&colorimetry,
6628 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
6630 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6634 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
6635 || strcmp (mimetype, "image/x-j2c") == 0
6636 || strcmp (mimetype, "image/x-jpc") == 0) {
6638 GstVideoInterlaceMode interlace_mode;
6639 GstVideoFieldOrder field_order;
6642 if (strcmp (mimetype, "image/x-j2c") == 0 ||
6643 strcmp (mimetype, "image/x-jpc") == 0) {
6646 gst_structure_get_int (structure, "fields", &fields);
6649 s = gst_structure_get_string (structure, "interlace-mode");
6651 interlace_mode = gst_video_interlace_mode_from_string (s);
6655 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
6656 GST_VIDEO_INTERLACE_MODE_MIXED;
6658 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
6659 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
6660 s = gst_structure_get_string (structure, "field-order");
6662 field_order = gst_video_field_order_from_string (s);
6665 ext_atom = build_fiel_extension (interlace_mode, field_order);
6667 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6671 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
6672 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
6673 /* The 'clap' extension is also defined for MP4 but inventing values in
6674 * general seems a bit tricky for this one. We only write it for
6675 * SD resolution in MOV, where it is a requirement.
6676 * The same goes for the 'tapt' extension, just that it is not defined for
6677 * MP4 and only for MOV
6679 gint dar_num, dar_den;
6680 gint clef_width, clef_height, prof_width;
6681 gint clap_width_n, clap_width_d, clap_height;
6685 /* First, guess display aspect ratio based on pixel aspect ratio,
6686 * width and height. We assume that display aspect ratio is either
6689 approx_dar = (gdouble) (width * par_num) / (height * par_den);
6690 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
6693 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
6697 dar_num = width * par_num;
6698 dar_den = height * par_den;
6699 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
6704 /* Then, calculate clean-aperture values (clap and clef)
6705 * using the guessed DAR.
6707 clef_height = clap_height = (height == 486 ? 480 : height);
6708 clef_width = gst_util_uint64_scale (clef_height,
6709 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
6710 prof_width = gst_util_uint64_scale (width,
6711 par_num * G_GUINT64_CONSTANT (65536), par_den);
6712 clap_width_n = clap_height * dar_num * par_den;
6713 clap_width_d = dar_den * par_num;
6714 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
6715 clap_width_n /= cdiv;
6716 clap_width_d /= cdiv;
6718 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
6719 height << 16, width << 16, height << 16);
6720 qtpad->trak->tapt = ext_atom;
6722 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
6723 clap_height, 1, 0, 1, 0, 1);
6725 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
6728 /* ok, set the pad info accordingly */
6729 qtpad->fourcc = entry.fourcc;
6732 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
6733 qtmux->context, &entry, rate, ext_atom_list);
6734 if (strcmp (mimetype, "video/x-prores") == 0) {
6735 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
6736 const gchar *compressor = NULL;
6737 mp4v->spatial_quality = 0x3FF;
6738 mp4v->temporal_quality = 0;
6739 mp4v->vendor = FOURCC_appl;
6740 mp4v->horizontal_resolution = 72 << 16;
6741 mp4v->vertical_resolution = 72 << 16;
6742 mp4v->depth = (entry.fourcc == FOURCC_ap4h
6743 || entry.fourcc == FOURCC_ap4x) ? (depth > 0 ? depth : 32) : 24;
6745 /* Set compressor name, required by some software */
6746 switch (entry.fourcc) {
6748 compressor = "Apple ProRes 422";
6751 compressor = "Apple ProRes 422 LT";
6754 compressor = "Apple ProRes 422 HQ";
6757 compressor = "Apple ProRes 422 Proxy";
6760 compressor = "Apple ProRes 4444";
6763 compressor = "Apple ProRes 4444 XQ";
6767 strcpy ((gchar *) mp4v->compressor + 1, compressor);
6768 mp4v->compressor[0] = strlen (compressor);
6772 gst_object_unref (qtmux);
6778 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6779 GST_PAD_NAME (pad), caps);
6780 gst_object_unref (qtmux);
6786 gst_qt_mux_subtitle_sink_set_caps (GstQTMuxPad * qtpad, GstCaps * caps)
6788 GstPad *pad = GST_PAD (qtpad);
6789 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6790 GstStructure *structure;
6791 SubtitleSampleEntry entry = { 0, };
6793 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6794 GST_DEBUG_PAD_NAME (pad), caps);
6796 /* subtitles default */
6797 subtitle_sample_entry_init (&entry);
6798 qtpad->is_out_of_order = FALSE;
6799 qtpad->sync = FALSE;
6800 qtpad->sparse = TRUE;
6801 qtpad->prepare_buf_func = NULL;
6803 structure = gst_caps_get_structure (caps, 0);
6805 if (gst_structure_has_name (structure, "text/x-raw")) {
6806 const gchar *format = gst_structure_get_string (structure, "format");
6807 if (format && strcmp (format, "utf8") == 0) {
6808 entry.fourcc = FOURCC_tx3g;
6809 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6810 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6817 qtpad->fourcc = entry.fourcc;
6819 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6820 qtmux->context, &entry);
6822 gst_object_unref (qtmux);
6828 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6829 GST_PAD_NAME (pad), caps);
6830 gst_object_unref (qtmux);
6836 gst_qt_mux_caption_sink_set_caps (GstQTMuxPad * qtpad, GstCaps * caps)
6838 GstPad *pad = GST_PAD (qtpad);
6839 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6840 GstStructure *structure;
6841 guint32 fourcc_entry;
6844 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6845 GST_DEBUG_PAD_NAME (pad), caps);
6847 /* captions default */
6848 qtpad->is_out_of_order = FALSE;
6849 qtpad->sync = FALSE;
6850 qtpad->sparse = TRUE;
6851 /* Closed caption data are within atoms */
6852 qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6854 structure = gst_caps_get_structure (caps, 0);
6856 /* We know we only handle 608,format=s334-1a and 708,format=cdp */
6857 if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6858 fourcc_entry = FOURCC_c608;
6859 } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6860 fourcc_entry = FOURCC_c708;
6864 /* We set the real timescale later to the one from the video track when
6865 * writing the headers */
6866 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6867 if (!timescale && qtmux->trak_timescale)
6868 timescale = qtmux->trak_timescale;
6869 else if (!timescale)
6872 qtpad->fourcc = fourcc_entry;
6874 (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6875 qtmux->context, timescale, fourcc_entry);
6877 /* Initialize caption track language code to 0 unless something else is
6878 * specified. Without this, Final Cut considers it "non-standard"
6880 qtpad->trak->mdia.mdhd.language_code = 0;
6882 gst_object_unref (qtmux);
6888 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6889 GST_PAD_NAME (pad), caps);
6890 gst_object_unref (qtmux);
6895 static GstFlowReturn
6896 gst_qt_mux_sink_event_pre_queue (GstAggregator * agg,
6897 GstAggregatorPad * agg_pad, GstEvent * event)
6899 GstAggregatorClass *agg_class = GST_AGGREGATOR_CLASS (parent_class);
6901 GstFlowReturn ret = GST_FLOW_OK;
6903 qtmux = GST_QT_MUX_CAST (agg);
6905 if (GST_EVENT_TYPE (event) == GST_EVENT_CAPS) {
6908 gst_event_parse_caps (event, &caps);
6909 if (!gst_qt_mux_can_renegotiate (qtmux, GST_PAD (agg_pad), caps)) {
6910 gst_event_unref (event);
6912 ret = GST_FLOW_NOT_NEGOTIATED;
6917 ret = agg_class->sink_event_pre_queue (agg, agg_pad, event);
6924 gst_qt_mux_sink_event (GstAggregator * agg, GstAggregatorPad * agg_pad,
6927 GstAggregatorClass *agg_class = GST_AGGREGATOR_CLASS (parent_class);
6928 GstQTMuxPad *qtmux_pad;
6930 guint32 avg_bitrate = 0, max_bitrate = 0;
6931 GstPad *pad = GST_PAD (agg_pad);
6932 gboolean ret = TRUE;
6934 qtmux = GST_QT_MUX_CAST (agg);
6935 qtmux_pad = GST_QT_MUX_PAD_CAST (agg_pad);
6937 switch (GST_EVENT_TYPE (event)) {
6938 case GST_EVENT_CAPS:
6942 gst_event_parse_caps (event, &caps);
6944 /* find stream data */
6945 g_assert (qtmux_pad->set_caps);
6947 /* depending on codec (h264/h265 for example), muxer will append a new
6948 * stsd entry per set_caps(), but it's not ideal if referenced fields
6949 * in caps is not updated from previous one.
6950 * Each set_caps() implementation can be more enhanced
6951 * so that we can avoid duplicated atoms though, this identical caps
6952 * case is one we can skip obviously */
6953 if (qtmux_pad->configured_caps &&
6954 gst_caps_is_equal (qtmux_pad->configured_caps, caps)) {
6955 GST_DEBUG_OBJECT (qtmux_pad, "Ignore duplicated caps %" GST_PTR_FORMAT,
6958 ret = qtmux_pad->set_caps (qtmux_pad, caps);
6960 GST_OBJECT_LOCK (qtmux);
6961 if (qtmux->current_pad == qtmux_pad) {
6962 qtmux->current_chunk_offset = -1;
6963 qtmux->current_chunk_size = 0;
6964 qtmux->current_chunk_duration = 0;
6966 GST_OBJECT_UNLOCK (qtmux);
6970 gst_caps_replace (&qtmux_pad->configured_caps, caps);
6972 gst_event_unref (event);
6976 case GST_EVENT_TAG:{
6978 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6979 GstTagMergeMode mode;
6982 GST_OBJECT_LOCK (qtmux);
6983 mode = gst_tag_setter_get_tag_merge_mode (setter);
6985 gst_event_parse_tag (event, &list);
6986 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6987 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6989 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6990 gst_tag_setter_merge_tags (setter, list, mode);
6991 qtmux->tags_changed = TRUE;
6993 if (!qtmux_pad->tags)
6994 qtmux_pad->tags = gst_tag_list_new_empty ();
6995 gst_tag_list_insert (qtmux_pad->tags, list, mode);
6996 qtmux_pad->tags_changed = TRUE;
6998 GST_OBJECT_UNLOCK (qtmux);
7000 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
7001 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
7002 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
7003 qtmux_pad->avg_bitrate = avg_bitrate;
7004 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
7005 qtmux_pad->max_bitrate = max_bitrate;
7008 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
7009 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
7011 if (qtmux_pad->trak) {
7012 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
7013 qtmux_pad->trak->mdia.mdhd.language_code = language_code (iso_code);
7019 gst_event_unref (event);
7029 ret = agg_class->sink_event (agg, agg_pad, event);
7035 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
7037 GstQTMux *mux = GST_QT_MUX_CAST (element);
7038 GstQTMuxPad *muxpad = GST_QT_MUX_PAD_CAST (pad);
7040 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
7042 /* Take a ref to the pad so we can clean it up after removing it from the element */
7043 pad = gst_object_ref (pad);
7045 /* Do aggregate level cleanup */
7046 GST_ELEMENT_CLASS (parent_class)->release_pad (element, pad);
7048 GST_OBJECT_LOCK (mux);
7049 if (mux->current_pad && GST_PAD (mux->current_pad) == pad) {
7050 mux->current_pad = NULL;
7051 mux->current_chunk_size = 0;
7052 mux->current_chunk_duration = 0;
7055 gst_qt_mux_pad_reset (muxpad);
7057 if (GST_ELEMENT (mux)->sinkpads == NULL) {
7058 /* No more outstanding request pads, reset our counters */
7059 mux->video_pads = 0;
7060 mux->audio_pads = 0;
7061 mux->subtitle_pads = 0;
7063 GST_OBJECT_UNLOCK (mux);
7065 gst_object_unref (pad);
7068 static GstAggregatorPad *
7069 gst_qt_mux_create_new_pad (GstAggregator * self,
7070 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
7072 return g_object_new (GST_TYPE_QT_MUX_PAD, "name", req_name, "direction",
7073 templ->direction, "template", templ, NULL);
7077 gst_qt_mux_request_new_pad (GstElement * element,
7078 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
7080 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
7081 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
7083 GstQTPadSetCapsFunc setcaps_func;
7087 if (templ->direction != GST_PAD_SINK)
7088 goto wrong_direction;
7090 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
7093 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
7094 setcaps_func = gst_qt_mux_audio_sink_set_caps;
7095 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
7096 name = g_strdup (req_name);
7098 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
7100 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
7101 setcaps_func = gst_qt_mux_video_sink_set_caps;
7102 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
7103 name = g_strdup (req_name);
7105 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
7107 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
7108 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
7109 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
7110 name = g_strdup (req_name);
7112 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
7114 } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
7115 setcaps_func = gst_qt_mux_caption_sink_set_caps;
7116 if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
7117 name = g_strdup (req_name);
7119 name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
7122 goto wrong_template;
7124 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
7126 qtpad = (GstQTMuxPad *)
7127 GST_ELEMENT_CLASS (parent_class)->request_new_pad (element,
7133 GST_OBJECT_LOCK (qtmux);
7134 gst_qt_mux_pad_reset (qtpad);
7135 qtpad->trak = atom_trak_new (qtmux->context);
7137 atom_moov_add_trak (qtmux->moov, qtpad->trak);
7138 GST_OBJECT_UNLOCK (qtmux);
7140 /* set up pad functions */
7141 qtpad->set_caps = setcaps_func;
7142 qtpad->dts = G_MININT64;
7144 return GST_PAD (qtpad);
7149 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
7154 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
7159 GST_WARNING_OBJECT (qtmux, "This is not our template!");
7165 gst_qt_mux_get_property (GObject * object,
7166 guint prop_id, GValue * value, GParamSpec * pspec)
7168 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
7170 GST_OBJECT_LOCK (qtmux);
7172 case PROP_MOVIE_TIMESCALE:
7173 g_value_set_uint (value, qtmux->timescale);
7175 case PROP_TRAK_TIMESCALE:
7176 g_value_set_uint (value, qtmux->trak_timescale);
7179 g_value_set_boolean (value, qtmux->guess_pts);
7181 #ifndef GST_REMOVE_DEPRECATED
7182 case PROP_DTS_METHOD:
7183 g_value_set_enum (value, qtmux->dts_method);
7186 case PROP_FAST_START:
7187 g_value_set_boolean (value, qtmux->fast_start);
7189 case PROP_FAST_START_TEMP_FILE:
7190 g_value_set_string (value, qtmux->fast_start_file_path);
7192 case PROP_MOOV_RECOV_FILE:
7193 g_value_set_string (value, qtmux->moov_recov_file_path);
7195 case PROP_FRAGMENT_DURATION:
7196 g_value_set_uint (value, qtmux->fragment_duration);
7198 case PROP_RESERVED_MAX_DURATION:
7199 g_value_set_uint64 (value, qtmux->reserved_max_duration);
7201 case PROP_RESERVED_DURATION_REMAINING:
7202 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
7203 g_value_set_uint64 (value, qtmux->reserved_max_duration);
7205 GstClockTime remaining = qtmux->reserved_duration_remaining;
7207 /* Report the remaining space as the calculated remaining, minus
7208 * however much we've muxed since the last update */
7209 if (remaining > qtmux->muxed_since_last_update)
7210 remaining -= qtmux->muxed_since_last_update;
7213 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
7214 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
7215 remaining, qtmux->reserved_duration_remaining,
7216 qtmux->muxed_since_last_update);
7217 g_value_set_uint64 (value, remaining);
7220 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
7221 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
7223 case PROP_RESERVED_BYTES_PER_SEC:
7224 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
7226 case PROP_RESERVED_PREFILL:
7227 g_value_set_boolean (value, qtmux->reserved_prefill);
7229 case PROP_INTERLEAVE_BYTES:
7230 g_value_set_uint64 (value, qtmux->interleave_bytes);
7232 case PROP_INTERLEAVE_TIME:
7233 g_value_set_uint64 (value, qtmux->interleave_time);
7235 case PROP_FORCE_CHUNKS:
7236 g_value_set_boolean (value, qtmux->force_chunks);
7238 case PROP_MAX_RAW_AUDIO_DRIFT:
7239 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
7241 case PROP_START_GAP_THRESHOLD:
7242 g_value_set_uint64 (value, qtmux->start_gap_threshold);
7244 case PROP_FORCE_CREATE_TIMECODE_TRAK:
7245 g_value_set_boolean (value, qtmux->force_create_timecode_trak);
7247 case PROP_FRAGMENT_MODE:{
7248 GstQTMuxFragmentMode mode = qtmux->fragment_mode;
7249 if (mode == GST_QT_MUX_FRAGMENT_STREAMABLE)
7250 mode = GST_QT_MUX_FRAGMENT_DASH_OR_MSS;
7251 g_value_set_enum (value, mode);
7255 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7258 GST_OBJECT_UNLOCK (qtmux);
7262 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
7266 g_free (qtmux->fast_start_file_path);
7267 qtmux->fast_start_file_path = NULL;
7269 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
7270 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
7275 gst_qt_mux_set_property (GObject * object,
7276 guint prop_id, const GValue * value, GParamSpec * pspec)
7278 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
7280 GST_OBJECT_LOCK (qtmux);
7282 case PROP_MOVIE_TIMESCALE:
7283 qtmux->timescale = g_value_get_uint (value);
7285 case PROP_TRAK_TIMESCALE:
7286 qtmux->trak_timescale = g_value_get_uint (value);
7289 qtmux->guess_pts = g_value_get_boolean (value);
7291 #ifndef GST_REMOVE_DEPRECATED
7292 case PROP_DTS_METHOD:
7293 qtmux->dts_method = g_value_get_enum (value);
7296 case PROP_FAST_START:
7297 qtmux->fast_start = g_value_get_boolean (value);
7299 case PROP_FAST_START_TEMP_FILE:
7300 g_free (qtmux->fast_start_file_path);
7301 qtmux->fast_start_file_path = g_value_dup_string (value);
7302 /* NULL means to generate a random one */
7303 if (!qtmux->fast_start_file_path) {
7304 gst_qt_mux_generate_fast_start_file_path (qtmux);
7307 case PROP_MOOV_RECOV_FILE:
7308 g_free (qtmux->moov_recov_file_path);
7309 qtmux->moov_recov_file_path = g_value_dup_string (value);
7311 case PROP_FRAGMENT_DURATION:
7312 qtmux->fragment_duration = g_value_get_uint (value);
7314 case PROP_RESERVED_MAX_DURATION:
7315 qtmux->reserved_max_duration = g_value_get_uint64 (value);
7317 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
7318 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
7320 case PROP_RESERVED_BYTES_PER_SEC:
7321 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
7323 case PROP_RESERVED_PREFILL:
7324 qtmux->reserved_prefill = g_value_get_boolean (value);
7326 case PROP_INTERLEAVE_BYTES:
7327 qtmux->interleave_bytes = g_value_get_uint64 (value);
7328 qtmux->interleave_bytes_set = TRUE;
7330 case PROP_INTERLEAVE_TIME:
7331 qtmux->interleave_time = g_value_get_uint64 (value);
7332 qtmux->interleave_time_set = TRUE;
7334 case PROP_FORCE_CHUNKS:
7335 qtmux->force_chunks = g_value_get_boolean (value);
7337 case PROP_MAX_RAW_AUDIO_DRIFT:
7338 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
7340 case PROP_START_GAP_THRESHOLD:
7341 qtmux->start_gap_threshold = g_value_get_uint64 (value);
7343 case PROP_FORCE_CREATE_TIMECODE_TRAK:
7344 qtmux->force_create_timecode_trak = g_value_get_boolean (value);
7345 qtmux->context->force_create_timecode_trak =
7346 qtmux->force_create_timecode_trak;
7348 case PROP_FRAGMENT_MODE:{
7349 GstQTMuxFragmentMode mode = g_value_get_enum (value);
7350 if (mode != GST_QT_MUX_FRAGMENT_STREAMABLE)
7351 qtmux->fragment_mode = mode;
7355 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7358 GST_OBJECT_UNLOCK (qtmux);
7362 gst_qt_mux_start (GstAggregator * agg)
7364 GstQTMux *qtmux = GST_QT_MUX_CAST (agg);
7367 qtmux->state = GST_QT_MUX_STATE_STARTED;
7369 /* let downstream know we think in BYTES and expect to do seeking later on */
7370 gst_segment_init (&segment, GST_FORMAT_BYTES);
7371 gst_aggregator_update_segment (agg, &segment);
7377 gst_qt_mux_stop (GstAggregator * agg)
7379 GstQTMux *qtmux = GST_QT_MUX_CAST (agg);
7381 gst_qt_mux_reset (qtmux, TRUE);
7388 PROP_SUBCLASS_STREAMABLE = 1,
7392 gst_qt_mux_subclass_set_property (GObject * object,
7393 guint prop_id, const GValue * value, GParamSpec * pspec)
7395 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
7397 GST_OBJECT_LOCK (qtmux);
7399 case PROP_SUBCLASS_STREAMABLE:{
7400 GstQTMuxClass *qtmux_klass =
7401 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
7402 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
7403 qtmux->streamable = g_value_get_boolean (value);
7408 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7411 GST_OBJECT_UNLOCK (qtmux);
7415 gst_qt_mux_subclass_get_property (GObject * object,
7416 guint prop_id, GValue * value, GParamSpec * pspec)
7418 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
7420 GST_OBJECT_LOCK (qtmux);
7422 case PROP_SUBCLASS_STREAMABLE:
7423 g_value_set_boolean (value, qtmux->streamable);
7426 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7429 GST_OBJECT_UNLOCK (qtmux);
7433 gst_qt_mux_subclass_class_init (GstQTMuxClass * klass)
7435 GObjectClass *gobject_class = (GObjectClass *) klass;
7436 GParamFlags streamable_flags;
7437 const gchar *streamable_desc;
7438 gboolean streamable;
7439 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
7440 "be streamed and hence no indexes written or duration written."
7442 gobject_class->set_property = gst_qt_mux_subclass_set_property;
7443 gobject_class->get_property = gst_qt_mux_subclass_get_property;
7445 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
7446 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
7447 streamable_desc = STREAMABLE_DESC;
7448 streamable = DEFAULT_STREAMABLE;
7451 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
7452 streamable_flags |= G_PARAM_DEPRECATED;
7456 g_object_class_install_property (gobject_class, PROP_SUBCLASS_STREAMABLE,
7457 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
7458 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
7462 gst_qt_mux_subclass_init (GstQTMux * qtmux)
7467 gst_qt_mux_register (GstPlugin * plugin)
7469 GTypeInfo parent_typeinfo = {
7470 sizeof (GstQTMuxClass),
7471 (GBaseInitFunc) gst_qt_mux_base_init,
7473 (GClassInitFunc) gst_qt_mux_class_init,
7478 (GInstanceInitFunc) gst_qt_mux_init,
7480 static const GInterfaceInfo tag_setter_info = {
7483 static const GInterfaceInfo tag_xmp_writer_info = {
7486 static const GInterfaceInfo preset_info = {
7490 GstQTMuxFormat format;
7491 GstQTMuxClassParams *params;
7494 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
7496 GST_LOG ("Registering muxers");
7499 g_type_register_static (GST_TYPE_AGGREGATOR, "GstBaseQTMux",
7500 &parent_typeinfo, 0);
7501 g_type_add_interface_static (parent_type, GST_TYPE_TAG_SETTER,
7503 g_type_add_interface_static (parent_type, GST_TYPE_TAG_XMP_WRITER,
7504 &tag_xmp_writer_info);
7505 g_type_add_interface_static (parent_type, GST_TYPE_PRESET, &preset_info);
7507 gst_type_mark_as_plugin_api (parent_type, 0);
7511 GTypeInfo subclass_typeinfo = {
7512 sizeof (GstQTMuxClass),
7515 (GClassInitFunc) gst_qt_mux_subclass_class_init,
7520 (GInstanceInitFunc) gst_qt_mux_subclass_init,
7522 GstQTMuxFormatProp *prop;
7523 GstCaps *subtitle_caps, *caption_caps;
7525 prop = &gst_qt_mux_format_list[i];
7526 format = prop->format;
7527 if (format == GST_QT_MUX_FORMAT_NONE)
7530 /* create a cache for these properties */
7531 params = g_new0 (GstQTMuxClassParams, 1);
7532 params->prop = prop;
7533 params->src_caps = gst_static_caps_get (&prop->src_caps);
7534 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
7535 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
7536 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
7537 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
7538 params->subtitle_sink_caps = subtitle_caps;
7540 gst_caps_unref (subtitle_caps);
7542 caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
7543 if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
7544 params->caption_sink_caps = caption_caps;
7546 gst_caps_unref (caption_caps);
7549 /* create the type now */
7551 g_type_register_static (parent_type, prop->type_name,
7552 &subclass_typeinfo, 0);
7553 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
7555 if (!gst_element_register (plugin, prop->name, prop->rank, type))
7561 GST_LOG ("Finished registering muxers");
7563 /* FIXME: ideally classification tag should be added and
7564 registered in gstreamer core gsttaglist
7567 GST_LOG ("Registering tags");
7569 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
7570 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
7571 gst_tag_merge_use_first);
7573 isomp4_element_init (plugin);
7575 GST_LOG ("Finished registering tags");
7580 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (qtmux, gst_qt_mux_register);