1 /* Quicktime muxer plugin for GStreamer
2 * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3 * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4 * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5 * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6 * Contact: Stefan Kost <stefan.kost@nokia.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
24 * Unless otherwise indicated, Source Code is licensed under MIT license.
25 * See further explanation attached in License Statement (distributed in the file
28 * Permission is hereby granted, free of charge, to any person obtaining a copy of
29 * this software and associated documentation files (the "Software"), to deal in
30 * the Software without restriction, including without limitation the rights to
31 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32 * of the Software, and to permit persons to whom the Software is furnished to do
33 * so, subject to the following conditions:
35 * The above copyright notice and this permission notice shall be included in all
36 * copies or substantial portions of the Software.
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49 * SECTION:element-qtmux
50 * @short_description: Muxer for quicktime(.mov) files
52 * This element merges streams (audio and video) into QuickTime(.mov) files.
54 * The following background intends to explain why various similar muxers
55 * are present in this plugin.
57 * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58 * QuickTime file format specification</ulink> served as basis for the MP4 file
59 * format specification (mp4mux), and as such the QuickTime file structure is
60 * nearly identical to the so-called ISO Base Media file format defined in
61 * ISO 14496-12 (except for some media specific parts).
62 * In turn, the latter ISO Base Media format was further specialized as a
63 * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64 * and in various 3GPP(2) specs (gppmux).
65 * The fragmented file features defined (only) in ISO Base Media are used by
66 * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
68 * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale,
69 * #GstQTMuxPad:trak-timescale) allow adjusting some technical parameters,
70 * which might be useful in (rare) cases to resolve compatibility issues in
73 * Some other properties influence the result more fundamentally.
74 * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
75 * file, somewhat contrary to this usually being called "the header".
76 * However, a #GstQTMux:faststart file will (with some effort) arrange this to
77 * be located near start of the file, which then allows it e.g. to be played
78 * while downloading. Alternatively, rather than having one chunk of metadata at
79 * start (or end), there can be some metadata at start and most of the other
80 * data can be spread out into fragments of #GstQTMux:fragment-duration.
81 * If such fragmented layout is intended for streaming purposes, then
82 * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
85 * When the maximum duration to be recorded can be known in advance, #GstQTMux
86 * also supports a 'Robust Muxing' mode. In robust muxing mode, space for the
87 * headers are reserved at the start of muxing, and rewritten at a configurable
88 * interval, so that the output file is always playable, even if the recording
89 * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
90 * output, such as filesink, because it needs to rewrite the start of the file.
92 * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
93 * and #GstQTMux::reserved-max-duration property. Also present is the
94 * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
95 * for some reason the default is not large enough and the initial reserved
96 * space for headers is too small. Applications can monitor the
97 * #GstQTMux::reserved-duration-remaining property to see how close to full
98 * the reserved space is becoming.
101 * <title>Example pipelines</title>
103 * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
105 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
117 #include <glib/gstdio.h>
120 #include <gst/base/gstcollectpads.h>
121 #include <gst/base/gstbytereader.h>
122 #include <gst/base/gstbitreader.h>
123 #include <gst/audio/audio.h>
124 #include <gst/video/video.h>
125 #include <gst/tag/tag.h>
126 #include <gst/pbutils/pbutils.h>
128 #include <sys/types.h>
130 #include <io.h> /* lseek, open, close, read */
132 #define lseek _lseeki64
134 #define off_t guint64
138 #define ftruncate g_win32_ftruncate
145 #include "gstqtmux.h"
147 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
148 #define GST_CAT_DEFAULT gst_qt_mux_debug
151 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
156 * The basic building blocks of MP4 files are:
157 * - an 'ftyp' box at the very start
158 * - an 'mdat' box which contains the raw audio/video/subtitle data;
159 * this is just a bunch of bytes, completely unframed and possibly
160 * unordered with no additional meta-information
161 * - a 'moov' box that contains information about the different streams
162 * and what they contain, as well as sample tables for each stream
163 * that tell the demuxer where in the mdat box each buffer/sample is
164 * and what its duration/timestamp etc. is, and whether it's a
166 * Additionally, fragmented MP4 works by writing chunks of data in
167 * pairs of 'moof' and 'mdat' boxes:
168 * - 'moof' boxes, header preceding each mdat fragment describing the
169 * contents, like a moov but only for that fragment.
170 * - a 'mfra' box for Fragmented MP4, which is written at the end and
171 * contains a summary of all fragments and seek tables.
173 * Currently mp4mux can work in 4 different modes / generate 4 types
174 * of output files/streams:
176 * - Normal mp4: mp4mux will write a little ftyp identifier at the
177 * beginning, then start an mdat box into which it will write all the
178 * sample data. At EOS it will then write the moov header with track
179 * headers and sample tables at the end of the file, and rewrite the
180 * start of the file to fix up the mdat box size at the beginning.
181 * It has to wait for EOS to write the moov (which includes the
182 * sample tables) because it doesn't know how much space those
183 * tables will be. The output downstream must be seekable to rewrite
184 * the mdat box at EOS.
186 * - Fragmented mp4: moov header with track headers at start
187 * but no sample table, followed by N fragments, each containing
188 * track headers with sample tables followed by some data. Downstream
189 * does not need to be seekable if the 'streamable' flag is TRUE,
190 * as the final mfra and total duration will be omitted.
192 * - Fast-start mp4: the goal here is to create a file where the moov
193 * headers are at the beginning; what mp4mux will do is write all
194 * sample data into a temp file and build moov header plus sample
195 * tables in memory and then when EOS comes, it will push out the
196 * moov header plus sample tables at the beginning, followed by the
197 * mdat sample data at the end which is read in from the temp file
198 * Files created in this mode are better for streaming over the
199 * network, since the client doesn't have to seek to the end of the
200 * file to get the headers, but it requires copying all sample data
201 * out of the temp file at EOS, which can be expensive. Downstream does
202 * not need to be seekable, because of the use of the temp file.
204 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
205 * and reserved-moov-update-period properties to reserve free space
206 * at the start of the file and periodically write the MOOV atom out
207 * to it. That means that killing the muxing at any point still
208 * results in a playable file, at the cost of wasting some amount of
209 * free space at the start of file. The approximate recording duration
210 * has to be known in advance to estimate how much free space to reserve
211 * for the moov, and the downstream must be seekable.
212 * If the moov header grows larger than the reserved space, an error
213 * is generated - so it's better to over-estimate the amount of space
214 * to reserve. To ensure the file is playable at any point, the moov
215 * is updated using a 'ping-pong' strategy, so the output is never in
219 #ifndef GST_REMOVE_DEPRECATED
228 gst_qt_mux_dts_method_get_type (void)
230 static GType gst_qt_mux_dts_method = 0;
232 if (!gst_qt_mux_dts_method) {
233 static const GEnumValue dts_methods[] = {
234 {DTS_METHOD_DD, "delta/duration", "dd"},
235 {DTS_METHOD_REORDER, "reorder", "reorder"},
236 {DTS_METHOD_ASC, "ascending", "asc"},
240 gst_qt_mux_dts_method =
241 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
244 return gst_qt_mux_dts_method;
247 #define GST_TYPE_QT_MUX_DTS_METHOD \
248 (gst_qt_mux_dts_method_get_type ())
254 PROP_PAD_TRAK_TIMESCALE,
257 #define DEFAULT_PAD_TRAK_TIMESCALE 0
259 GType gst_qt_mux_pad_get_type (void);
261 #define GST_TYPE_QT_MUX_PAD \
262 (gst_qt_mux_pad_get_type())
263 #define GST_QT_MUX_PAD(obj) \
264 (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_QT_MUX_PAD, GstQTMuxPad))
265 #define GST_QT_MUX_PAD_CLASS(klass) \
266 (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_QT_MUX_PAD, GstQTMuxPadClass))
267 #define GST_IS_QT_MUX_PAD(obj) \
268 (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_QT_MUX_PAD))
269 #define GST_IS_QT_MUX_PAD_CLASS(klass) \
270 (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_QT_MUX_PAD))
271 #define GST_QT_MUX_PAD_CAST(obj) \
272 ((GstQTMuxPad *)(obj))
274 typedef struct _GstQTMuxPad GstQTMuxPad;
275 typedef struct _GstQTMuxPadClass GstQTMuxPadClass;
281 guint32 trak_timescale;
284 struct _GstQTMuxPadClass
289 G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_PAD);
292 gst_qt_mux_pad_set_property (GObject * object,
293 guint prop_id, const GValue * value, GParamSpec * pspec)
295 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
297 GST_OBJECT_LOCK (pad);
299 case PROP_PAD_TRAK_TIMESCALE:
300 pad->trak_timescale = g_value_get_uint (value);
303 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
306 GST_OBJECT_UNLOCK (pad);
310 gst_qt_mux_pad_get_property (GObject * object,
311 guint prop_id, GValue * value, GParamSpec * pspec)
313 GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
315 GST_OBJECT_LOCK (pad);
317 case PROP_PAD_TRAK_TIMESCALE:
318 g_value_set_uint (value, pad->trak_timescale);
321 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
324 GST_OBJECT_UNLOCK (pad);
328 gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
330 GObjectClass *gobject_class = (GObjectClass *) klass;
332 gobject_class->get_property = gst_qt_mux_pad_get_property;
333 gobject_class->set_property = gst_qt_mux_pad_set_property;
335 g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
336 g_param_spec_uint ("trak-timescale", "Track timescale",
337 "Timescale to use for this pad's trak (units per second, 0 is automatic)",
338 0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
339 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
343 gst_qt_mux_pad_init (GstQTMuxPad * pad)
345 pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
349 gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
353 GST_OBJECT_LOCK (pad);
354 timescale = pad->trak_timescale;
355 GST_OBJECT_UNLOCK (pad);
360 /* QTMux signals and args */
370 PROP_MOVIE_TIMESCALE,
373 PROP_FAST_START_TEMP_FILE,
374 PROP_MOOV_RECOV_FILE,
375 PROP_FRAGMENT_DURATION,
377 PROP_RESERVED_MAX_DURATION,
378 PROP_RESERVED_DURATION_REMAINING,
379 PROP_RESERVED_MOOV_UPDATE_PERIOD,
380 PROP_RESERVED_BYTES_PER_SEC,
381 PROP_RESERVED_PREFILL,
382 #ifndef GST_REMOVE_DEPRECATED
386 PROP_INTERLEAVE_BYTES,
387 PROP_INTERLEAVE_TIME,
388 PROP_MAX_RAW_AUDIO_DRIFT,
391 /* some spare for header size as well */
392 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
394 #define DEFAULT_MOVIE_TIMESCALE 0
395 #define DEFAULT_TRAK_TIMESCALE 0
396 #define DEFAULT_DO_CTTS TRUE
397 #define DEFAULT_FAST_START FALSE
398 #define DEFAULT_FAST_START_TEMP_FILE NULL
399 #define DEFAULT_MOOV_RECOV_FILE NULL
400 #define DEFAULT_FRAGMENT_DURATION 0
401 #define DEFAULT_STREAMABLE TRUE
402 #ifndef GST_REMOVE_DEPRECATED
403 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
405 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
406 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
407 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
408 #define DEFAULT_RESERVED_PREFILL FALSE
409 #define DEFAULT_INTERLEAVE_BYTES 0
410 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
411 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
413 static void gst_qt_mux_finalize (GObject * object);
415 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
416 GstStateChange transition);
418 /* property functions */
419 static void gst_qt_mux_set_property (GObject * object,
420 guint prop_id, const GValue * value, GParamSpec * pspec);
421 static void gst_qt_mux_get_property (GObject * object,
422 guint prop_id, GValue * value, GParamSpec * pspec);
425 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
426 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
427 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
430 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
431 GstCollectData * data, GstEvent * event, gpointer user_data);
433 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
435 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
439 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
441 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
442 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
444 static GstElementClass *parent_class = NULL;
447 gst_qt_mux_base_init (gpointer g_class)
449 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
450 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
451 GstQTMuxClassParams *params;
452 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
453 GstPadTemplate *srctempl;
454 gchar *longname, *description;
457 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
458 GST_QT_MUX_PARAMS_QDATA);
459 g_assert (params != NULL);
461 /* construct the element details struct */
462 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
463 description = g_strdup_printf ("Multiplex audio and video into a %s file",
464 params->prop->long_name);
465 gst_element_class_set_static_metadata (element_class, longname,
466 "Codec/Muxer", description,
467 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
469 g_free (description);
472 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
473 GST_PAD_ALWAYS, params->src_caps);
474 gst_element_class_add_pad_template (element_class, srctempl);
476 if (params->audio_sink_caps) {
477 audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
478 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
479 GST_TYPE_QT_MUX_PAD);
480 gst_element_class_add_pad_template (element_class, audiosinktempl);
483 if (params->video_sink_caps) {
484 videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
485 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
486 GST_TYPE_QT_MUX_PAD);
487 gst_element_class_add_pad_template (element_class, videosinktempl);
490 if (params->subtitle_sink_caps) {
491 subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
492 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
493 GST_TYPE_QT_MUX_PAD);
494 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
497 klass->format = params->prop->format;
501 gst_qt_mux_class_init (GstQTMuxClass * klass)
503 GObjectClass *gobject_class;
504 GstElementClass *gstelement_class;
505 GParamFlags streamable_flags;
506 const gchar *streamable_desc;
508 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
509 "be streamed and hence no indexes written or duration written."
511 gobject_class = (GObjectClass *) klass;
512 gstelement_class = (GstElementClass *) klass;
514 parent_class = g_type_class_peek_parent (klass);
516 gobject_class->finalize = gst_qt_mux_finalize;
517 gobject_class->get_property = gst_qt_mux_get_property;
518 gobject_class->set_property = gst_qt_mux_set_property;
520 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
521 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
522 streamable_desc = STREAMABLE_DESC;
523 streamable = DEFAULT_STREAMABLE;
526 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
527 streamable_flags |= G_PARAM_DEPRECATED;
531 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
532 g_param_spec_uint ("movie-timescale", "Movie timescale",
533 "Timescale to use in the movie (units per second, 0 == default)",
534 0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
535 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
536 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
537 g_param_spec_uint ("trak-timescale", "Track timescale",
538 "Timescale to use for the tracks (units per second, 0 is automatic)",
539 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
540 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
541 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
542 g_param_spec_boolean ("presentation-time",
543 "Include presentation-time info",
544 "Calculate and include presentation/composition time "
545 "(in addition to decoding time)", DEFAULT_DO_CTTS,
546 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
547 #ifndef GST_REMOVE_DEPRECATED
548 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
549 g_param_spec_enum ("dts-method", "dts-method",
550 "Method to determine DTS time (DEPRECATED)",
551 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
552 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
553 G_PARAM_STATIC_STRINGS));
555 g_object_class_install_property (gobject_class, PROP_FAST_START,
556 g_param_spec_boolean ("faststart", "Format file to faststart",
557 "If the file should be formatted for faststart (headers first)",
558 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
559 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
560 g_param_spec_string ("faststart-file", "File to use for storing buffers",
561 "File that will be used temporarily to store data from the stream "
562 "when creating a faststart file. If null a filepath will be "
563 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
564 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
565 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
566 g_param_spec_string ("moov-recovery-file",
567 "File to store data for posterior moov atom recovery",
568 "File to be used to store "
569 "data for moov atom making movie file recovery possible in case "
570 "of a crash during muxing. Null for disabled. (Experimental)",
571 DEFAULT_MOOV_RECOV_FILE,
572 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
573 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
574 g_param_spec_uint ("fragment-duration", "Fragment duration",
575 "Fragment durations in ms (produce a fragmented file if > 0)",
576 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
577 2000 : DEFAULT_FRAGMENT_DURATION,
578 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
579 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
580 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
581 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
582 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
583 g_param_spec_uint64 ("reserved-max-duration",
584 "Reserved maximum file duration (ns)",
585 "When set to a value > 0, reserves space for index tables at the "
586 "beginning of the file.",
587 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
588 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
589 g_object_class_install_property (gobject_class,
590 PROP_RESERVED_DURATION_REMAINING,
591 g_param_spec_uint64 ("reserved-duration-remaining",
592 "Report the approximate amount of remaining recording space (ns)",
593 "Reports the approximate amount of remaining moov header space "
594 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
595 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
596 g_object_class_install_property (gobject_class,
597 PROP_RESERVED_MOOV_UPDATE_PERIOD,
598 g_param_spec_uint64 ("reserved-moov-update-period",
599 "Interval at which to update index tables (ns)",
600 "When used with reserved-max-duration, periodically updates the "
601 "index tables with information muxed so far.", 0, G_MAXUINT64,
602 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
603 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
604 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
605 g_param_spec_uint ("reserved-bytes-per-sec",
606 "Reserved MOOV bytes per second, per track",
607 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
608 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
609 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
610 g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
611 g_param_spec_boolean ("reserved-prefill",
612 "Reserved Prefill Samples Table",
613 "Prefill samples table of reserved duration",
614 DEFAULT_RESERVED_PREFILL,
615 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
616 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
617 g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
618 "Interleave between streams in bytes",
619 0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
620 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
621 g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
622 g_param_spec_uint64 ("interleave-time", "Interleave (time)",
623 "Interleave between streams in nanoseconds",
624 0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
625 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
626 g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
627 g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
628 "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
629 0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
630 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
632 gstelement_class->request_new_pad =
633 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
634 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
635 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
639 gst_qt_mux_pad_reset (GstQTPad * qtpad)
642 qtpad->is_out_of_order = FALSE;
643 qtpad->sample_size = 0;
646 qtpad->sample_offset = 0;
647 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
648 qtpad->first_ts = GST_CLOCK_TIME_NONE;
649 qtpad->first_dts = GST_CLOCK_TIME_NONE;
650 qtpad->prepare_buf_func = NULL;
651 qtpad->create_empty_buffer = NULL;
652 qtpad->avg_bitrate = 0;
653 qtpad->max_bitrate = 0;
654 qtpad->total_duration = 0;
655 qtpad->total_bytes = 0;
656 qtpad->sparse = FALSE;
658 gst_buffer_replace (&qtpad->last_buf, NULL);
661 gst_tag_list_unref (qtpad->tags);
665 /* reference owned elsewhere */
667 qtpad->tc_trak = NULL;
670 atom_traf_free (qtpad->traf);
673 atom_array_clear (&qtpad->fragment_buffers);
675 g_array_unref (qtpad->samples);
676 qtpad->samples = NULL;
678 /* reference owned elsewhere */
681 qtpad->first_pts = GST_CLOCK_TIME_NONE;
684 gst_video_time_code_free (qtpad->first_tc);
685 qtpad->first_tc = NULL;
687 if (qtpad->raw_audio_adapter)
688 gst_object_unref (qtpad->raw_audio_adapter);
689 qtpad->raw_audio_adapter = NULL;
693 * Takes GstQTMux back to its initial state
696 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
700 qtmux->state = GST_QT_MUX_STATE_NONE;
701 qtmux->header_size = 0;
702 qtmux->mdat_size = 0;
705 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
706 qtmux->fragment_sequence = 0;
709 atom_ftyp_free (qtmux->ftyp);
713 atom_moov_free (qtmux->moov);
717 atom_mfra_free (qtmux->mfra);
720 if (qtmux->fast_start_file) {
721 fclose (qtmux->fast_start_file);
722 g_remove (qtmux->fast_start_file_path);
723 qtmux->fast_start_file = NULL;
725 if (qtmux->moov_recov_file) {
726 fclose (qtmux->moov_recov_file);
727 qtmux->moov_recov_file = NULL;
729 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
730 AtomInfo *ainfo = (AtomInfo *) walk->data;
731 ainfo->free_func (ainfo->atom);
734 g_slist_free (qtmux->extra_atoms);
735 qtmux->extra_atoms = NULL;
737 GST_OBJECT_LOCK (qtmux);
738 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
739 GST_OBJECT_UNLOCK (qtmux);
742 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
743 GstQTPad *qtpad = (GstQTPad *) walk->data;
744 gst_qt_mux_pad_reset (qtpad);
746 /* hm, moov_free above yanked the traks away from us,
747 * so do not free, but do clear */
752 qtmux->moov = atom_moov_new (qtmux->context);
753 /* ensure all is as nice and fresh as request_new_pad would provide it */
754 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
755 GstQTPad *qtpad = (GstQTPad *) walk->data;
757 qtpad->trak = atom_trak_new (qtmux->context);
758 atom_moov_add_trak (qtmux->moov, qtpad->trak);
762 qtmux->current_pad = NULL;
763 qtmux->current_chunk_size = 0;
764 qtmux->current_chunk_duration = 0;
765 qtmux->current_chunk_offset = -1;
767 qtmux->reserved_moov_size = 0;
768 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
769 qtmux->muxed_since_last_update = 0;
770 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
774 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
776 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
777 GstPadTemplate *templ;
779 templ = gst_element_class_get_pad_template (klass, "src");
780 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
781 gst_pad_use_fixed_caps (qtmux->srcpad);
782 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
784 qtmux->sinkpads = NULL;
785 qtmux->collect = gst_collect_pads_new ();
786 gst_collect_pads_set_event_function (qtmux->collect,
787 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
788 gst_collect_pads_set_clip_function (qtmux->collect,
789 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
790 gst_collect_pads_set_function (qtmux->collect,
791 GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
793 /* properties set to default upon construction */
795 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
796 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
797 qtmux->reserved_bytes_per_sec_per_trak =
798 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
799 qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
800 qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
801 qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
803 /* always need this */
805 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
807 /* internals to initial state */
808 gst_qt_mux_reset (qtmux, TRUE);
813 gst_qt_mux_finalize (GObject * object)
815 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
817 gst_qt_mux_reset (qtmux, FALSE);
819 g_free (qtmux->fast_start_file_path);
820 g_free (qtmux->moov_recov_file_path);
822 atoms_context_free (qtmux->context);
823 gst_object_unref (qtmux->collect);
825 g_slist_free (qtmux->sinkpads);
827 G_OBJECT_CLASS (parent_class)->finalize (object);
831 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
838 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
843 size = gst_buffer_get_size (buf);
844 newbuf = gst_buffer_new_and_alloc (size + 8);
845 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
847 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
848 GST_WRITE_UINT32_BE (map.data, map.size);
849 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
851 gst_buffer_unmap (buf, &map);
852 gst_buffer_unref (buf);
858 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
865 const guint8 *dataend;
867 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
872 gst_buffer_map (buf, &frommap, GST_MAP_READ);
874 dataend = memchr (frommap.data, 0, frommap.size);
875 size = dataend ? dataend - frommap.data : frommap.size;
876 newbuf = gst_buffer_new_and_alloc (size + 2);
878 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
880 GST_WRITE_UINT16_BE (tomap.data, size);
881 memcpy (tomap.data + 2, frommap.data, size);
883 gst_buffer_unmap (newbuf, &tomap);
884 gst_buffer_unmap (buf, &frommap);
886 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
888 /* gst_buffer_copy_into is trying to be too clever and
889 * won't copy duration when size is different */
890 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
892 gst_buffer_unref (buf);
898 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
899 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
904 g_return_if_fail (qtpad->trak_ste);
906 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
908 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
912 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
916 GstByteReader reader;
919 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
920 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
924 if (G_UNLIKELY (map.size < 8))
927 gst_byte_reader_init (&reader, map.data, map.size);
928 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
933 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
935 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
938 gst_bit_reader_init (&bits, map.data, map.size);
940 /* off + sync + crc */
941 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
943 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
944 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
945 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
946 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
947 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
949 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
950 gst_bit_reader_skip_unchecked (&bits, 2);
951 if ((acmod & 0x4)) /* if a surround channel exists */
952 gst_bit_reader_skip_unchecked (&bits, 2);
953 if (acmod == 0x2) /* if in 2/0 mode */
954 gst_bit_reader_skip_unchecked (&bits, 2);
956 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
958 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
959 bsmod, acmod, lfe_on);
961 /* AC-3 spec says that those values should be constant for the
962 * whole stream when muxed in mp4. We trust the input follows it */
963 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
964 "prepare buffer function");
965 qtpad->prepare_buf_func = NULL;
969 gst_buffer_unmap (buf, &map);
974 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
979 GST_WRITE_UINT16_BE (data, 0);
981 return gst_buffer_new_wrapped (data, 2);
985 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
986 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
988 switch (gst_tag_get_type (tag)) {
994 if (!gst_tag_list_get_string (list, tag, &str) || !str)
996 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
997 GST_FOURCC_ARGS (fourcc), str);
998 atom_udta_add_str_tag (udta, fourcc, str);
1007 if (!gst_tag_list_get_double (list, tag, &value))
1009 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1010 GST_FOURCC_ARGS (fourcc), (gint) value);
1011 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1018 /* paired unsigned integers */
1022 got_tag = gst_tag_list_get_uint (list, tag, &value);
1023 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1026 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1027 GST_FOURCC_ARGS (fourcc), value, count);
1028 atom_udta_add_uint_tag (udta, fourcc, 0,
1029 value << 16 | (count & 0xFFFF));
1031 /* unpaired unsigned integers */
1032 if (!gst_tag_list_get_uint (list, tag, &value))
1034 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1035 GST_FOURCC_ARGS (fourcc), value);
1036 atom_udta_add_uint_tag (udta, fourcc, 1, value);
1041 g_assert_not_reached ();
1047 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1048 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1056 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1058 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1061 year = g_date_get_year (date);
1062 month = g_date_get_month (date);
1063 day = g_date_get_day (date);
1067 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1068 day == G_DATE_BAD_DAY) {
1069 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1073 str = g_strdup_printf ("%u-%u-%u", year, month, day);
1074 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1075 GST_FOURCC_ARGS (fourcc), str);
1076 atom_udta_add_str_tag (udta, fourcc, str);
1081 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1082 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1084 GValue value = { 0, };
1088 GstStructure *structure;
1092 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1094 if (!gst_tag_list_copy_value (&value, list, tag))
1097 sample = gst_value_get_sample (&value);
1102 buf = gst_sample_get_buffer (sample);
1106 caps = gst_sample_get_caps (sample);
1108 GST_WARNING_OBJECT (qtmux, "preview image without caps");
1112 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1114 structure = gst_caps_get_structure (caps, 0);
1115 if (gst_structure_has_name (structure, "image/jpeg"))
1117 else if (gst_structure_has_name (structure, "image/png"))
1121 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1125 gst_buffer_map (buf, &map, GST_MAP_READ);
1126 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1127 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1128 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1129 gst_buffer_unmap (buf, &map);
1131 g_value_unset (&value);
1135 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1136 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1141 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1142 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1144 if (!gst_tag_list_get_string (list, tag, &str) || !str)
1148 if (!gst_tag_list_get_uint (list, tag2, &number))
1152 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1153 GST_FOURCC_ARGS (fourcc), str);
1154 atom_udta_add_3gp_str_tag (udta, fourcc, str);
1156 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1157 GST_FOURCC_ARGS (fourcc), str, number);
1158 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1165 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1166 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1171 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1173 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1176 year = g_date_get_year (date);
1179 if (year == G_DATE_BAD_YEAR) {
1180 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1184 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1185 GST_FOURCC_ARGS (fourcc), year);
1186 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1190 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1191 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1193 gdouble latitude = -360, longitude = -360, altitude = 0;
1194 gchar *location = NULL;
1195 guint8 *data, *ddata;
1196 gint size = 0, len = 0;
1197 gboolean ret = FALSE;
1199 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1201 ret = gst_tag_list_get_string (list, tag, &location);
1202 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1204 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1206 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1213 len = strlen (location);
1214 size += len + 1 + 2;
1216 /* role + (long, lat, alt) + body + notes */
1217 size += 1 + 3 * 4 + 1 + 1;
1219 data = ddata = g_malloc (size);
1222 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1225 memcpy (data + 2, location, len);
1226 GST_WRITE_UINT8 (data + 2 + len, 0);
1227 data += len + 1 + 2;
1229 GST_WRITE_UINT8 (data, 0);
1230 /* long, lat, alt */
1231 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1232 QT_WRITE_SFP32 (data + 1, longitude);
1233 QT_WRITE_SFP32 (data + 5, latitude);
1234 QT_WRITE_SFP32 (data + 9, altitude);
1235 /* neither astronomical body nor notes */
1236 GST_WRITE_UINT16_BE (data + 13, 0);
1238 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1239 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1244 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1245 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1247 gchar *keywords = NULL;
1248 guint8 *data, *ddata;
1252 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1254 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1257 kwds = g_strsplit (keywords, ",", 0);
1261 for (i = 0; kwds[i]; i++) {
1262 /* size byte + null-terminator */
1263 size += strlen (kwds[i]) + 1 + 1;
1266 /* language tag + count + keywords */
1269 data = ddata = g_malloc (size);
1272 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1274 GST_WRITE_UINT8 (data + 2, i);
1277 for (i = 0; kwds[i]; ++i) {
1278 gint len = strlen (kwds[i]);
1280 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1281 GST_FOURCC_ARGS (fourcc), kwds[i]);
1283 GST_WRITE_UINT8 (data, len + 1);
1284 memcpy (data + 1, kwds[i], len + 1);
1290 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1295 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1296 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1304 size = strlen (input);
1306 if (size < 4 + 3 + 1 + 1 + 1) {
1307 /* at least the minimum xxxx://y/z */
1308 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1313 /* read the fourcc */
1314 memcpy (&fourcc, data, 4);
1318 if (strncmp (data, "://", 3) != 0) {
1324 /* read the table number */
1325 if (sscanf (data, "%d", &table) != 1) {
1329 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1330 ", table numbers should be positive, ignoring tag", table);
1334 /* find the next / */
1335 while (size > 0 && data[0] != '/') {
1342 g_assert (data[0] == '/');
1351 /* read up the rest of the string */
1352 *p_content = g_strdup (data);
1353 *p_table = (guint16) table;
1359 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1360 "input (%s) didn't match the expected entitycode://table/content",
1367 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1368 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1370 gchar *clsf_data = NULL;
1374 gchar *content = NULL;
1377 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1379 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1382 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1383 GST_FOURCC_ARGS (fourcc), clsf_data);
1385 /* parse the string, format is:
1386 * entityfourcc://table/content
1388 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1392 size = strlen (content) + 1;
1394 /* now we have everything, build the atom
1395 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1396 data = g_malloc (4 + 2 + 2 + size);
1397 GST_WRITE_UINT32_LE (data, entity);
1398 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1399 GST_WRITE_UINT16_BE (data + 6, 0);
1400 memcpy (data + 8, content, size);
1403 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1407 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1408 const GstTagList * list, AtomUDTA * udta, const char *tag,
1409 const char *tag2, guint32 fourcc);
1412 * Struct to record mappings from gstreamer tags to fourcc codes
1414 typedef struct _GstTagToFourcc
1417 const gchar *gsttag;
1418 const gchar *gsttag2;
1419 const GstQTMuxAddUdtaTagFunc func;
1422 /* tag list tags to fourcc matching */
1423 static const GstTagToFourcc tag_matches_mp4[] = {
1424 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1425 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1426 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1427 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1428 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1429 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1430 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1431 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1432 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1433 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1434 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1435 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1436 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1437 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1438 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1439 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1440 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1441 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1442 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1443 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1444 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1445 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1446 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1447 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1448 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1449 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1450 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1451 gst_qt_mux_add_mp4_tag},
1452 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1453 gst_qt_mux_add_mp4_tag},
1454 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1455 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1459 static const GstTagToFourcc tag_matches_3gp[] = {
1460 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1461 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1462 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1463 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1464 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1465 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1466 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1467 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1468 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1469 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1470 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1471 gst_qt_mux_add_3gp_classification},
1475 /* qtdemux produces these for atoms it cannot parse */
1476 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1479 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1481 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1482 GstBuffer *xmp = NULL;
1484 /* adobe specs only have 'quicktime' and 'mp4',
1485 * but I guess we can extrapolate to gpp.
1486 * Keep mj2 out for now as we don't add any tags for it yet.
1487 * If you have further info about xmp on these formats, please share */
1488 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1491 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1493 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1494 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1497 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1500 /* for isom/mp4, it is a top level uuid atom */
1501 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1504 ainfo = build_uuid_xmp_atom (xmp);
1506 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1511 gst_buffer_unref (xmp);
1515 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1518 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1521 const gchar *tag, *tag2;
1522 const GstTagToFourcc *tag_matches;
1524 switch (qtmux_klass->format) {
1525 case GST_QT_MUX_FORMAT_3GP:
1526 tag_matches = tag_matches_3gp;
1528 case GST_QT_MUX_FORMAT_MJ2:
1532 /* sort of iTunes style for mp4 and QT (?) */
1533 tag_matches = tag_matches_mp4;
1540 /* Clear existing tags so we don't add them over and over */
1541 atom_udta_clear_tags (udta);
1543 for (i = 0; tag_matches[i].fourcc; i++) {
1544 fourcc = tag_matches[i].fourcc;
1545 tag = tag_matches[i].gsttag;
1546 tag2 = tag_matches[i].gsttag2;
1548 g_assert (tag_matches[i].func);
1549 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1552 /* add unparsed blobs if present */
1553 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1556 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1557 for (i = 0; i < num_tags; ++i) {
1558 GstSample *sample = NULL;
1560 const GstStructure *s;
1562 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1565 buf = gst_sample_get_buffer (sample);
1567 if (buf && (s = gst_sample_get_info (sample))) {
1568 const gchar *style = NULL;
1571 gst_buffer_map (buf, &map, GST_MAP_READ);
1572 GST_DEBUG_OBJECT (qtmux,
1573 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1574 GST_PTR_FORMAT, i, num_tags, map.size, s);
1575 if (s && (style = gst_structure_get_string (s, "style"))) {
1576 /* try to prevent some style tag ending up into another variant
1577 * (todo: make into a list if more cases) */
1578 if ((strcmp (style, "itunes") == 0 &&
1579 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1580 (strcmp (style, "iso") == 0 &&
1581 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1582 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1583 atom_udta_add_blob_tag (udta, map.data, map.size);
1586 gst_buffer_unmap (buf, &map);
1588 gst_sample_unref (sample);
1596 * Gets the tagsetter iface taglist and puts the known tags
1597 * into the output stream
1600 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1602 const GstTagList *tags = NULL;
1605 GST_OBJECT_LOCK (qtmux);
1606 if (qtmux->tags_changed) {
1607 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1608 qtmux->tags_changed = FALSE;
1610 GST_OBJECT_UNLOCK (qtmux);
1612 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1614 if (tags && !gst_tag_list_is_empty (tags)) {
1615 GstTagList *copy = gst_tag_list_copy (tags);
1617 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1618 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1619 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1620 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1622 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1623 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1624 gst_qt_mux_add_xmp_tags (qtmux, copy);
1625 gst_tag_list_unref (copy);
1627 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1630 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1631 GstCollectData *cdata = (GstCollectData *) walk->data;
1632 GstQTPad *qpad = (GstQTPad *) cdata;
1633 GstPad *pad = qpad->collect.pad;
1635 if (qpad->tags_changed && qpad->tags) {
1636 GST_DEBUG_OBJECT (pad, "Adding tags");
1637 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1638 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1639 qpad->tags_changed = FALSE;
1640 GST_DEBUG_OBJECT (pad, "Tags added");
1642 GST_DEBUG_OBJECT (pad, "No new tags received");
1647 static inline GstBuffer *
1648 _gst_buffer_new_take_data (guint8 * data, guint size)
1652 buf = gst_buffer_new ();
1653 gst_buffer_append_memory (buf,
1654 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1659 static GstFlowReturn
1660 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1666 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1668 size = gst_buffer_get_size (buf);
1669 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1671 if (mind_fast && qtmux->fast_start_file) {
1675 GST_LOG_OBJECT (qtmux, "to temporary file");
1676 gst_buffer_map (buf, &map, GST_MAP_READ);
1677 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1678 gst_buffer_unmap (buf, &map);
1679 gst_buffer_unref (buf);
1685 GST_LOG_OBJECT (qtmux, "downstream");
1686 res = gst_pad_push (qtmux->srcpad, buf);
1689 if (G_LIKELY (offset))
1697 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1698 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1699 return GST_FLOW_ERROR;
1704 gst_qt_mux_seek_to_beginning (FILE * f)
1707 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1709 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1710 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1713 if (fseek (f, (long) 0, SEEK_SET) != 0)
1719 static GstFlowReturn
1720 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1722 GstFlowReturn ret = GST_FLOW_OK;
1723 GstBuffer *buf = NULL;
1725 if (fflush (qtmux->fast_start_file))
1728 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1731 /* hm, this could all take a really really long time,
1732 * but there may not be another way to get moov atom first
1733 * (somehow optimize copy?) */
1734 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1735 while (ret == GST_FLOW_OK) {
1736 const int bufsize = 4096;
1740 buf = gst_buffer_new_and_alloc (bufsize);
1741 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1742 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1744 gst_buffer_unmap (buf, &map);
1747 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1748 gst_buffer_unmap (buf, &map);
1749 if (size != bufsize)
1750 gst_buffer_set_size (buf, size);
1751 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1755 gst_buffer_unref (buf);
1757 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1759 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1767 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1768 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1769 ret = GST_FLOW_ERROR;
1774 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1775 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1776 ret = GST_FLOW_ERROR;
1781 /* clear descriptor so we don't remove temp file later on,
1782 * might be possible to recover */
1783 fclose (qtmux->fast_start_file);
1784 qtmux->fast_start_file = NULL;
1790 * Sends the initial mdat atom fields (size fields and fourcc type),
1791 * the subsequent buffers are considered part of it's data.
1792 * As we can't predict the amount of data that we are going to place in mdat
1793 * we need to record the position of the size field in the stream so we can
1794 * seek back to it later and update when the streams have finished.
1796 static GstFlowReturn
1797 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1798 gboolean extended, gboolean fsync_after)
1803 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1804 "size %" G_GUINT64_FORMAT, size);
1806 /* if the qtmux state is EOS, really write the mdat, otherwise
1807 * allow size == 0 for a placeholder atom */
1808 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1812 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1813 /* Always write 16-bytes, but put a free atom first
1814 * if the size is < 4GB. */
1815 buf = gst_buffer_new_and_alloc (16);
1816 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1819 /* Write extended mdat header and large_size field */
1820 GST_WRITE_UINT32_BE (map.data, 1);
1821 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1822 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1824 /* Write an empty free atom, then standard 32-bit mdat */
1825 GST_WRITE_UINT32_BE (map.data, 8);
1826 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1827 GST_WRITE_UINT32_BE (map.data + 8, size);
1828 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1830 gst_buffer_unmap (buf, &map);
1832 buf = gst_buffer_new_and_alloc (8);
1833 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1835 /* Vanilla 32-bit mdat */
1836 GST_WRITE_UINT32_BE (map.data, size);
1837 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1838 gst_buffer_unmap (buf, &map);
1841 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1843 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1845 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1850 * We get the position of the mdat size field, seek back to it
1851 * and overwrite with the real value
1853 static GstFlowReturn
1854 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1855 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1859 /* We must have recorded the mdat position for this to work */
1860 g_assert (mdat_pos != 0);
1862 /* seek and rewrite the header */
1863 gst_segment_init (&segment, GST_FORMAT_BYTES);
1864 segment.start = mdat_pos;
1865 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1867 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1871 static GstFlowReturn
1872 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1875 guint64 size = 0, offset = 0;
1876 guint8 *data = NULL;
1878 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1880 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1881 goto serialize_error;
1883 buf = _gst_buffer_new_take_data (data, offset);
1885 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1886 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1891 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1892 ("Failed to serialize ftyp"));
1893 return GST_FLOW_ERROR;
1898 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1899 GstBuffer ** p_prefix)
1901 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1902 guint32 major, version;
1904 GstBuffer *prefix = NULL;
1905 AtomFTYP *ftyp = NULL;
1907 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1909 /* init and send context and ftyp based on current property state */
1910 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1911 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1912 qtmux->fast_start_file != NULL);
1913 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1920 gst_buffer_unref (prefix);
1925 static GstFlowReturn
1926 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1928 GstFlowReturn ret = GST_FLOW_OK;
1929 GstBuffer *prefix = NULL;
1931 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1933 /* init and send context and ftyp based on current property state */
1935 atom_ftyp_free (qtmux->ftyp);
1938 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1940 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1941 if (ret != GST_FLOW_OK)
1944 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1948 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1950 GstStructure *structure;
1951 GValue array = { 0 };
1952 GValue value = { 0 };
1953 GstCaps *caps, *tcaps;
1955 tcaps = gst_pad_get_current_caps (mux->srcpad);
1956 caps = gst_caps_copy (tcaps);
1957 gst_caps_unref (tcaps);
1959 structure = gst_caps_get_structure (caps, 0);
1961 g_value_init (&array, GST_TYPE_ARRAY);
1963 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1964 g_value_init (&value, GST_TYPE_BUFFER);
1965 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1966 gst_value_array_append_value (&array, &value);
1967 g_value_unset (&value);
1969 gst_structure_set_value (structure, "streamheader", &array);
1970 g_value_unset (&array);
1971 gst_pad_set_caps (mux->srcpad, caps);
1972 gst_caps_unref (caps);
1976 * Write out a free space atom. The offset is adjusted by the full
1977 * size, but a smaller buffer is sent
1979 static GstFlowReturn
1980 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1981 gboolean fsync_after)
1985 guint8 *data = NULL;
1986 guint64 offset = 0, bsize = 0;
1989 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1991 /* We can't make a free space atom smaller than the header */
1995 node_header = g_malloc0 (sizeof (Atom));
1996 node_header->type = FOURCC_free;
1997 node_header->size = size;
2000 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2001 goto serialize_error;
2003 buf = _gst_buffer_new_take_data (data, offset);
2004 g_free (node_header);
2007 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2009 GST_LOG_OBJECT (qtmux, "Pushing free atom");
2010 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2017 /* Make sure downstream position ends up at the end of this free box */
2018 gst_segment_init (&segment, GST_FORMAT_BYTES);
2019 segment.start = *off;
2020 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2028 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2029 ("Not enough free reserved space"));
2030 return GST_FLOW_ERROR;
2034 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2035 ("Failed to serialize mdat"));
2036 g_free (node_header);
2037 return GST_FLOW_ERROR;
2042 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2044 gboolean fragmented = FALSE;
2047 GST_OBJECT_LOCK (qtmux);
2048 timescale = qtmux->timescale;
2049 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2050 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2052 GST_OBJECT_UNLOCK (qtmux);
2054 /* inform lower layers of our property wishes, and determine duration.
2055 * Let moov take care of this using its list of traks;
2056 * so that released pads are also included */
2057 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2059 atom_moov_update_timescale (qtmux->moov, timescale);
2060 atom_moov_set_fragmented (qtmux->moov, fragmented);
2062 atom_moov_update_duration (qtmux->moov);
2065 static GstFlowReturn
2066 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2067 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2069 guint64 offset = 0, size = 0;
2072 GstFlowReturn ret = GST_FLOW_OK;
2074 guint64 current_time = atoms_get_current_qt_time ();
2076 /* update modification times */
2077 qtmux->moov->mvhd.time_info.modification_time = current_time;
2078 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2079 GstCollectData *cdata = (GstCollectData *) walk->data;
2080 GstQTPad *qtpad = (GstQTPad *) cdata;
2082 qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2083 qtpad->trak->tkhd.modification_time = current_time;
2086 /* serialize moov */
2089 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2090 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2091 goto serialize_error;
2092 qtmux->last_moov_size = offset;
2094 /* Check we have enough reserved space for this and a Free atom */
2095 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2096 goto too_small_reserved;
2097 buf = _gst_buffer_new_take_data (data, offset);
2098 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2100 /* If at EOS, this is the final moov, put in the streamheader
2101 * (apparently used by a flumotion util) */
2102 if (qtmux->state == GST_QT_MUX_STATE_EOS)
2103 gst_qt_mux_set_header_on_caps (qtmux, buf);
2106 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2107 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2109 /* Write out a free atom if needed */
2110 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2111 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2112 (guint32) (padded_moov_size - offset));
2114 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2121 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2122 ("Not enough free reserved header space"),
2123 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2124 offset, padded_moov_size));
2125 return GST_FLOW_ERROR;
2130 return GST_FLOW_ERROR;
2134 /* either calculates size of extra atoms or pushes them */
2135 static GstFlowReturn
2136 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2140 guint64 loffset = 0, size = 0;
2142 GstFlowReturn ret = GST_FLOW_OK;
2144 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2145 AtomInfo *ainfo = (AtomInfo *) walk->data;
2149 if (!ainfo->copy_data_func (ainfo->atom,
2150 send ? &data : NULL, &size, &loffset))
2151 goto serialize_error;
2156 GST_DEBUG_OBJECT (qtmux,
2157 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2158 GST_FOURCC_ARGS (ainfo->atom->type));
2159 buf = _gst_buffer_new_take_data (data, loffset);
2160 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2161 if (ret != GST_FLOW_OK)
2174 return GST_FLOW_ERROR;
2179 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2181 gboolean seekable = FALSE;
2182 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2184 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2185 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2186 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2188 /* have to assume seeking is not supported if query not handled downstream */
2189 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2192 gst_query_unref (query);
2198 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2201 gboolean fail = FALSE;
2202 AtomFTYP *ftyp = NULL;
2203 GstBuffer *prefix = NULL;
2205 GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2206 qtmux->moov_recov_file_path);
2208 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2209 if (qtmux->moov_recov_file == NULL) {
2210 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2211 qtmux->moov_recov_file_path);
2215 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2217 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2218 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2219 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2223 atom_ftyp_free (ftyp);
2225 gst_buffer_unref (prefix);
2227 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2228 GstCollectData *cdata = (GstCollectData *) walk->data;
2229 GstQTPad *qpad = (GstQTPad *) cdata;
2230 /* write info for each stream */
2231 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2233 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2243 fclose (qtmux->moov_recov_file);
2244 qtmux->moov_recov_file = NULL;
2248 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2250 switch (qpad->fourcc) {
2257 return qpad->sample_offset;
2260 return gst_util_uint64_scale_ceil (qpad->sample_offset,
2261 qpad->expected_sample_duration_n,
2262 qpad->expected_sample_duration_d *
2263 atom_trak_get_timescale (qpad->trak));
2270 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2272 switch (qpad->fourcc) {
2274 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2276 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2278 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2280 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2287 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2289 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2291 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2293 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2300 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2302 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2304 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2306 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2313 if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2315 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2317 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2319 } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2328 guint64 next_sample_offset;
2330 block_idx = prefill_get_block_index (qtmux, qpad);
2331 next_sample_offset =
2332 gst_util_uint64_scale (block_idx + 1,
2333 qpad->expected_sample_duration_d *
2334 atom_trak_get_timescale (qpad->trak),
2335 qpad->expected_sample_duration_n);
2337 return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2342 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2350 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2352 switch (qpad->fourcc) {
2359 return gst_util_uint64_scale (qpad->sample_offset + 1,
2360 qpad->expected_sample_duration_d * GST_SECOND,
2361 qpad->expected_sample_duration_n);
2365 guint64 next_sample_offset;
2367 block_idx = prefill_get_block_index (qtmux, qpad);
2368 next_sample_offset =
2369 gst_util_uint64_scale (block_idx + 1,
2370 qpad->expected_sample_duration_d *
2371 atom_trak_get_timescale (qpad->trak),
2372 qpad->expected_sample_duration_n);
2374 return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2375 atom_trak_get_timescale (qpad->trak));
2378 GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2386 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2391 GstClockTime input_timestamp;
2392 guint64 input_timestamp_distance;
2395 gst_adapter_push (qtpad->raw_audio_adapter, buf);
2397 block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2398 qtpad->expected_sample_duration_n,
2399 qtpad->expected_sample_duration_d *
2400 atom_trak_get_timescale (qtpad->trak));
2402 gst_util_uint64_scale (block_idx + 1,
2403 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2404 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2406 if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2407 GST_COLLECT_PADS_STATE_EOS)
2408 && gst_adapter_available (qtpad->raw_audio_adapter) <
2409 nsamples * qtpad->sample_size)
2410 || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2415 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2416 &input_timestamp_distance);
2417 if (input_timestamp != GST_CLOCK_TIME_NONE)
2419 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2420 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2423 gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2424 !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2425 GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2426 qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2427 GST_BUFFER_PTS (buf) = input_timestamp;
2428 GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2429 GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2431 qtpad->raw_audio_adapter_offset += nsamples;
2433 /* Check if we have yet another block of raw audio in the adapter */
2435 gst_util_uint64_scale (block_idx + 2,
2436 qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2437 qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2438 if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2439 nsamples * qtpad->sample_size) {
2441 gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2442 &input_timestamp_distance);
2443 if (input_timestamp != GST_CLOCK_TIME_NONE)
2445 gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2446 qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2447 qtpad->raw_audio_adapter_pts = input_timestamp;
2449 qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2456 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2458 switch (qpad->fourcc) {
2465 guint sample_size = prefill_get_sample_size (qtmux, qpad);
2466 atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2473 /* Find the (first) video track and assume that we have to output
2475 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2476 GstCollectData *cdata = (GstCollectData *) walk->data;
2477 GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2479 if (tmp_qpad->trak->is_video) {
2480 qpad->expected_sample_duration_n =
2481 tmp_qpad->expected_sample_duration_n;
2482 qpad->expected_sample_duration_d =
2483 tmp_qpad->expected_sample_duration_d;
2489 GST_INFO_OBJECT (qpad->collect.pad,
2490 "Found no video framerate, using 40ms audio buffers");
2491 qpad->expected_sample_duration_n = 25;
2492 qpad->expected_sample_duration_d = 1;
2495 /* Set a prepare_buf_func that ensures this */
2496 qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2497 qpad->raw_audio_adapter = gst_adapter_new ();
2498 qpad->raw_audio_adapter_offset = 0;
2499 qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2509 find_best_pad_prefill (GstQTMux * qtmux)
2512 GstQTPad *best_pad = NULL;
2514 if (qtmux->current_pad &&
2515 (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2516 (qtmux->interleave_bytes == 0
2517 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2518 && (qtmux->interleave_time == 0
2519 || qtmux->current_chunk_duration <= qtmux->interleave_time)
2520 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2521 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2523 if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2524 best_pad = qtmux->current_pad;
2526 } else if (qtmux->collect->data->next) {
2527 best_pad = qtmux->current_pad = NULL;
2531 GstClockTime best_time = GST_CLOCK_TIME_NONE;
2533 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2534 GstCollectData *cdata = (GstCollectData *) walk->data;
2535 GstQTPad *qtpad = (GstQTPad *) cdata;
2536 GstClockTime timestamp;
2538 if (qtpad->total_duration >= qtmux->reserved_max_duration)
2541 timestamp = qtpad->total_duration;
2543 if (best_pad == NULL ||
2544 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2546 best_time = timestamp;
2555 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2559 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2561 /* Update expected sample sizes/durations as needed, this is for raw
2562 * audio where samples are actual audio samples. */
2563 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2564 GstCollectData *cdata = (GstCollectData *) walk->data;
2565 GstQTPad *qpad = (GstQTPad *) cdata;
2567 if (!prefill_update_sample_size (qtmux, qpad))
2571 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2572 /* For the first sample check/update timecode as needed. We do that before
2573 * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2574 * initial buffer directly, not with last_buf */
2575 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2576 GstCollectData *cdata = (GstCollectData *) walk->data;
2577 GstQTPad *qpad = (GstQTPad *) cdata;
2579 gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2580 GstVideoTimeCodeMeta *tc_meta;
2582 if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
2583 GstVideoTimeCode *tc = &tc_meta->tc;
2585 qpad->tc_trak = atom_trak_new (qtmux->context);
2586 atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2588 qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2589 atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2591 atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2592 qpad->trak->mdia.mdhd.time_info.timescale, tc);
2594 atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2595 qtmux->mdat_size, FALSE, 0);
2597 qpad->tc_pos = qtmux->mdat_size;
2598 qpad->first_tc = gst_video_time_code_copy (tc);
2599 qpad->first_pts = GST_BUFFER_PTS (buffer);
2601 qtmux->current_chunk_offset = -1;
2602 qtmux->current_chunk_size = 0;
2603 qtmux->current_chunk_duration = 0;
2604 qtmux->mdat_size += 4;
2607 gst_buffer_unref (buffer);
2611 while ((qpad = find_best_pad_prefill (qtmux))) {
2612 GstClockTime timestamp, next_timestamp, duration;
2613 guint nsamples, sample_size;
2614 guint64 chunk_offset;
2615 gint64 scaled_duration;
2616 gint64 pts_offset = 0;
2617 gboolean sync = FALSE;
2618 TrakBufferEntryInfo sample_entry;
2620 sample_size = prefill_get_sample_size (qtmux, qpad);
2622 if (sample_size == -1) {
2627 qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2629 timestamp = qpad->total_duration;
2630 next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2631 duration = next_timestamp - timestamp;
2633 if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2634 qpad->first_ts = timestamp;
2635 if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2636 qpad->first_dts = timestamp;
2638 if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2639 qtmux->current_pad = qpad;
2640 if (qtmux->current_chunk_offset == -1)
2641 qtmux->current_chunk_offset = qtmux->mdat_size;
2643 qtmux->current_chunk_offset += qtmux->current_chunk_size;
2644 qtmux->current_chunk_size = 0;
2645 qtmux->current_chunk_duration = 0;
2647 if (qpad->sample_size)
2648 nsamples = sample_size / qpad->sample_size;
2651 qpad->last_dts = timestamp;
2652 scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2653 atom_trak_get_timescale (qpad->trak),
2654 GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2655 atom_trak_get_timescale (qpad->trak), GST_SECOND);
2657 qtmux->current_chunk_size += sample_size;
2658 qtmux->current_chunk_duration += duration;
2659 qpad->total_bytes += sample_size;
2661 chunk_offset = qtmux->current_chunk_offset;
2663 /* I-frame only, no frame reordering */
2667 if (qtmux->current_chunk_duration > qtmux->longest_chunk
2668 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2669 qtmux->longest_chunk = qtmux->current_chunk_duration;
2672 sample_entry.track_id = qpad->trak->tkhd.track_ID;
2673 sample_entry.nsamples = nsamples;
2674 sample_entry.delta = scaled_duration / nsamples;
2675 sample_entry.size = sample_size / nsamples;
2676 sample_entry.chunk_offset = chunk_offset;
2677 sample_entry.pts_offset = pts_offset;
2678 sample_entry.sync = sync;
2679 sample_entry.do_pts = TRUE;
2680 g_array_append_val (qpad->samples, sample_entry);
2681 atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2682 sample_size / nsamples, chunk_offset, sync, pts_offset);
2684 qpad->total_duration = next_timestamp;
2685 qtmux->mdat_size += sample_size;
2686 qpad->sample_offset += nsamples;
2692 static GstFlowReturn
2693 gst_qt_mux_start_file (GstQTMux * qtmux)
2695 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2696 GstFlowReturn ret = GST_FLOW_OK;
2700 GstClockTime reserved_max_duration;
2701 guint reserved_bytes_per_sec_per_trak;
2704 GST_DEBUG_OBJECT (qtmux, "starting file");
2706 GST_OBJECT_LOCK (qtmux);
2707 reserved_max_duration = qtmux->reserved_max_duration;
2708 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2709 GST_OBJECT_UNLOCK (qtmux);
2711 /* stream-start (FIXME: create id based on input ids) */
2712 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2713 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2715 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2716 /* qtmux has structure with and without variant, remove all but the first */
2717 while (gst_caps_get_size (caps) > 1)
2718 gst_caps_remove_structure (caps, 1);
2719 gst_pad_set_caps (qtmux->srcpad, caps);
2720 gst_caps_unref (caps);
2722 /* Default is 'normal' mode */
2723 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2725 /* Require a sensible fragment duration when muxing
2726 * using the ISML muxer */
2727 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2728 qtmux->fragment_duration == 0)
2731 if (qtmux->fragment_duration > 0) {
2732 if (qtmux->streamable)
2733 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2735 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2736 } else if (qtmux->fast_start) {
2737 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2738 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2739 if (qtmux->reserved_prefill)
2740 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2742 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2745 switch (qtmux->mux_mode) {
2746 case GST_QT_MUX_MODE_MOOV_AT_END:
2747 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2748 /* We have to be able to seek to rewrite the mdat header, or any
2749 * moov atom we write will not be visible in the file, because an
2750 * MDAT with 0 as the size covers the rest of the file. A file
2751 * with no moov is not playable, so error out now. */
2752 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2753 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2754 ("Downstream is not seekable - will not be able to create a playable file"),
2756 return GST_FLOW_ERROR;
2759 case GST_QT_MUX_MODE_FAST_START:
2760 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2761 break; /* Don't need seekability, ignore */
2762 case GST_QT_MUX_MODE_FRAGMENTED:
2763 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2764 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2765 "streamable=false. Will ignore that and create streamable output "
2767 qtmux->streamable = TRUE;
2768 g_object_notify (G_OBJECT (qtmux), "streamable");
2771 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2772 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2773 GST_WARNING_OBJECT (qtmux,
2774 "downstream is not seekable, will not be able "
2775 "to trim samples table at the end if less than reserved-duration is "
2781 /* let downstream know we think in BYTES and expect to do seeking later on */
2782 gst_segment_init (&segment, GST_FORMAT_BYTES);
2783 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2785 GST_OBJECT_LOCK (qtmux);
2787 if (qtmux->timescale == 0) {
2788 guint32 suggested_timescale = 0;
2791 /* Calculate a reasonable timescale for the moov:
2792 * If there is video, it is the biggest video track timescale or an even
2793 * multiple of it if it's smaller than 1800.
2794 * Otherwise it is 1800 */
2795 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
2796 GstCollectData *cdata = (GstCollectData *) walk->data;
2797 GstQTPad *qpad = (GstQTPad *) cdata;
2803 if (!qpad->trak->mdia.minf.vmhd)
2806 suggested_timescale =
2807 MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
2810 if (suggested_timescale == 0)
2811 suggested_timescale = 1800;
2813 while (suggested_timescale < 1800)
2814 suggested_timescale *= 2;
2816 qtmux->timescale = suggested_timescale;
2819 /* initialize our moov recovery file */
2820 if (qtmux->moov_recov_file_path) {
2821 gst_qt_mux_prepare_moov_recovery (qtmux);
2824 /* Make sure the first time we update the moov, we'll
2825 * include any tagsetter tags */
2826 qtmux->tags_changed = TRUE;
2828 GST_OBJECT_UNLOCK (qtmux);
2831 * send mdat header if already needed, and mark position for later update.
2832 * We don't send ftyp now if we are on fast start mode, because we can
2833 * better fine tune using the information we gather to create the whole moov
2836 switch (qtmux->mux_mode) {
2837 case GST_QT_MUX_MODE_MOOV_AT_END:
2838 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2839 if (ret != GST_FLOW_OK)
2842 /* Store this as the mdat offset for later updating
2843 * when we write the moov */
2844 qtmux->mdat_pos = qtmux->header_size;
2845 /* extended atom in case we go over 4GB while writing and need
2846 * the full 64-bit atom */
2848 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2851 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2852 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2853 if (ret != GST_FLOW_OK)
2856 /* Pad ftyp out to an 8-byte boundary before starting the moov
2857 * ping pong region. It should be well less than 1 disk sector,
2858 * unless there's a bajillion compatible types listed,
2859 * but let's be sure the free atom doesn't cross a sector
2860 * boundary anyway */
2861 if (qtmux->header_size % 8) {
2862 /* Extra 8 bytes for the padding free atom header */
2863 guint padding = (guint) (16 - (qtmux->header_size % 8));
2864 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2866 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2868 if (ret != GST_FLOW_OK)
2872 /* Store this as the moov offset for later updating.
2873 * We record mdat position below */
2874 qtmux->moov_pos = qtmux->header_size;
2876 /* Set up the initial 'ping' state of the ping-pong buffers */
2877 qtmux->reserved_moov_first_active = TRUE;
2879 gst_qt_mux_configure_moov (qtmux);
2880 gst_qt_mux_setup_metadata (qtmux);
2881 /* Empty free atom to begin, starting on an 8-byte boundary */
2882 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2883 if (ret != GST_FLOW_OK)
2885 /* Moov header, not padded yet */
2886 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2887 if (ret != GST_FLOW_OK)
2889 /* The moov we just sent contains the 'base' size of the moov, before
2890 * we put in any time-dependent per-trak data. Use that to make
2891 * a good estimate of how much extra to reserve */
2892 /* Calculate how much space to reserve for our MOOV atom.
2893 * We actually reserve twice that, for ping-pong buffers */
2894 qtmux->base_moov_size = qtmux->last_moov_size;
2895 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2896 qtmux->base_moov_size);
2897 qtmux->reserved_moov_size = qtmux->base_moov_size +
2898 gst_util_uint64_scale (reserved_max_duration,
2899 reserved_bytes_per_sec_per_trak *
2900 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2902 /* Need space for at least 4 atom headers. More really, but
2903 * this as an absolute minimum */
2904 if (qtmux->reserved_moov_size < 4 * 8)
2905 goto reserved_moov_too_small;
2907 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2908 2 * qtmux->reserved_moov_size + 16);
2910 GST_OBJECT_LOCK (qtmux);
2911 qtmux->reserved_duration_remaining =
2912 gst_util_uint64_scale (qtmux->reserved_moov_size -
2913 qtmux->base_moov_size, GST_SECOND,
2914 reserved_bytes_per_sec_per_trak *
2915 atom_moov_get_trak_count (qtmux->moov));
2916 GST_OBJECT_UNLOCK (qtmux);
2918 /* Now that we know how much reserved space is targetted,
2919 * output a free atom to fill the extra reserved */
2920 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2921 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2922 if (ret != GST_FLOW_OK)
2925 /* Then a free atom containing 'pong' buffer, with an
2926 * extra 8 bytes to account for the free atom header itself */
2927 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2928 qtmux->reserved_moov_size + 8, FALSE);
2929 if (ret != GST_FLOW_OK)
2932 /* extra atoms go after the free/moov(s), before the mdat */
2934 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2935 if (ret != GST_FLOW_OK)
2938 qtmux->mdat_pos = qtmux->header_size;
2939 /* extended atom in case we go over 4GB while writing and need
2940 * the full 64-bit atom */
2942 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2945 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2946 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2947 if (ret != GST_FLOW_OK)
2950 /* Store this as the moov offset for later updating.
2951 * We record mdat position below */
2952 qtmux->moov_pos = qtmux->header_size;
2954 if (!gst_qt_mux_prefill_samples (qtmux)) {
2955 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2956 ("Unsupported codecs or configuration for prefill mode"), (NULL));
2958 return GST_FLOW_ERROR;
2961 gst_qt_mux_update_global_statistics (qtmux);
2962 gst_qt_mux_configure_moov (qtmux);
2963 gst_qt_mux_update_edit_lists (qtmux);
2964 gst_qt_mux_setup_metadata (qtmux);
2966 /* Moov header with pre-filled samples */
2967 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2968 if (ret != GST_FLOW_OK)
2971 /* last_moov_size now contains the full size of the moov, moov_pos the
2972 * position. This allows us to rewrite it in the very end as needed */
2973 qtmux->reserved_moov_size =
2974 qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
2976 /* Send an additional free atom at the end so we definitely have space
2977 * to rewrite the moov header at the end and remove the samples that
2978 * were not actually written */
2980 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2981 12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
2982 if (ret != GST_FLOW_OK)
2985 /* extra atoms go after the free/moov(s), before the mdat */
2987 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2988 if (ret != GST_FLOW_OK)
2991 qtmux->mdat_pos = qtmux->header_size;
2993 /* And now send the mdat header */
2995 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
2996 qtmux->mdat_size, TRUE, FALSE);
2998 /* chunks position is set relative to the first byte of the
2999 * MDAT atom payload. Set the overall offset into the file */
3000 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3005 gst_segment_init (&segment, GST_FORMAT_BYTES);
3006 segment.start = qtmux->moov_pos;
3007 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3009 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3010 if (ret != GST_FLOW_OK)
3013 segment.start = qtmux->header_size;
3014 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3017 qtmux->current_chunk_size = 0;
3018 qtmux->current_chunk_duration = 0;
3019 qtmux->current_chunk_offset = -1;
3020 qtmux->mdat_size = 0;
3021 qtmux->current_pad = NULL;
3022 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3024 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3025 GstCollectData *cdata = (GstCollectData *) walk->data;
3026 GstQTPad *qtpad = (GstQTPad *) cdata;
3028 qtpad->total_bytes = 0;
3029 qtpad->total_duration = 0;
3030 qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3031 qtpad->last_dts = GST_CLOCK_TIME_NONE;
3032 qtpad->sample_offset = 0;
3036 case GST_QT_MUX_MODE_FAST_START:
3037 GST_OBJECT_LOCK (qtmux);
3038 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3039 if (!qtmux->fast_start_file)
3041 GST_OBJECT_UNLOCK (qtmux);
3042 /* send a dummy buffer for preroll */
3043 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3045 case GST_QT_MUX_MODE_FRAGMENTED:
3046 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3047 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3048 if (ret != GST_FLOW_OK)
3050 /* store the moov pos so we can update the duration later
3051 * in non-streamable mode */
3052 qtmux->moov_pos = qtmux->header_size;
3054 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3055 qtmux->fragment_duration);
3056 /* also used as snapshot marker to indicate fragmented file */
3057 qtmux->fragment_sequence = 1;
3058 /* prepare moov and/or tags */
3059 gst_qt_mux_configure_moov (qtmux);
3060 gst_qt_mux_setup_metadata (qtmux);
3061 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3062 if (ret != GST_FLOW_OK)
3066 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3067 if (ret != GST_FLOW_OK)
3069 /* prepare index if not streamable */
3070 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3071 qtmux->mfra = atom_mfra_new (qtmux->context);
3079 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3080 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3081 return GST_FLOW_ERROR;
3083 reserved_moov_too_small:
3085 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3086 ("Not enough reserved space for creating headers"), (NULL));
3087 return GST_FLOW_ERROR;
3091 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3092 (("Could not open temporary file \"%s\""),
3093 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3094 GST_OBJECT_UNLOCK (qtmux);
3095 return GST_FLOW_ERROR;
3099 static GstFlowReturn
3100 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3102 GstFlowReturn ret = GST_FLOW_OK;
3105 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3106 GstCollectData *cdata = (GstCollectData *) walk->data;
3107 GstQTPad *qtpad = (GstQTPad *) cdata;
3109 /* avoid add_buffer complaining if not negotiated
3110 * in which case no buffers either, so skipping */
3111 if (!qtpad->fourcc) {
3112 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3113 GST_PAD_NAME (qtpad->collect.pad));
3117 /* send last buffer; also flushes possibly queued buffers/ts */
3118 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3119 GST_PAD_NAME (qtpad->collect.pad));
3120 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3121 if (ret != GST_FLOW_OK) {
3122 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3123 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3124 gst_flow_get_name (ret));
3132 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3136 /* for setting some subtitles fields */
3137 guint max_width = 0;
3138 guint max_height = 0;
3140 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3142 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3143 GstCollectData *cdata = (GstCollectData *) walk->data;
3144 GstQTPad *qtpad = (GstQTPad *) cdata;
3146 if (!qtpad->fourcc) {
3147 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3148 GST_PAD_NAME (qtpad->collect.pad));
3152 /* having flushed above, can check for buffers now */
3153 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3154 GstClockTime first_pts_in = qtpad->first_ts;
3155 /* it should be, since we got first_ts by adding adjustment
3156 * to a positive incoming PTS */
3157 if (qtpad->dts_adjustment <= first_pts_in)
3158 first_pts_in -= qtpad->dts_adjustment;
3159 /* determine max stream duration */
3160 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3161 || qtpad->last_dts > qtmux->last_dts) {
3162 qtmux->last_dts = qtpad->last_dts;
3164 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3165 || first_pts_in < qtmux->first_ts) {
3166 /* we need the original incoming PTS here, as this first_ts
3167 * is used in update_edit_lists to construct the edit list that arrange
3168 * for sync'ed streams. The first_ts is most likely obtained from
3169 * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3170 * so it makes no difference, though it matters in other cases */
3171 qtmux->first_ts = first_pts_in;
3175 /* subtitles need to know the video width/height,
3176 * it is stored shifted 16 bits to the left according to the
3178 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3179 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3181 /* update average bitrate of streams if needed */
3183 guint32 avgbitrate = 0;
3184 guint32 maxbitrate = qtpad->max_bitrate;
3186 if (qtpad->avg_bitrate)
3187 avgbitrate = qtpad->avg_bitrate;
3188 else if (qtpad->total_duration > 0)
3189 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3190 8 * GST_SECOND, qtpad->total_duration);
3192 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3196 /* need to update values on subtitle traks now that we know the
3197 * max width and height */
3198 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3199 GstCollectData *cdata = (GstCollectData *) walk->data;
3200 GstQTPad *qtpad = (GstQTPad *) cdata;
3202 if (!qtpad->fourcc) {
3203 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3204 GST_PAD_NAME (qtpad->collect.pad));
3208 if (qtpad->fourcc == FOURCC_tx3g) {
3209 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3214 /* Called after gst_qt_mux_update_global_statistics() updates the
3215 * first_ts tracking, to create/set edit lists for delayed streams */
3217 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3221 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3222 GST_TIME_ARGS (qtmux->first_ts));
3223 /* add/update EDTSs for late streams. configure_moov will have
3224 * set the trak durations above by summing the sample tables,
3225 * here we extend that if needing to insert an empty segment */
3226 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3227 GstCollectData *cdata = (GstCollectData *) walk->data;
3228 GstQTPad *qtpad = (GstQTPad *) cdata;
3230 atom_trak_edts_clear (qtpad->trak);
3232 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3233 guint32 lateness = 0;
3234 guint32 duration = qtpad->trak->tkhd.duration;
3237 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3242 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3243 lateness = gst_util_uint64_scale_round (diff,
3244 qtmux->timescale, GST_SECOND);
3247 GST_DEBUG_OBJECT (qtmux,
3248 "Pad %s is a late stream by %" GST_TIME_FORMAT,
3249 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3251 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3252 (guint32) (1 * 65536.0));
3256 /* Always write an edit list for the whole track. In general this is not
3257 * necessary except for the case of having a gap or DTS adjustment but
3258 * it allows to give the whole track's duration in the usually more
3259 * accurate media timescale
3262 GstClockTime ctts = 0;
3263 guint32 media_start;
3265 if (qtpad->first_ts > qtpad->first_dts)
3266 ctts = qtpad->first_ts - qtpad->first_dts;
3268 media_start = gst_util_uint64_scale_round (ctts,
3269 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3271 /* atom_trak_set_elst_entry() has a quirk - if the edit list
3272 * is empty because there's no gap added above, this call
3273 * will not replace index 1, it will create the entry at index 0.
3274 * Luckily, that's exactly what we want here */
3275 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3276 (guint32) (1 * 65536.0));
3279 /* need to add the empty time to the trak duration */
3280 duration += lateness;
3281 qtpad->trak->tkhd.duration = duration;
3282 if (qtpad->tc_trak) {
3283 qtpad->tc_trak->tkhd.duration = duration;
3284 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3287 /* And possibly grow the moov duration */
3288 if (duration > qtmux->moov->mvhd.time_info.duration) {
3289 qtmux->moov->mvhd.time_info.duration = duration;
3290 qtmux->moov->mvex.mehd.fragment_duration = duration;
3296 static GstFlowReturn
3297 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3302 guint64 offset = qtpad->tc_pos;
3303 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3305 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3308 g_assert (qtpad->tc_pos != -1);
3310 gst_segment_init (&segment, GST_FORMAT_BYTES);
3311 segment.start = offset;
3312 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3314 buf = gst_buffer_new_and_alloc (4);
3315 gst_buffer_map (buf, &map, GST_MAP_WRITE);
3317 GST_WRITE_UINT32_BE (map.data,
3318 gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3319 gst_buffer_unmap (buf, &map);
3321 /* Reset this value, so the timecode won't be re-rewritten */
3324 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3327 static GstFlowReturn
3328 gst_qt_mux_stop_file (GstQTMux * qtmux)
3330 gboolean ret = GST_FLOW_OK;
3331 guint64 offset = 0, size = 0;
3332 gboolean large_file;
3335 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3337 /* pushing last buffers for each pad */
3338 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3341 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3342 /* Streamable mode; no need to write duration or MFRA */
3343 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3347 gst_qt_mux_update_global_statistics (qtmux);
3348 for (walk = qtmux->collect->data; walk; walk = walk->next) {
3349 GstQTPad *qtpad = (GstQTPad *) walk->data;
3351 if (qtpad->tc_pos != -1) {
3352 /* File is being stopped and timecode hasn't been updated. Update it now
3353 * with whatever we have */
3354 ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3355 if (ret != GST_FLOW_OK)
3360 switch (qtmux->mux_mode) {
3361 case GST_QT_MUX_MODE_FRAGMENTED:{
3363 guint8 *data = NULL;
3367 GST_DEBUG_OBJECT (qtmux, "adding mfra");
3368 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3369 goto serialize_error;
3370 buf = _gst_buffer_new_take_data (data, offset);
3371 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3372 if (ret != GST_FLOW_OK)
3375 /* only mvex duration is updated,
3376 * mvhd should be consistent with empty moov
3377 * (but TODO maybe some clients do not handle that well ?) */
3378 qtmux->moov->mvex.mehd.fragment_duration =
3379 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
3380 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
3381 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
3382 /* seek and rewrite the header */
3383 gst_segment_init (&segment, GST_FORMAT_BYTES);
3384 segment.start = qtmux->moov_pos;
3385 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3386 /* no need to seek back */
3387 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3389 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3390 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3391 if (G_UNLIKELY (ret != GST_FLOW_OK))
3393 /* Finalise by writing the final size into the mdat. Up until now
3394 * it's been 0, which means 'rest of the file'
3395 * No need to seek back after this, we won't write any more */
3396 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3397 qtmux->mdat_size, NULL, TRUE);
3399 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3401 guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3403 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3404 GstCollectData *cdata = (GstCollectData *) walk->data;
3405 GstQTPad *qpad = (GstQTPad *) cdata;
3406 const TrakBufferEntryInfo *sample_entry;
3408 AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3410 /* Get the block index of the last sample we wrote, not of the next
3411 * sample we would write */
3412 block_idx = prefill_get_block_index (qtmux, qpad);
3413 g_assert (block_idx > 0);
3417 &g_array_index (qpad->samples, TrakBufferEntryInfo, block_idx);
3422 guint64 nsamples = 0;
3425 n = atom_array_get_len (&stbl->stts.entries);
3426 for (i = 0; i < n; i++) {
3427 entry = &atom_array_index (&stbl->stts.entries, i);
3428 if (nsamples + entry->sample_count >= qpad->sample_offset) {
3429 entry->sample_count = qpad->sample_offset - nsamples;
3430 stbl->stts.entries.len = i + 1;
3433 nsamples += entry->sample_count;
3440 g_assert (stbl->stsz.entries.len == 0);
3441 stbl->stsz.table_size = qpad->sample_offset;
3447 guint64 nsamples = 0;
3448 gint chunk_index = 0;
3450 n = stbl->stco64.entries.len;
3451 for (i = 0; i < n; i++) {
3452 guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3454 if (*entry == sample_entry->chunk_offset) {
3455 stbl->stco64.entries.len = i + 1;
3456 chunk_index = i + 1;
3461 g_assert (chunk_index > 0);
3463 n = stbl->stsc.entries.len;
3464 for (i = 0; i < n; i++) {
3465 STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3467 if (entry->first_chunk >= chunk_index)
3472 (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3474 1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3475 i - 1).samples_per_chunk;
3481 STSCEntry *prev_entry =
3482 &atom_array_index (&stbl->stsc.entries, i - 1);
3485 prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3486 if (qpad->sample_offset - nsamples > 0) {
3487 stbl->stsc.entries.len = i;
3488 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3489 qpad->sample_offset - nsamples);
3491 stbl->stsc.entries.len = i;
3492 stbl->stco64.entries.len--;
3495 /* Everything in a single chunk */
3496 stbl->stsc.entries.len = 0;
3497 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3498 qpad->sample_offset);
3505 for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3506 AtomTREX *trex = walk2->data;
3508 if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3509 trex->track_ID = next_track_id;
3514 qpad->trak->tkhd.track_ID = next_track_id++;
3517 qtmux->moov->mvhd.next_track_id = next_track_id;
3519 gst_qt_mux_update_global_statistics (qtmux);
3520 gst_qt_mux_configure_moov (qtmux);
3522 gst_qt_mux_update_edit_lists (qtmux);
3524 /* Check if any gap edit lists were added. We don't have any space
3525 * reserved for this in the moov and the pre-finalized moov would have
3526 * broken A/V synchronization. Error out here now
3528 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3529 GstCollectData *cdata = (GstCollectData *) walk->data;
3530 GstQTPad *qpad = (GstQTPad *) cdata;
3532 if (qpad->trak->edts
3533 && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3534 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3535 ("Can't support gaps in prefill mode"));
3537 return GST_FLOW_ERROR;
3541 gst_qt_mux_setup_metadata (qtmux);
3542 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3547 gst_segment_init (&segment, GST_FORMAT_BYTES);
3548 segment.start = qtmux->moov_pos;
3549 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3552 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3554 if (ret != GST_FLOW_OK)
3557 if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3559 gst_qt_mux_send_free_atom (qtmux, NULL,
3560 qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3563 if (ret != GST_FLOW_OK)
3567 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3568 qtmux->mdat_size, NULL, FALSE);
3575 /* Moov-at-end or fast-start mode from here down */
3576 gst_qt_mux_configure_moov (qtmux);
3578 gst_qt_mux_update_edit_lists (qtmux);
3580 /* tags into file metadata */
3581 gst_qt_mux_setup_metadata (qtmux);
3583 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3585 switch (qtmux->mux_mode) {
3586 case GST_QT_MUX_MODE_FAST_START:{
3587 /* if faststart, update the offset of the atoms in the movie with the offset
3588 * that the movie headers before mdat will cause.
3589 * Also, send the ftyp */
3592 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3593 if (ret != GST_FLOW_OK) {
3596 /* copy into NULL to obtain size */
3597 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3598 goto serialize_error;
3599 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3601 offset += qtmux->header_size + (large_file ? 16 : 8);
3603 /* sum up with the extra atoms size */
3604 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3605 if (ret != GST_FLOW_OK)
3610 offset = qtmux->header_size;
3614 /* Now that we know the size of moov + extra atoms, we can adjust
3615 * the chunk offsets stored into the moov */
3616 atom_moov_chunks_set_offset (qtmux->moov, offset);
3618 /* write out moov and extra atoms */
3619 /* note: as of this point, we no longer care about tracking written data size,
3620 * since there is no more use for it anyway */
3621 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3622 if (ret != GST_FLOW_OK)
3626 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3627 if (ret != GST_FLOW_OK)
3630 switch (qtmux->mux_mode) {
3631 case GST_QT_MUX_MODE_MOOV_AT_END:
3633 /* mdat needs update iff not using faststart */
3634 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3635 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3636 qtmux->mdat_size, NULL, FALSE);
3637 /* note; no seeking back to the end of file is done,
3638 * since we no longer write anything anyway */
3641 case GST_QT_MUX_MODE_FAST_START:
3643 /* send mdat atom and move buffered data into it */
3644 /* mdat_size = accumulated (buffered data) */
3645 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3647 if (ret != GST_FLOW_OK)
3649 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3650 if (ret != GST_FLOW_OK)
3655 g_assert_not_reached ();
3663 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3664 ("Failed to serialize moov"));
3665 return GST_FLOW_ERROR;
3669 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3670 return GST_FLOW_ERROR;
3674 static GstFlowReturn
3675 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3676 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3677 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3679 GstFlowReturn ret = GST_FLOW_OK;
3681 /* setup if needed */
3682 if (G_UNLIKELY (!pad->traf || force))
3686 /* flush pad fragment if threshold reached,
3687 * or at new keyframe if we should be minding those in the first place */
3688 if (G_UNLIKELY (force || (sync && pad->sync) ||
3689 pad->fragment_duration < (gint64) delta)) {
3691 guint64 size = 0, offset = 0;
3692 guint8 *data = NULL;
3694 guint i, total_size;
3696 /* now we know where moof ends up, update offset in tfra */
3698 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3700 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3701 /* takes ownership */
3702 atom_moof_add_traf (moof, pad->traf);
3704 atom_moof_copy_data (moof, &data, &size, &offset);
3705 buffer = _gst_buffer_new_take_data (data, offset);
3706 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3707 gst_buffer_get_size (buffer));
3708 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3710 /* and actual data */
3712 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3714 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3717 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
3718 atom_array_get_len (&pad->fragment_buffers), total_size);
3719 if (ret == GST_FLOW_OK)
3720 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
3722 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3723 if (G_LIKELY (ret == GST_FLOW_OK))
3724 ret = gst_qt_mux_send_buffer (qtmux,
3725 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
3728 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
3731 atom_array_clear (&pad->fragment_buffers);
3732 atom_moof_free (moof);
3733 qtmux->fragment_sequence++;
3738 if (G_UNLIKELY (!pad->traf)) {
3739 GST_LOG_OBJECT (qtmux, "setting up new fragment");
3740 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
3741 atom_array_init (&pad->fragment_buffers, 512);
3742 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
3743 atom_trak_get_timescale (pad->trak), 1000);
3745 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
3746 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
3747 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
3749 atom_traf_set_base_decode_time (pad->traf, dts);
3752 /* add buffer and metadata */
3753 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
3755 atom_array_append (&pad->fragment_buffers, buf, 256);
3756 pad->fragment_duration -= delta;
3759 guint32 sn = atom_traf_get_sample_num (pad->traf);
3761 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
3762 atom_tfra_add_entry (pad->tfra, dts, sn);
3765 if (G_UNLIKELY (force))
3771 /* Here's the clever bit of robust recording: Updating the moov
3772 * header is done using a ping-pong scheme inside 2 blocks of size
3773 * 'reserved_moov_size' at the start of the file, in such a way that the
3774 * file on-disk is always valid if interrupted.
3775 * Inside the reserved space, we have 2 pairs of free + moov atoms
3776 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
3777 * at offset "reserved_moov_size".
3779 * 1. Free-A has 0 size payload, moov-A immediately after is
3780 * active/current, and is padded with an internal Free atom to
3781 * end at reserved_space/2. Free-B is at reserved_space/2, sized
3782 * to cover the remaining free space (including moov-B).
3783 * 2. We write moov-B (which is invisible inside free-B), and pad it to
3784 * end at the end of free space. Then, we update free-A to size
3785 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
3786 * free-B header, and makes moov-B active.
3787 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
3788 * Change the size of free-A to make moov-A active again.
3789 * 4. Rinse and repeat.
3792 static GstFlowReturn
3793 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
3797 guint64 freeA_offset;
3798 guint32 new_freeA_size;
3799 guint64 new_moov_offset;
3801 /* Update moov info, then seek and rewrite the MOOV atom */
3802 gst_qt_mux_update_global_statistics (qtmux);
3803 gst_qt_mux_configure_moov (qtmux);
3805 gst_qt_mux_update_edit_lists (qtmux);
3807 /* tags into file metadata */
3808 gst_qt_mux_setup_metadata (qtmux);
3810 /* chunks position is set relative to the first byte of the
3811 * MDAT atom payload. Set the overall offset into the file */
3812 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3814 /* Calculate which moov to rewrite. qtmux->moov_pos points to
3815 * the start of the free-A header */
3816 freeA_offset = qtmux->moov_pos;
3817 if (qtmux->reserved_moov_first_active) {
3818 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
3819 /* After this, freeA will include itself, moovA, plus the freeB
3821 new_freeA_size = qtmux->reserved_moov_size + 16;
3823 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
3826 /* the moov we update is after free-A, calculate its offset */
3827 new_moov_offset = freeA_offset + new_freeA_size;
3829 /* Swap ping-pong cadence marker */
3830 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
3832 /* seek and rewrite the MOOV atom */
3833 gst_segment_init (&segment, GST_FORMAT_BYTES);
3834 segment.start = new_moov_offset;
3835 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3838 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3840 if (ret != GST_FLOW_OK)
3843 /* Update the estimated recording space remaining, based on amount used so
3844 * far and duration muxed so far */
3845 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
3846 GstClockTime remain;
3847 GstClockTime time_muxed = qtmux->last_dts;
3850 gst_util_uint64_scale (qtmux->reserved_moov_size -
3851 qtmux->last_moov_size, time_muxed,
3852 qtmux->last_moov_size - qtmux->base_moov_size);
3853 /* Always under-estimate slightly, so users
3854 * have time to stop muxing before we run out */
3855 if (remain < GST_SECOND / 2)
3858 remain -= GST_SECOND / 2;
3860 GST_INFO_OBJECT (qtmux,
3861 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
3862 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
3863 qtmux->reserved_moov_size, qtmux->last_moov_size,
3864 GST_TIME_ARGS (qtmux->last_dts),
3865 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
3867 GST_OBJECT_LOCK (qtmux);
3868 qtmux->reserved_duration_remaining = remain;
3869 qtmux->muxed_since_last_update = 0;
3870 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
3871 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
3872 GST_OBJECT_UNLOCK (qtmux);
3876 /* Now update the moov-A size. Don't pass offset, since we don't need
3877 * send_free_atom() to seek for us - all our callers seek back to
3878 * where they need after this, or they don't need it */
3879 gst_segment_init (&segment, GST_FORMAT_BYTES);
3880 segment.start = freeA_offset;
3881 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3883 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
3888 static GstFlowReturn
3889 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
3892 GstFlowReturn flow_ret;
3894 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
3896 GST_OBJECT_LOCK (qtmux);
3898 /* Update the offset of how much we've muxed, so the
3899 * report of remaining space keeps counting down */
3900 if (position > qtmux->last_moov_update &&
3901 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
3902 GST_LOG_OBJECT (qtmux,
3903 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
3904 qtmux->muxed_since_last_update);
3905 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
3908 /* Next, check if we're supposed to send periodic moov updates downstream */
3909 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
3910 GST_OBJECT_UNLOCK (qtmux);
3914 /* Update if position is > the threshold or there's been no update yet */
3915 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
3916 (position <= qtmux->last_moov_update ||
3917 (position - qtmux->last_moov_update) <
3918 qtmux->reserved_moov_update_period)) {
3919 GST_OBJECT_UNLOCK (qtmux);
3920 return GST_FLOW_OK; /* No update needed yet */
3923 qtmux->last_moov_update = position;
3924 GST_OBJECT_UNLOCK (qtmux);
3926 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
3927 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
3928 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
3930 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3931 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
3934 /* Seek back to previous position */
3935 gst_segment_init (&segment, GST_FORMAT_BYTES);
3936 segment.start = mdat_offset;
3937 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3942 static GstFlowReturn
3943 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
3944 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
3945 gint64 last_dts, gint64 scaled_duration, guint sample_size,
3946 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
3948 GstFlowReturn ret = GST_FLOW_OK;
3950 /* note that a new chunk is started each time (not fancy but works) */
3951 if (qtmux->moov_recov_file) {
3952 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
3953 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
3954 do_pts, pts_offset)) {
3955 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
3956 "recovery file, disabling recovery");
3957 fclose (qtmux->moov_recov_file);
3958 qtmux->moov_recov_file = NULL;
3962 switch (qtmux->mux_mode) {
3963 case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3964 const TrakBufferEntryInfo *sample_entry;
3965 guint64 block_idx = prefill_get_block_index (qtmux, pad);
3967 if (block_idx >= pad->samples->len) {
3968 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3969 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
3970 block_idx, pad->samples->len));
3971 gst_buffer_unref (buffer);
3972 return GST_FLOW_ERROR;
3975 /* Check if all values are as expected */
3977 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
3979 /* Allow +/- 1 difference for the scaled_duration to allow
3980 * for some rounding errors
3982 if (sample_entry->nsamples != nsamples
3983 || ABSDIFF (sample_entry->delta, scaled_duration) > 1
3984 || sample_entry->size != sample_size
3985 || sample_entry->chunk_offset != chunk_offset
3986 || sample_entry->pts_offset != pts_offset
3987 || sample_entry->sync != sync) {
3988 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3989 ("Unexpected values in sample %" G_GUINT64_FORMAT,
3990 pad->sample_offset + 1));
3991 gst_buffer_unref (buffer);
3992 return GST_FLOW_ERROR;
3995 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3998 case GST_QT_MUX_MODE_MOOV_AT_END:
3999 case GST_QT_MUX_MODE_FAST_START:
4000 case GST_QT_MUX_MODE_ROBUST_RECORDING:
4001 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4002 sample_size, chunk_offset, sync, pts_offset);
4003 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4004 /* Check if it's time to re-write the headers in robust-recording mode */
4005 if (ret == GST_FLOW_OK
4006 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4007 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4009 case GST_QT_MUX_MODE_FRAGMENTED:
4010 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4011 /* ensure that always sync samples are marked as such */
4012 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4013 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4014 sample_size, !pad->sync || sync, pts_offset);
4022 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4023 guint buffer_size, GstClockTime duration)
4025 /* not that much happens here,
4026 * but updating any of this very likely needs to happen all in sync,
4027 * unless there is a very good reason not to */
4029 /* for computing the avg bitrate */
4030 pad->total_bytes += buffer_size;
4031 pad->total_duration += duration;
4032 /* for keeping track of where we are in chunk;
4033 * ensures that data really is located as recorded in atoms */
4034 qtmux->current_chunk_size += buffer_size;
4035 qtmux->current_chunk_duration += duration;
4038 static GstFlowReturn
4039 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4040 GstBuffer * buf, GstFlowReturn ret)
4042 GstVideoTimeCodeMeta *tc_meta;
4043 GstVideoTimeCode *tc;
4046 guint32 frames_since_daily_jam;
4047 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4049 if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4052 if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4055 tc_meta = gst_buffer_get_video_time_code_meta (buf);
4061 /* This means we never got a timecode before */
4062 if (pad->first_tc == NULL) {
4063 #ifndef GST_DISABLE_GST_DEBUG
4064 gchar *tc_str = gst_video_time_code_to_string (tc);
4065 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4068 g_assert (pad->tc_trak == NULL);
4069 pad->first_tc = gst_video_time_code_copy (tc);
4070 /* If frames are out of order, the frame we're currently getting might
4071 * not be the first one. Just write a 0 timecode for now and wait
4072 * until we receive a timecode that's lower than the current one */
4073 if (pad->is_out_of_order) {
4074 pad->first_pts = GST_BUFFER_PTS (buf);
4075 frames_since_daily_jam = 0;
4076 /* Position to rewrite */
4077 pad->tc_pos = qtmux->mdat_size;
4079 frames_since_daily_jam =
4080 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4081 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4083 /* Write the timecode trak now */
4084 pad->tc_trak = atom_trak_new (qtmux->context);
4085 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4087 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4088 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4090 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4091 pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4093 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4094 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4095 g_assert (szret == 4);
4097 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4098 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4100 /* Need to reset the current chunk (of the previous pad) here because
4101 * some other data was written now above, and the pad has to start a
4103 qtmux->current_chunk_offset = -1;
4104 qtmux->current_chunk_size = 0;
4105 qtmux->current_chunk_duration = 0;
4106 } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4107 frames_since_daily_jam =
4108 gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4109 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4111 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4112 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4113 g_assert (szret == 4);
4115 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4118 qtmux->current_chunk_offset = -1;
4119 qtmux->current_chunk_size = 0;
4120 qtmux->current_chunk_duration = 0;
4121 } else if (pad->is_out_of_order) {
4122 /* Check for a lower timecode than the one stored */
4123 g_assert (pad->tc_trak != NULL);
4124 if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4125 if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4126 gst_video_time_code_free (pad->first_tc);
4127 pad->first_tc = gst_video_time_code_copy (tc);
4130 guint64 bk_size = qtmux->mdat_size;
4132 /* If this frame's DTS is after the first PTS received, it means
4133 * we've already received the first frame to be presented. Otherwise
4134 * the decoder would need to go back in time */
4135 gst_qt_mux_update_timecode (qtmux, pad);
4137 /* Reset writing position */
4138 gst_segment_init (&segment, GST_FORMAT_BYTES);
4139 segment.start = bk_size;
4140 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4148 * Here we push the buffer and update the tables in the track atoms
4150 static GstFlowReturn
4151 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4153 GstBuffer *last_buf = NULL;
4154 GstClockTime duration;
4155 guint nsamples, sample_size;
4156 guint64 chunk_offset;
4157 gint64 last_dts, scaled_duration;
4158 gint64 pts_offset = 0;
4159 gboolean sync = FALSE;
4160 GstFlowReturn ret = GST_FLOW_OK;
4164 goto not_negotiated;
4166 /* if this pad has a prepare function, call it */
4167 if (pad->prepare_buf_func != NULL) {
4170 new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4171 if (buf && !new_buf)
4176 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4177 if (ret != GST_FLOW_OK) {
4179 gst_buffer_unref (buf);
4183 last_buf = pad->last_buf;
4184 pad->last_buf = buf;
4186 if (last_buf == NULL) {
4187 #ifndef GST_DISABLE_GST_DEBUG
4189 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4190 "received NULL buffer, doing nothing",
4191 GST_PAD_NAME (pad->collect.pad));
4193 GST_LOG_OBJECT (qtmux,
4194 "Pad %s has no previous buffer stored, storing now",
4195 GST_PAD_NAME (pad->collect.pad));
4201 if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4204 /* if this is the first buffer, store the timestamp */
4205 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4206 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4207 pad->first_ts = GST_BUFFER_PTS (last_buf);
4208 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4209 pad->first_ts = GST_BUFFER_DTS (last_buf);
4212 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4213 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4214 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4215 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4218 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4219 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4221 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4222 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4223 pad->first_ts = pad->first_dts = 0;
4225 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4226 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4227 GST_TIME_ARGS (pad->first_ts));
4230 if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4231 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4232 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4233 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4234 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4235 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4236 pad->last_buf = buf = gst_buffer_make_writable (buf);
4237 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4240 buffer_size = gst_buffer_get_size (last_buf);
4242 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4243 guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4244 guint fill_size = required_buffer_size - buffer_size;
4248 if (required_buffer_size < buffer_size) {
4249 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4250 ("Sample size %u bigger than expected maximum %u", buffer_size,
4251 required_buffer_size));
4255 if (fill_size > 0) {
4256 GST_DEBUG_OBJECT (qtmux,
4257 "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4258 required_buffer_size);
4259 mem = gst_allocator_alloc (NULL, fill_size, NULL);
4260 gst_memory_map (mem, &map, GST_MAP_WRITE);
4261 memset (map.data, 0, map.size);
4262 gst_memory_unmap (mem, &map);
4263 last_buf = gst_buffer_make_writable (last_buf);
4264 gst_buffer_append_memory (last_buf, mem);
4265 buffer_size = required_buffer_size;
4269 /* duration actually means time delta between samples, so we calculate
4270 * the duration based on the difference in DTS or PTS, falling back
4271 * to DURATION if the other two don't exist, such as with the last
4272 * sample before EOS. Or use 0 if nothing else is available */
4273 if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4274 duration = GST_BUFFER_DURATION (last_buf);
4278 if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4279 && GST_BUFFER_DTS_IS_VALID (last_buf))
4280 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4281 else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4282 && GST_BUFFER_PTS_IS_VALID (last_buf))
4283 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4286 if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4287 GST_DEBUG_OBJECT (qtmux,
4288 "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4289 ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4290 GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4291 qtmux->current_chunk_size,
4292 GST_TIME_ARGS (qtmux->current_chunk_duration));
4293 qtmux->current_pad = pad;
4294 if (qtmux->current_chunk_offset == -1)
4295 qtmux->current_chunk_offset = qtmux->mdat_size;
4297 qtmux->current_chunk_offset += qtmux->current_chunk_size;
4298 qtmux->current_chunk_size = 0;
4299 qtmux->current_chunk_duration = 0;
4302 last_dts = gst_util_uint64_scale_round (pad->last_dts,
4303 atom_trak_get_timescale (pad->trak), GST_SECOND);
4305 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4306 if (pad->sample_size && !qtmux->fragment_sequence) {
4307 GstClockTime expected_timestamp;
4309 /* Constant size packets: usually raw audio (with many samples per
4310 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4312 sample_size = pad->sample_size;
4313 if (buffer_size % sample_size != 0)
4314 goto fragmented_sample;
4316 /* note: qt raw audio storage warps it implicitly into a timewise
4317 * perfect stream, discarding buffer times.
4318 * If the difference between the current PTS and the expected one
4319 * becomes too big, we error out: there was a gap and we have no way to
4320 * represent that, causing A/V sync to be off */
4321 expected_timestamp =
4322 gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4323 atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4324 if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4325 expected_timestamp) > qtmux->max_raw_audio_drift)
4326 goto raw_audio_timestamp_drift;
4328 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4329 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4330 atom_trak_get_timescale (pad->trak), GST_SECOND);
4331 duration = GST_BUFFER_DURATION (last_buf);
4333 nsamples = buffer_size / sample_size;
4335 gst_util_uint64_scale_round (nsamples, GST_SECOND,
4336 atom_trak_get_timescale (pad->trak));
4339 /* timescale = samplerate */
4340 scaled_duration = 1;
4342 pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4343 nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4346 sample_size = buffer_size;
4347 if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4348 || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4350 if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4351 pad->last_dts = GST_BUFFER_DTS (buf);
4353 pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4355 if ((gint64) (pad->last_dts) < 0) {
4356 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4357 atom_trak_get_timescale (pad->trak), GST_SECOND);
4359 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4360 atom_trak_get_timescale (pad->trak), GST_SECOND);
4362 scaled_duration = scaled_dts - last_dts;
4363 last_dts = scaled_dts;
4365 /* first convert intended timestamp (in GstClockTime resolution) to
4366 * trak timescale, then derive delta;
4367 * this ensures sums of (scale)delta add up to converted timestamp,
4368 * which only deviates at most 1/scale from timestamp itself */
4369 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4370 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4371 pad->last_dts += duration;
4375 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4377 chunk_offset = qtmux->current_chunk_offset;
4379 GST_LOG_OBJECT (qtmux,
4380 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4381 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4382 GST_LOG_OBJECT (qtmux,
4383 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4384 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4385 nsamples, scaled_duration, sample_size, chunk_offset);
4387 /* might be a sync sample */
4389 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4390 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4391 GST_PAD_NAME (pad->collect.pad));
4395 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4396 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4397 atom_trak_get_timescale (pad->trak), GST_SECOND);
4399 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4400 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4403 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4404 atom_trak_get_timescale (pad->trak), GST_SECOND);
4406 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4407 " timebase_dts: %d pts_offset: %d",
4408 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4409 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4410 (int) (last_dts), (int) (pts_offset));
4412 if (GST_CLOCK_TIME_IS_VALID (duration)
4413 && (qtmux->current_chunk_duration > qtmux->longest_chunk
4414 || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4415 GST_DEBUG_OBJECT (qtmux,
4416 "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4417 GST_TIME_ARGS (qtmux->current_chunk_duration),
4418 GST_PAD_NAME (pad->collect.pad));
4419 qtmux->longest_chunk = qtmux->current_chunk_duration;
4422 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4423 const TrakBufferEntryInfo *sample_entry;
4424 guint64 block_idx = prefill_get_block_index (qtmux, pad);
4426 if (block_idx >= pad->samples->len) {
4427 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4428 ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4429 block_idx, pad->samples->len));
4433 /* Check if all values are as expected */
4435 &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4437 if (chunk_offset < sample_entry->chunk_offset) {
4438 guint fill_size = sample_entry->chunk_offset - chunk_offset;
4439 GstBuffer *fill_buf;
4441 fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4442 gst_buffer_memset (fill_buf, 0, 0, fill_size);
4444 ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4445 if (ret != GST_FLOW_OK)
4447 qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4448 qtmux->current_chunk_size = buffer_size;
4449 qtmux->current_chunk_duration = duration;
4450 } else if (chunk_offset != sample_entry->chunk_offset) {
4451 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4452 ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4453 G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4458 /* now we go and register this buffer/sample all over */
4459 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4460 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4461 chunk_offset, sync, TRUE, pts_offset);
4462 pad->sample_offset += nsamples;
4464 /* if this is sparse and we have a next buffer, check if there is any gap
4465 * between them to insert an empty sample */
4466 if (pad->sparse && buf) {
4467 if (pad->create_empty_buffer) {
4468 GstBuffer *empty_buf;
4469 gint64 empty_duration =
4470 GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4471 gint64 empty_duration_scaled;
4474 empty_buf = pad->create_empty_buffer (pad, empty_duration);
4476 pad->last_dts = GST_BUFFER_PTS (buf);
4477 empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4478 atom_trak_get_timescale (pad->trak), GST_SECOND)
4479 - (last_dts + scaled_duration);
4480 empty_size = gst_buffer_get_size (empty_buf);
4482 gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4486 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4487 last_dts + scaled_duration, empty_duration_scaled,
4488 empty_size, chunk_offset, sync, TRUE, 0);
4490 /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
4491 g_assert_not_reached ();
4492 GST_WARNING_OBJECT (qtmux,
4493 "no empty buffer creation function found for pad %s",
4494 GST_PAD_NAME (pad->collect.pad));
4505 gst_buffer_unref (last_buf);
4506 return GST_FLOW_ERROR;
4510 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4511 ("Audio buffer contains fragmented sample."));
4514 raw_audio_timestamp_drift:
4516 /* TODO: Could in theory be implemented with edit lists */
4517 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4518 ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4519 ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4520 GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4521 GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4523 atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4528 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4533 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4534 ("format wasn't negotiated before buffer flow on pad %s",
4535 GST_PAD_NAME (pad->collect.pad)));
4537 gst_buffer_unref (buf);
4538 return GST_FLOW_NOT_NEGOTIATED;
4543 * DTS running time can be negative. There is no way to represent that in
4544 * MP4 however, thus we need to offset DTS so that it starts from 0.
4547 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4548 GstCollectData * cdata, GstBuffer ** buf)
4553 pts = GST_BUFFER_PTS (*buf);
4554 dts = GST_COLLECT_PADS_DTS (cdata);
4556 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4557 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4558 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4560 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4561 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4562 pad->dts_adjustment = -dts;
4564 pad->dts_adjustment = 0;
4567 if (pad->dts_adjustment > 0) {
4568 *buf = gst_buffer_make_writable (*buf);
4570 dts += pad->dts_adjustment;
4572 if (GST_CLOCK_TIME_IS_VALID (pts))
4573 pts += pad->dts_adjustment;
4575 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4576 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4581 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4585 GST_BUFFER_PTS (*buf) = pts;
4586 GST_BUFFER_DTS (*buf) = dts;
4588 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4589 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4594 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4597 GstQTPad *best_pad = NULL;
4599 if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4600 guint64 smallest_offset = G_MAXUINT64;
4601 guint64 chunk_offset = 0;
4603 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4604 GstCollectData *cdata = (GstCollectData *) walk->data;
4605 GstQTPad *qtpad = (GstQTPad *) cdata;
4606 const TrakBufferEntryInfo *sample_entry;
4607 guint64 block_idx, current_block_idx;
4608 guint64 chunk_offset_offset = 0;
4609 GstBuffer *tmp_buf =
4610 gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4612 /* Check for EOS pads and just skip them */
4613 if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4614 || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4617 gst_buffer_unref (tmp_buf);
4619 /* Find the exact offset where the next sample of this track is supposed
4620 * to be written at */
4621 block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4623 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4624 while (block_idx > 0) {
4625 const TrakBufferEntryInfo *tmp =
4626 &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4628 if (tmp->chunk_offset != sample_entry->chunk_offset)
4630 chunk_offset_offset += tmp->size * tmp->nsamples;
4634 /* Except for the previously selected pad being EOS we always have
4635 * qtmux->current_chunk_offset + qtmux->current_chunk_size
4637 * sample_entry->chunk_offset + chunk_offset_offset
4638 * for the best pad. Instead of checking that, we just return the
4639 * pad that has the smallest offset for the next to-be-written sample.
4641 if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4642 smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4644 chunk_offset = sample_entry->chunk_offset;
4648 if (chunk_offset != qtmux->current_chunk_offset) {
4649 qtmux->current_pad = NULL;
4655 if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4656 || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4657 || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4658 && (qtmux->interleave_time == 0
4659 || qtmux->current_chunk_duration <= qtmux->interleave_time)
4660 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4661 && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4662 GstBuffer *tmp_buf =
4663 gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4665 if (tmp_buf || qtmux->current_pad->last_buf) {
4666 best_pad = qtmux->current_pad;
4668 gst_buffer_unref (tmp_buf);
4669 GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4670 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4672 } else if (qtmux->collect->data->next) {
4673 /* Only switch pads if we have more than one, otherwise
4674 * we can just put everything into a single chunk and save
4675 * a few bytes of offsets
4677 if (qtmux->current_pad)
4678 GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4679 GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4680 best_pad = qtmux->current_pad = NULL;
4684 GstClockTime best_time = GST_CLOCK_TIME_NONE;
4686 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4687 GstCollectData *cdata = (GstCollectData *) walk->data;
4688 GstQTPad *qtpad = (GstQTPad *) cdata;
4690 GstClockTime timestamp;
4692 tmp_buf = gst_collect_pads_peek (pads, cdata);
4694 /* This one is newly EOS now, finish it for real */
4695 if (qtpad->last_buf) {
4696 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4701 if (qtpad->last_buf)
4702 timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
4704 timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
4707 if (best_pad == NULL ||
4708 !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
4710 best_time = timestamp;
4714 gst_buffer_unref (tmp_buf);
4718 GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
4719 GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4721 GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
4728 static GstFlowReturn
4729 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
4731 GstFlowReturn ret = GST_FLOW_OK;
4732 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
4733 GstQTPad *best_pad = NULL;
4735 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
4736 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
4739 qtmux->state = GST_QT_MUX_STATE_DATA;
4742 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
4743 return GST_FLOW_EOS;
4745 best_pad = find_best_pad (qtmux, pads);
4747 /* clipping already converted to running time */
4748 if (best_pad != NULL) {
4749 GstBuffer *buf = NULL;
4751 if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
4752 best_pad->raw_audio_adapter == NULL ||
4753 best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
4754 buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
4756 g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
4757 && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
4760 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
4761 (GstCollectData *) best_pad, &buf);
4763 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
4765 qtmux->state = GST_QT_MUX_STATE_EOS;
4766 ret = gst_qt_mux_stop_file (qtmux);
4767 if (ret == GST_FLOW_OK) {
4768 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
4769 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
4772 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
4773 gst_flow_get_name (ret));
4781 check_field (GQuark field_id, const GValue * value, gpointer user_data)
4783 GstStructure *structure = (GstStructure *) user_data;
4784 const GValue *other = gst_structure_id_get_value (structure, field_id);
4787 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
4791 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
4794 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
4795 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
4797 return gst_structure_foreach (sub_s, check_field, sup_s);
4801 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4803 GstPad *pad = qtpad->collect.pad;
4804 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4805 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4806 GstStructure *structure;
4807 const gchar *mimetype;
4808 gint rate, channels;
4809 const GValue *value = NULL;
4810 const GstBuffer *codec_data = NULL;
4811 GstQTMuxFormat format;
4812 AudioSampleEntry entry = { 0, };
4813 AtomInfo *ext_atom = NULL;
4814 gint constant_size = 0;
4815 const gchar *stream_format;
4818 /* does not go well to renegotiate stream mid-way, unless
4819 * the old caps are a subset of the new one (this means upstream
4820 * added more info to the caps, as both should be 'fixed' caps) */
4821 if (qtpad->fourcc) {
4822 GstCaps *current_caps;
4824 current_caps = gst_pad_get_current_caps (pad);
4825 g_assert (caps != NULL);
4827 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4828 gst_caps_unref (current_caps);
4829 goto refuse_renegotiation;
4831 GST_DEBUG_OBJECT (qtmux,
4832 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4833 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4834 gst_caps_unref (current_caps);
4839 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4840 GST_DEBUG_PAD_NAME (pad), caps);
4842 qtpad->prepare_buf_func = NULL;
4844 format = qtmux_klass->format;
4845 structure = gst_caps_get_structure (caps, 0);
4846 mimetype = gst_structure_get_name (structure);
4849 if (!gst_structure_get_int (structure, "channels", &channels) ||
4850 !gst_structure_get_int (structure, "rate", &rate)) {
4855 value = gst_structure_get_value (structure, "codec_data");
4857 codec_data = gst_value_get_buffer (value);
4859 qtpad->is_out_of_order = FALSE;
4861 /* set common properties */
4862 entry.sample_rate = rate;
4863 entry.channels = channels;
4865 entry.sample_size = 16;
4866 /* this is the typical compressed case */
4867 if (format == GST_QT_MUX_FORMAT_QT) {
4869 entry.compression_id = -2;
4872 /* now map onto a fourcc, and some extra properties */
4873 if (strcmp (mimetype, "audio/mpeg") == 0) {
4874 gint mpegversion = 0, mpegaudioversion = 0;
4877 gst_structure_get_int (structure, "mpegversion", &mpegversion);
4878 switch (mpegversion) {
4880 gst_structure_get_int (structure, "layer", &layer);
4881 gst_structure_get_int (structure, "mpegaudioversion",
4885 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
4886 if (format == GST_QT_MUX_FORMAT_QT)
4887 entry.fourcc = FOURCC__mp3;
4889 entry.fourcc = FOURCC_mp4a;
4891 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
4892 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4893 qtpad->max_bitrate);
4896 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
4897 || format == GST_QT_MUX_FORMAT_QT);
4898 entry.samples_per_packet = 384;
4899 } else if (layer == 2) {
4900 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
4901 || format == GST_QT_MUX_FORMAT_QT);
4902 entry.samples_per_packet = 1152;
4904 g_warn_if_fail (layer == 3);
4905 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
4907 entry.bytes_per_sample = 2;
4911 /* check stream-format */
4912 stream_format = gst_structure_get_string (structure, "stream-format");
4913 if (stream_format) {
4914 if (strcmp (stream_format, "raw") != 0) {
4915 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
4916 "please use 'raw'", stream_format);
4920 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
4924 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
4925 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
4930 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
4931 /* warn if not Low Complexity profile */
4934 GST_WARNING_OBJECT (qtmux,
4935 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
4939 entry.fourcc = FOURCC_mp4a;
4941 if (format == GST_QT_MUX_FORMAT_QT)
4942 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
4943 qtpad->avg_bitrate, qtpad->max_bitrate);
4946 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
4947 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
4948 qtpad->max_bitrate);
4953 } else if (strcmp (mimetype, "audio/AMR") == 0) {
4954 entry.fourcc = FOURCC_samr;
4955 entry.sample_size = 16;
4956 entry.samples_per_packet = 160;
4957 entry.bytes_per_sample = 2;
4958 ext_atom = build_amr_extension ();
4959 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
4960 entry.fourcc = FOURCC_sawb;
4961 entry.sample_size = 16;
4962 entry.samples_per_packet = 320;
4963 entry.bytes_per_sample = 2;
4964 ext_atom = build_amr_extension ();
4965 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
4968 gst_audio_info_init (&info);
4969 if (!gst_audio_info_from_caps (&info, caps))
4972 /* spec has no place for a distinction in these */
4973 if (info.finfo->width != info.finfo->depth) {
4974 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
4978 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
4979 if (info.finfo->endianness == G_LITTLE_ENDIAN)
4980 entry.fourcc = FOURCC_sowt;
4981 else if (info.finfo->endianness == G_BIG_ENDIAN)
4982 entry.fourcc = FOURCC_twos;
4984 entry.fourcc = FOURCC_sowt;
4985 /* maximum backward compatibility; only new version for > 16 bit */
4986 if (info.finfo->depth <= 16)
4988 /* not compressed in any case */
4989 entry.compression_id = 0;
4990 /* QT spec says: max at 16 bit even if sample size were actually larger,
4991 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
4992 entry.sample_size = info.finfo->depth;
4993 entry.bytes_per_sample = info.finfo->depth / 8;
4994 entry.samples_per_packet = 1;
4995 entry.bytes_per_packet = info.finfo->depth / 8;
4996 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
4998 if (info.finfo->width == 8 && info.finfo->depth == 8) {
4999 /* fall back to old 8-bit version */
5000 entry.fourcc = FOURCC_raw_;
5002 entry.compression_id = 0;
5003 entry.sample_size = 8;
5005 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5009 constant_size = (info.finfo->depth / 8) * info.channels;
5010 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5011 entry.fourcc = FOURCC_alaw;
5012 entry.samples_per_packet = 1023;
5013 entry.bytes_per_sample = 2;
5014 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5015 entry.fourcc = FOURCC_ulaw;
5016 entry.samples_per_packet = 1023;
5017 entry.bytes_per_sample = 2;
5018 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5020 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5021 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5024 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5026 entry.fourcc = MS_WAVE_FOURCC (0x11);
5027 /* 4 byte header per channel (including one sample). 2 samples per byte
5028 remaining. Simplifying gives the following (samples per block per
5030 entry.samples_per_packet = 2 * blocksize / channels - 7;
5031 entry.bytes_per_sample = 2;
5033 entry.bytes_per_frame = blocksize;
5034 entry.bytes_per_packet = blocksize / channels;
5035 /* ADPCM has constant size packets */
5037 /* TODO: I don't really understand why this helps, but it does! Constant
5038 * size and compression_id of -2 seem to be incompatible, and other files
5039 * in the wild use this too. */
5040 entry.compression_id = -1;
5042 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5043 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5044 GstBuffer *codec_config;
5048 entry.fourcc = FOURCC_alac;
5049 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5050 /* let's check if codec data already comes with 'alac' atom prefix */
5051 if (!codec_data || (len = map.size) < 28) {
5052 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5053 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5056 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5059 gst_buffer_copy_region ((GstBuffer *) codec_data,
5060 GST_BUFFER_COPY_MEMORY, 8, len);
5062 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5064 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5066 /* does not look good, but perhaps some trailing unneeded stuff */
5067 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5069 if (format == GST_QT_MUX_FORMAT_QT)
5070 ext_atom = build_mov_alac_extension (codec_config);
5072 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5073 /* set some more info */
5074 gst_buffer_map (codec_config, &map, GST_MAP_READ);
5075 entry.bytes_per_sample = 2;
5076 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5077 gst_buffer_unmap (codec_config, &map);
5078 gst_buffer_unref (codec_config);
5079 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5080 entry.fourcc = FOURCC_ac_3;
5082 /* Fixed values according to TS 102 366 but it also mentions that
5083 * they should be ignored */
5085 entry.sample_size = 16;
5087 /* AC-3 needs an extension atom but its data can only be obtained from
5088 * the stream itself. Abuse the prepare_buf_func so we parse a frame
5089 * and get the needed data */
5090 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5091 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5092 /* Based on the specification defined in:
5093 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5094 guint8 channels, mapping_family, stream_count, coupled_count;
5098 guint8 channel_mapping[256];
5099 const GValue *streamheader;
5100 const GValue *first_element;
5103 entry.fourcc = FOURCC_opus;
5104 entry.sample_size = 16;
5106 streamheader = gst_structure_get_value (structure, "streamheader");
5107 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5108 gst_value_array_get_size (streamheader) != 0) {
5109 first_element = gst_value_array_get_value (streamheader, 0);
5110 header = gst_value_get_buffer (first_element);
5111 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5112 &mapping_family, &stream_count, &coupled_count, channel_mapping,
5113 &pre_skip, &output_gain)) {
5114 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5118 GST_WARNING_OBJECT (qtmux,
5119 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5121 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5122 &mapping_family, &stream_count, &coupled_count,
5124 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5131 entry.channels = channels;
5132 ext_atom = build_opus_extension (rate, channels, mapping_family,
5133 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5139 timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5140 if (!timescale && qtmux->trak_timescale)
5141 timescale = qtmux->trak_timescale;
5142 else if (!timescale)
5143 timescale = entry.sample_rate;
5145 /* ok, set the pad info accordingly */
5146 qtpad->fourcc = entry.fourcc;
5147 qtpad->sample_size = constant_size;
5149 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5150 qtmux->context, &entry, timescale, ext_atom, constant_size);
5152 gst_object_unref (qtmux);
5158 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5159 GST_PAD_NAME (pad), caps);
5160 gst_object_unref (qtmux);
5163 refuse_renegotiation:
5165 GST_WARNING_OBJECT (qtmux,
5166 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5167 GST_PAD_NAME (pad), caps);
5168 gst_object_unref (qtmux);
5174 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5176 GstPad *pad = qtpad->collect.pad;
5177 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5178 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5179 GstStructure *structure;
5180 const gchar *mimetype;
5181 gint width, height, depth = -1;
5182 gint framerate_num, framerate_den;
5184 const GValue *value = NULL;
5185 const GstBuffer *codec_data = NULL;
5186 VisualSampleEntry entry = { 0, };
5187 GstQTMuxFormat format;
5188 AtomInfo *ext_atom = NULL;
5189 GList *ext_atom_list = NULL;
5190 gboolean sync = FALSE;
5191 int par_num, par_den;
5192 const gchar *multiview_mode;
5194 /* does not go well to renegotiate stream mid-way, unless
5195 * the old caps are a subset of the new one (this means upstream
5196 * added more info to the caps, as both should be 'fixed' caps) */
5197 if (qtpad->fourcc) {
5198 GstCaps *current_caps;
5200 current_caps = gst_pad_get_current_caps (pad);
5201 g_assert (caps != NULL);
5203 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5204 gst_caps_unref (current_caps);
5205 goto refuse_renegotiation;
5207 GST_DEBUG_OBJECT (qtmux,
5208 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5209 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5210 gst_caps_unref (current_caps);
5215 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5216 GST_DEBUG_PAD_NAME (pad), caps);
5218 qtpad->prepare_buf_func = NULL;
5220 format = qtmux_klass->format;
5221 structure = gst_caps_get_structure (caps, 0);
5222 mimetype = gst_structure_get_name (structure);
5224 /* required parts */
5225 if (!gst_structure_get_int (structure, "width", &width) ||
5226 !gst_structure_get_int (structure, "height", &height))
5231 /* works as a default timebase */
5232 framerate_num = 10000;
5234 gst_structure_get_fraction (structure, "framerate", &framerate_num,
5236 gst_structure_get_int (structure, "depth", &depth);
5237 value = gst_structure_get_value (structure, "codec_data");
5239 codec_data = gst_value_get_buffer (value);
5243 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5246 qtpad->is_out_of_order = FALSE;
5248 /* bring frame numerator into a range that ensures both reasonable resolution
5249 * as well as a fair duration */
5250 qtpad->expected_sample_duration_n = framerate_num;
5251 qtpad->expected_sample_duration_d = framerate_den;
5253 rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5254 if (!rate && qtmux->trak_timescale)
5255 rate = qtmux->trak_timescale;
5257 rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5259 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5262 multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5263 if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5264 GstVideoMultiviewMode mode;
5265 GstVideoMultiviewFlags flags = 0;
5267 mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5268 gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5270 case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5271 qtpad->trak->mdia.minf.stbl.svmi =
5273 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5275 case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5276 qtpad->trak->mdia.minf.stbl.svmi =
5278 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5280 case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5281 qtpad->trak->mdia.minf.stbl.svmi =
5283 flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5286 GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5292 /* set common properties */
5293 entry.width = width;
5294 entry.height = height;
5295 entry.par_n = par_num;
5296 entry.par_d = par_den;
5297 /* should be OK according to qt and iso spec, override if really needed */
5298 entry.color_table_id = -1;
5299 entry.frame_count = 1;
5302 /* sync entries by default */
5305 /* now map onto a fourcc, and some extra properties */
5306 if (strcmp (mimetype, "video/x-raw") == 0) {
5307 const gchar *format;
5309 const GstVideoFormatInfo *vinfo;
5311 format = gst_structure_get_string (structure, "format");
5312 fmt = gst_video_format_from_string (format);
5313 vinfo = gst_video_format_get_info (fmt);
5316 case GST_VIDEO_FORMAT_UYVY:
5319 entry.fourcc = FOURCC_2vuy;
5320 entry.depth = depth;
5323 case GST_VIDEO_FORMAT_v210:
5326 entry.fourcc = FOURCC_v210;
5327 entry.depth = depth;
5331 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5332 entry.fourcc = FOURCC_raw_;
5333 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5338 } else if (strcmp (mimetype, "video/x-h263") == 0) {
5340 if (format == GST_QT_MUX_FORMAT_QT)
5341 entry.fourcc = FOURCC_h263;
5343 entry.fourcc = FOURCC_s263;
5344 ext_atom = build_h263_extension ();
5345 if (ext_atom != NULL)
5346 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5347 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5348 strcmp (mimetype, "video/mpeg") == 0) {
5351 if (strcmp (mimetype, "video/x-divx") == 0) {
5352 gst_structure_get_int (structure, "divxversion", &version);
5353 version = version == 5 ? 1 : 0;
5355 gst_structure_get_int (structure, "mpegversion", &version);
5356 version = version == 4 ? 1 : 0;
5359 entry.fourcc = FOURCC_mp4v;
5361 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5362 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5363 qtpad->max_bitrate);
5364 if (ext_atom != NULL)
5365 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5367 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5368 "output might not play in Apple QuickTime (try global-headers?)");
5370 } else if (strcmp (mimetype, "video/x-h264") == 0) {
5372 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5376 entry.fourcc = FOURCC_avc1;
5378 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5379 if (ext_atom != NULL)
5380 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5381 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5382 if (ext_atom != NULL)
5383 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5384 } else if (strcmp (mimetype, "video/x-h265") == 0) {
5385 const gchar *format;
5388 GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5392 format = gst_structure_get_string (structure, "stream-format");
5393 if (strcmp (format, "hvc1") == 0)
5394 entry.fourcc = FOURCC_hvc1;
5395 else if (strcmp (format, "hev1") == 0)
5396 entry.fourcc = FOURCC_hev1;
5398 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5399 if (ext_atom != NULL)
5400 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5402 ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5403 if (ext_atom != NULL)
5404 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5406 } else if (strcmp (mimetype, "video/x-svq") == 0) {
5408 const GstBuffer *seqh = NULL;
5409 const GValue *seqh_value;
5412 gst_structure_get_int (structure, "svqversion", &version);
5414 entry.fourcc = FOURCC_SVQ3;
5418 seqh_value = gst_structure_get_value (structure, "seqh");
5420 seqh = gst_value_get_buffer (seqh_value);
5421 ext_atom = build_SMI_atom (seqh);
5423 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5426 /* we need to add the gamma anyway because quicktime might crash
5427 * when it doesn't find it */
5428 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5429 /* it seems that using 0 here makes it ignored */
5432 ext_atom = build_gama_atom (gamma);
5434 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5436 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5437 "a bug at http://bugzilla.gnome.org", version);
5439 } else if (strcmp (mimetype, "video/x-dv") == 0) {
5441 gboolean pal = TRUE;
5444 if (framerate_num != 25 || framerate_den != 1)
5446 gst_structure_get_int (structure, "dvversion", &version);
5447 /* fall back to typical one */
5453 entry.fourcc = FOURCC_dvcp;
5455 entry.fourcc = FOURCC_dvc_;
5459 entry.fourcc = FOURCC_dv5p;
5461 entry.fourcc = FOURCC_dv5n;
5464 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5467 } else if (strcmp (mimetype, "image/jpeg") == 0) {
5468 entry.fourcc = FOURCC_jpeg;
5470 } else if (strcmp (mimetype, "image/png") == 0) {
5471 entry.fourcc = FOURCC_png;
5473 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5474 strcmp (mimetype, "image/x-jpc") == 0) {
5475 const gchar *colorspace;
5476 const GValue *cmap_array;
5477 const GValue *cdef_array;
5480 if (strcmp (mimetype, "image/x-jpc") == 0) {
5481 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5484 gst_structure_get_int (structure, "num-components", &ncomp);
5485 cmap_array = gst_structure_get_value (structure, "component-map");
5486 cdef_array = gst_structure_get_value (structure, "channel-definitions");
5489 entry.fourcc = FOURCC_mjp2;
5492 colorspace = gst_structure_get_string (structure, "colorspace");
5495 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5496 cdef_array)) != NULL) {
5497 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5499 ext_atom = build_jp2x_extension (codec_data);
5501 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5503 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5506 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5507 entry.fourcc = FOURCC_vp08;
5508 } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5509 entry.fourcc = FOURCC_vp09;
5510 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5511 entry.fourcc = FOURCC_drac;
5512 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5515 gst_structure_get_uint (structure, "format", &fourcc);
5516 entry.fourcc = fourcc;
5517 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5520 gst_structure_get_uint (structure, "format", &fourcc);
5521 entry.fourcc = fourcc;
5522 } else if (strcmp (mimetype, "video/x-prores") == 0) {
5523 const gchar *variant;
5525 variant = gst_structure_get_string (structure, "variant");
5526 if (!variant || !g_strcmp0 (variant, "standard"))
5527 entry.fourcc = FOURCC_apcn;
5528 else if (!g_strcmp0 (variant, "lt"))
5529 entry.fourcc = FOURCC_apcs;
5530 else if (!g_strcmp0 (variant, "hq"))
5531 entry.fourcc = FOURCC_apch;
5532 else if (!g_strcmp0 (variant, "proxy"))
5533 entry.fourcc = FOURCC_apco;
5534 else if (!g_strcmp0 (variant, "4444"))
5535 entry.fourcc = FOURCC_ap4h;
5536 else if (!g_strcmp0 (variant, "4444xq"))
5537 entry.fourcc = FOURCC_ap4x;
5541 if (!qtmux->interleave_time_set)
5542 qtmux->interleave_time = 500 * GST_MSECOND;
5543 if (!qtmux->interleave_bytes_set)
5544 qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5545 } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5546 entry.fourcc = FOURCC_cfhd;
5553 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5554 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5556 GstVideoColorimetry colorimetry;
5558 s = gst_structure_get_string (structure, "colorimetry");
5559 if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5561 build_colr_extension (&colorimetry,
5562 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5564 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5568 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5569 || strcmp (mimetype, "image/x-j2c") == 0
5570 || strcmp (mimetype, "image/x-jpc") == 0) {
5572 GstVideoInterlaceMode interlace_mode;
5573 GstVideoFieldOrder field_order;
5576 if (strcmp (mimetype, "image/x-j2c") == 0 ||
5577 strcmp (mimetype, "image/x-jpc") == 0) {
5580 gst_structure_get_int (structure, "fields", &fields);
5583 s = gst_structure_get_string (structure, "interlace-mode");
5585 interlace_mode = gst_video_interlace_mode_from_string (s);
5589 1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5590 GST_VIDEO_INTERLACE_MODE_MIXED;
5592 field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5593 if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5594 s = gst_structure_get_string (structure, "field-order");
5596 field_order = gst_video_field_order_from_string (s);
5599 ext_atom = build_fiel_extension (interlace_mode, field_order);
5601 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5605 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5606 width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5607 /* The 'clap' extension is also defined for MP4 but inventing values in
5608 * general seems a bit tricky for this one. We only write it for
5609 * SD resolution in MOV, where it is a requirement.
5610 * The same goes for the 'tapt' extension, just that it is not defined for
5611 * MP4 and only for MOV
5613 gint dar_num, dar_den;
5614 gint clef_width, clef_height, prof_width;
5615 gint clap_width_n, clap_width_d, clap_height;
5619 /* First, guess display aspect ratio based on pixel aspect ratio,
5620 * width and height. We assume that display aspect ratio is either
5623 approx_dar = (gdouble) (width * par_num) / (height * par_den);
5624 if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5627 } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5631 dar_num = width * par_num;
5632 dar_den = height * par_den;
5633 cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5638 /* Then, calculate clean-aperture values (clap and clef)
5639 * using the guessed DAR.
5641 clef_height = clap_height = (height == 486 ? 480 : height);
5642 clef_width = gst_util_uint64_scale (clef_height,
5643 dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5644 prof_width = gst_util_uint64_scale (width,
5645 par_num * G_GUINT64_CONSTANT (65536), par_den);
5646 clap_width_n = clap_height * dar_num * par_den;
5647 clap_width_d = dar_den * par_num;
5648 cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5649 clap_width_n /= cdiv;
5650 clap_width_d /= cdiv;
5652 ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5653 height << 16, width << 16, height << 16);
5654 qtpad->trak->tapt = ext_atom;
5656 ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5657 clap_height, 1, 0, 1, 0, 1);
5659 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5662 /* ok, set the pad info accordingly */
5663 qtpad->fourcc = entry.fourcc;
5666 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5667 qtmux->context, &entry, rate, ext_atom_list);
5668 if (strcmp (mimetype, "video/x-prores") == 0) {
5669 SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5670 const gchar *compressor = NULL;
5671 mp4v->spatial_quality = 0x3FF;
5672 mp4v->temporal_quality = 0;
5673 mp4v->vendor = FOURCC_appl;
5674 mp4v->horizontal_resolution = 72 << 16;
5675 mp4v->vertical_resolution = 72 << 16;
5676 mp4v->depth = (entry.fourcc == FOURCC_ap4h
5677 || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5679 /* Set compressor name, required by some software */
5680 switch (entry.fourcc) {
5682 compressor = "Apple ProRes 422";
5685 compressor = "Apple ProRes 422 LT";
5688 compressor = "Apple ProRes 422 HQ";
5691 compressor = "Apple ProRes 422 Proxy";
5694 compressor = "Apple ProRes 4444";
5697 compressor = "Apple ProRes 4444 XQ";
5701 strcpy ((gchar *) mp4v->compressor + 1, compressor);
5702 mp4v->compressor[0] = strlen (compressor);
5706 gst_object_unref (qtmux);
5712 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5713 GST_PAD_NAME (pad), caps);
5714 gst_object_unref (qtmux);
5717 refuse_renegotiation:
5719 GST_ELEMENT_WARNING (qtmux, STREAM, FORMAT,
5720 ("Can't change input format at runtime."),
5721 ("pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5723 gst_object_unref (qtmux);
5729 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5731 GstPad *pad = qtpad->collect.pad;
5732 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5733 GstStructure *structure;
5734 SubtitleSampleEntry entry = { 0, };
5736 /* does not go well to renegotiate stream mid-way, unless
5737 * the old caps are a subset of the new one (this means upstream
5738 * added more info to the caps, as both should be 'fixed' caps) */
5739 if (qtpad->fourcc) {
5740 GstCaps *current_caps;
5742 current_caps = gst_pad_get_current_caps (pad);
5743 g_assert (caps != NULL);
5745 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5746 gst_caps_unref (current_caps);
5747 goto refuse_renegotiation;
5749 GST_DEBUG_OBJECT (qtmux,
5750 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5751 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5752 gst_caps_unref (current_caps);
5757 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5758 GST_DEBUG_PAD_NAME (pad), caps);
5760 /* subtitles default */
5761 subtitle_sample_entry_init (&entry);
5762 qtpad->is_out_of_order = FALSE;
5763 qtpad->sync = FALSE;
5764 qtpad->sparse = TRUE;
5765 qtpad->prepare_buf_func = NULL;
5767 structure = gst_caps_get_structure (caps, 0);
5769 if (gst_structure_has_name (structure, "text/x-raw")) {
5770 const gchar *format = gst_structure_get_string (structure, "format");
5771 if (format && strcmp (format, "utf8") == 0) {
5772 entry.fourcc = FOURCC_tx3g;
5773 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
5774 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
5781 qtpad->fourcc = entry.fourcc;
5783 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
5784 qtmux->context, &entry);
5786 gst_object_unref (qtmux);
5792 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5793 GST_PAD_NAME (pad), caps);
5794 gst_object_unref (qtmux);
5797 refuse_renegotiation:
5799 GST_WARNING_OBJECT (qtmux,
5800 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
5802 gst_object_unref (qtmux);
5808 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
5809 GstEvent * event, gpointer user_data)
5812 guint32 avg_bitrate = 0, max_bitrate = 0;
5813 GstPad *pad = data->pad;
5814 gboolean ret = TRUE;
5816 qtmux = GST_QT_MUX_CAST (user_data);
5817 switch (GST_EVENT_TYPE (event)) {
5818 case GST_EVENT_CAPS:
5821 GstQTPad *collect_pad;
5823 gst_event_parse_caps (event, &caps);
5825 /* find stream data */
5826 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5827 g_assert (collect_pad);
5828 g_assert (collect_pad->set_caps);
5830 ret = collect_pad->set_caps (collect_pad, caps);
5831 gst_event_unref (event);
5835 case GST_EVENT_TAG:{
5837 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
5838 GstTagMergeMode mode;
5840 GstQTPad *collect_pad;
5842 GST_OBJECT_LOCK (qtmux);
5843 mode = gst_tag_setter_get_tag_merge_mode (setter);
5844 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
5846 gst_event_parse_tag (event, &list);
5847 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
5848 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
5850 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
5851 gst_tag_setter_merge_tags (setter, list, mode);
5852 qtmux->tags_changed = TRUE;
5854 if (!collect_pad->tags)
5855 collect_pad->tags = gst_tag_list_new_empty ();
5856 gst_tag_list_insert (collect_pad->tags, list, mode);
5857 collect_pad->tags_changed = TRUE;
5859 GST_OBJECT_UNLOCK (qtmux);
5861 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
5862 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
5863 GstQTPad *qtpad = gst_pad_get_element_private (pad);
5866 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
5867 qtpad->avg_bitrate = avg_bitrate;
5868 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
5869 qtpad->max_bitrate = max_bitrate;
5872 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
5873 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
5875 GstQTPad *qtpad = gst_pad_get_element_private (pad);
5878 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
5879 qtpad->trak->mdia.mdhd.language_code =
5880 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
5881 (iso_code[2] - 0x60);
5887 gst_event_unref (event);
5897 return gst_collect_pads_event_default (pads, data, event, FALSE);
5903 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
5905 GstQTMux *mux = GST_QT_MUX_CAST (element);
5908 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
5910 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
5911 GstQTPad *qtpad = (GstQTPad *) walk->data;
5912 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
5913 if (qtpad->collect.pad == pad) {
5914 /* this is it, remove */
5915 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
5916 gst_element_remove_pad (element, pad);
5921 if (mux->current_pad && mux->current_pad->collect.pad == pad) {
5922 mux->current_pad = NULL;
5923 mux->current_chunk_size = 0;
5924 mux->current_chunk_duration = 0;
5927 gst_collect_pads_remove_pad (mux->collect, pad);
5929 if (mux->sinkpads == NULL) {
5930 /* No more outstanding request pads, reset our counters */
5931 mux->video_pads = 0;
5932 mux->audio_pads = 0;
5933 mux->subtitle_pads = 0;
5938 gst_qt_mux_request_new_pad (GstElement * element,
5939 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
5941 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
5942 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
5943 GstQTPad *collect_pad;
5945 GstQTPadSetCapsFunc setcaps_func;
5948 gboolean lock = TRUE;
5950 if (templ->direction != GST_PAD_SINK)
5951 goto wrong_direction;
5953 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
5956 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
5957 setcaps_func = gst_qt_mux_audio_sink_set_caps;
5958 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
5959 name = g_strdup (req_name);
5961 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
5963 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
5964 setcaps_func = gst_qt_mux_video_sink_set_caps;
5965 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
5966 name = g_strdup (req_name);
5968 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
5970 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
5971 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
5972 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
5973 name = g_strdup (req_name);
5975 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
5979 goto wrong_template;
5981 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
5983 /* create pad and add to collections */
5985 g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
5986 templ->direction, "template", templ, NULL);
5988 collect_pad = (GstQTPad *)
5989 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
5990 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
5992 gst_qt_mux_pad_reset (collect_pad);
5993 collect_pad->trak = atom_trak_new (qtmux->context);
5994 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
5996 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
5998 /* set up pad functions */
5999 collect_pad->set_caps = setcaps_func;
6001 gst_pad_set_active (newpad, TRUE);
6002 gst_element_add_pad (element, newpad);
6009 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6014 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6019 GST_WARNING_OBJECT (qtmux, "This is not our template!");
6025 gst_qt_mux_get_property (GObject * object,
6026 guint prop_id, GValue * value, GParamSpec * pspec)
6028 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6030 GST_OBJECT_LOCK (qtmux);
6032 case PROP_MOVIE_TIMESCALE:
6033 g_value_set_uint (value, qtmux->timescale);
6035 case PROP_TRAK_TIMESCALE:
6036 g_value_set_uint (value, qtmux->trak_timescale);
6039 g_value_set_boolean (value, qtmux->guess_pts);
6041 #ifndef GST_REMOVE_DEPRECATED
6042 case PROP_DTS_METHOD:
6043 g_value_set_enum (value, qtmux->dts_method);
6046 case PROP_FAST_START:
6047 g_value_set_boolean (value, qtmux->fast_start);
6049 case PROP_FAST_START_TEMP_FILE:
6050 g_value_set_string (value, qtmux->fast_start_file_path);
6052 case PROP_MOOV_RECOV_FILE:
6053 g_value_set_string (value, qtmux->moov_recov_file_path);
6055 case PROP_FRAGMENT_DURATION:
6056 g_value_set_uint (value, qtmux->fragment_duration);
6058 case PROP_STREAMABLE:
6059 g_value_set_boolean (value, qtmux->streamable);
6061 case PROP_RESERVED_MAX_DURATION:
6062 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6064 case PROP_RESERVED_DURATION_REMAINING:
6065 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6066 g_value_set_uint64 (value, qtmux->reserved_max_duration);
6068 GstClockTime remaining = qtmux->reserved_duration_remaining;
6070 /* Report the remaining space as the calculated remaining, minus
6071 * however much we've muxed since the last update */
6072 if (remaining > qtmux->muxed_since_last_update)
6073 remaining -= qtmux->muxed_since_last_update;
6076 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6077 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6078 remaining, qtmux->reserved_duration_remaining,
6079 qtmux->muxed_since_last_update);
6080 g_value_set_uint64 (value, remaining);
6083 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6084 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6086 case PROP_RESERVED_BYTES_PER_SEC:
6087 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6089 case PROP_RESERVED_PREFILL:
6090 g_value_set_boolean (value, qtmux->reserved_prefill);
6092 case PROP_INTERLEAVE_BYTES:
6093 g_value_set_uint64 (value, qtmux->interleave_bytes);
6095 case PROP_INTERLEAVE_TIME:
6096 g_value_set_uint64 (value, qtmux->interleave_time);
6098 case PROP_MAX_RAW_AUDIO_DRIFT:
6099 g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6102 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6105 GST_OBJECT_UNLOCK (qtmux);
6109 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6113 g_free (qtmux->fast_start_file_path);
6114 qtmux->fast_start_file_path = NULL;
6116 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6117 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6122 gst_qt_mux_set_property (GObject * object,
6123 guint prop_id, const GValue * value, GParamSpec * pspec)
6125 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6127 GST_OBJECT_LOCK (qtmux);
6129 case PROP_MOVIE_TIMESCALE:
6130 qtmux->timescale = g_value_get_uint (value);
6132 case PROP_TRAK_TIMESCALE:
6133 qtmux->trak_timescale = g_value_get_uint (value);
6136 qtmux->guess_pts = g_value_get_boolean (value);
6138 #ifndef GST_REMOVE_DEPRECATED
6139 case PROP_DTS_METHOD:
6140 qtmux->dts_method = g_value_get_enum (value);
6143 case PROP_FAST_START:
6144 qtmux->fast_start = g_value_get_boolean (value);
6146 case PROP_FAST_START_TEMP_FILE:
6147 g_free (qtmux->fast_start_file_path);
6148 qtmux->fast_start_file_path = g_value_dup_string (value);
6149 /* NULL means to generate a random one */
6150 if (!qtmux->fast_start_file_path) {
6151 gst_qt_mux_generate_fast_start_file_path (qtmux);
6154 case PROP_MOOV_RECOV_FILE:
6155 g_free (qtmux->moov_recov_file_path);
6156 qtmux->moov_recov_file_path = g_value_dup_string (value);
6158 case PROP_FRAGMENT_DURATION:
6159 qtmux->fragment_duration = g_value_get_uint (value);
6161 case PROP_STREAMABLE:{
6162 GstQTMuxClass *qtmux_klass =
6163 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6164 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6165 qtmux->streamable = g_value_get_boolean (value);
6169 case PROP_RESERVED_MAX_DURATION:
6170 qtmux->reserved_max_duration = g_value_get_uint64 (value);
6172 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6173 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6175 case PROP_RESERVED_BYTES_PER_SEC:
6176 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6178 case PROP_RESERVED_PREFILL:
6179 qtmux->reserved_prefill = g_value_get_boolean (value);
6181 case PROP_INTERLEAVE_BYTES:
6182 qtmux->interleave_bytes = g_value_get_uint64 (value);
6183 qtmux->interleave_bytes_set = TRUE;
6185 case PROP_INTERLEAVE_TIME:
6186 qtmux->interleave_time = g_value_get_uint64 (value);
6187 qtmux->interleave_time_set = TRUE;
6189 case PROP_MAX_RAW_AUDIO_DRIFT:
6190 qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6193 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6196 GST_OBJECT_UNLOCK (qtmux);
6199 static GstStateChangeReturn
6200 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6202 GstStateChangeReturn ret;
6203 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6205 switch (transition) {
6206 case GST_STATE_CHANGE_NULL_TO_READY:
6208 case GST_STATE_CHANGE_READY_TO_PAUSED:
6209 gst_collect_pads_start (qtmux->collect);
6210 qtmux->state = GST_QT_MUX_STATE_STARTED;
6212 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6214 case GST_STATE_CHANGE_PAUSED_TO_READY:
6215 gst_collect_pads_stop (qtmux->collect);
6221 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6223 switch (transition) {
6224 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6226 case GST_STATE_CHANGE_PAUSED_TO_READY:
6227 gst_qt_mux_reset (qtmux, TRUE);
6229 case GST_STATE_CHANGE_READY_TO_NULL:
6239 gst_qt_mux_register (GstPlugin * plugin)
6241 GTypeInfo typeinfo = {
6242 sizeof (GstQTMuxClass),
6243 (GBaseInitFunc) gst_qt_mux_base_init,
6245 (GClassInitFunc) gst_qt_mux_class_init,
6250 (GInstanceInitFunc) gst_qt_mux_init,
6252 static const GInterfaceInfo tag_setter_info = {
6255 static const GInterfaceInfo tag_xmp_writer_info = {
6258 static const GInterfaceInfo preset_info = {
6262 GstQTMuxFormat format;
6263 GstQTMuxClassParams *params;
6266 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6268 GST_LOG ("Registering muxers");
6271 GstQTMuxFormatProp *prop;
6272 GstCaps *subtitle_caps;
6274 prop = &gst_qt_mux_format_list[i];
6275 format = prop->format;
6276 if (format == GST_QT_MUX_FORMAT_NONE)
6279 /* create a cache for these properties */
6280 params = g_new0 (GstQTMuxClassParams, 1);
6281 params->prop = prop;
6282 params->src_caps = gst_static_caps_get (&prop->src_caps);
6283 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6284 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6285 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6286 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6287 params->subtitle_sink_caps = subtitle_caps;
6289 gst_caps_unref (subtitle_caps);
6292 /* create the type now */
6293 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6295 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6296 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6297 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6298 &tag_xmp_writer_info);
6299 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6301 if (!gst_element_register (plugin, prop->name, prop->rank, type))
6307 GST_LOG ("Finished registering muxers");
6309 /* FIXME: ideally classification tag should be added and
6310 registered in gstreamer core gsttaglist
6313 GST_LOG ("Registering tags");
6315 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6316 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6317 gst_tag_merge_use_first);
6319 GST_LOG ("Finished registering tags");