1 /* Quicktime muxer plugin for GStreamer
2 * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3 * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4 * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5 * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6 * Contact: Stefan Kost <stefan.kost@nokia.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
24 * Unless otherwise indicated, Source Code is licensed under MIT license.
25 * See further explanation attached in License Statement (distributed in the file
28 * Permission is hereby granted, free of charge, to any person obtaining a copy of
29 * this software and associated documentation files (the "Software"), to deal in
30 * the Software without restriction, including without limitation the rights to
31 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32 * of the Software, and to permit persons to whom the Software is furnished to do
33 * so, subject to the following conditions:
35 * The above copyright notice and this permission notice shall be included in all
36 * copies or substantial portions of the Software.
38 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49 * SECTION:element-qtmux
50 * @short_description: Muxer for quicktime(.mov) files
52 * This element merges streams (audio and video) into QuickTime(.mov) files.
54 * The following background intends to explain why various similar muxers
55 * are present in this plugin.
57 * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58 * QuickTime file format specification</ulink> served as basis for the MP4 file
59 * format specification (mp4mux), and as such the QuickTime file structure is
60 * nearly identical to the so-called ISO Base Media file format defined in
61 * ISO 14496-12 (except for some media specific parts).
62 * In turn, the latter ISO Base Media format was further specialized as a
63 * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64 * and in various 3GPP(2) specs (gppmux).
65 * The fragmented file features defined (only) in ISO Base Media are used by
66 * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
68 * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale) allow
69 * adjusting some technical parameters, which might be useful in (rare) cases to
70 * resolve compatibility issues in some situations.
72 * Some other properties influence the result more fundamentally.
73 * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
74 * file, somewhat contrary to this usually being called "the header".
75 * However, a #GstQTMux:faststart file will (with some effort) arrange this to
76 * be located near start of the file, which then allows it e.g. to be played
77 * while downloading. Alternatively, rather than having one chunk of metadata at
78 * start (or end), there can be some metadata at start and most of the other
79 * data can be spread out into fragments of #GstQTMux:fragment-duration.
80 * If such fragmented layout is intended for streaming purposes, then
81 * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
84 * When the maximum duration to be recorded can be known in advance, #GstQTMux
85 * also supports a 'Robust Muxing' mode. In robust muxing mode, space for the
86 * headers are reserved at the start of muxing, and rewritten at a configurable
87 * interval, so that the output file is always playable, even if the recording
88 * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
89 * output, such as filesink, because it needs to rewrite the start of the file.
91 * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
92 * and #GstQTMux::reserved-max-duration property. Also present is the
93 * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
94 * for some reason the default is not large enough and the initial reserved
95 * space for headers is too small. Applications can monitor the
96 * #GstQTMux::reserved-duration-remaining property to see how close to full
97 * the reserved space is becoming.
100 * <title>Example pipelines</title>
102 * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
104 * Records a video stream captured from a v4l2 device and muxes it into a qt file.
116 #include <glib/gstdio.h>
119 #include <gst/base/gstcollectpads.h>
120 #include <gst/base/gstbytereader.h>
121 #include <gst/base/gstbitreader.h>
122 #include <gst/audio/audio.h>
123 #include <gst/video/video.h>
124 #include <gst/tag/tag.h>
125 #include <gst/pbutils/pbutils.h>
127 #include <sys/types.h>
129 #include <io.h> /* lseek, open, close, read */
131 #define lseek _lseeki64
133 #define off_t guint64
137 #define ftruncate g_win32_ftruncate
144 #include "gstqtmux.h"
146 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
147 #define GST_CAT_DEFAULT gst_qt_mux_debug
151 * The basic building blocks of MP4 files are:
152 * - an 'ftyp' box at the very start
153 * - an 'mdat' box which contains the raw audio/video/subtitle data;
154 * this is just a bunch of bytes, completely unframed and possibly
155 * unordered with no additional meta-information
156 * - a 'moov' box that contains information about the different streams
157 * and what they contain, as well as sample tables for each stream
158 * that tell the demuxer where in the mdat box each buffer/sample is
159 * and what its duration/timestamp etc. is, and whether it's a
161 * Additionally, fragmented MP4 works by writing chunks of data in
162 * pairs of 'moof' and 'mdat' boxes:
163 * - 'moof' boxes, header preceding each mdat fragment describing the
164 * contents, like a moov but only for that fragment.
165 * - a 'mfra' box for Fragmented MP4, which is written at the end and
166 * contains a summary of all fragments and seek tables.
168 * Currently mp4mux can work in 4 different modes / generate 4 types
169 * of output files/streams:
171 * - Normal mp4: mp4mux will write a little ftyp identifier at the
172 * beginning, then start an mdat box into which it will write all the
173 * sample data. At EOS it will then write the moov header with track
174 * headers and sample tables at the end of the file, and rewrite the
175 * start of the file to fix up the mdat box size at the beginning.
176 * It has to wait for EOS to write the moov (which includes the
177 * sample tables) because it doesn't know how much space those
178 * tables will be. The output downstream must be seekable to rewrite
179 * the mdat box at EOS.
181 * - Fragmented mp4: moov header with track headers at start
182 * but no sample table, followed by N fragments, each containing
183 * track headers with sample tables followed by some data. Downstream
184 * does not need to be seekable if the 'streamable' flag is TRUE,
185 * as the final mfra and total duration will be omitted.
187 * - Fast-start mp4: the goal here is to create a file where the moov
188 * headers are at the beginning; what mp4mux will do is write all
189 * sample data into a temp file and build moov header plus sample
190 * tables in memory and then when EOS comes, it will push out the
191 * moov header plus sample tables at the beginning, followed by the
192 * mdat sample data at the end which is read in from the temp file
193 * Files created in this mode are better for streaming over the
194 * network, since the client doesn't have to seek to the end of the
195 * file to get the headers, but it requires copying all sample data
196 * out of the temp file at EOS, which can be expensive. Downstream does
197 * not need to be seekable, because of the use of the temp file.
199 * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
200 * and reserved-moov-update-period properties to reserve free space
201 * at the start of the file and periodically write the MOOV atom out
202 * to it. That means that killing the muxing at any point still
203 * results in a playable file, at the cost of wasting some amount of
204 * free space at the start of file. The approximate recording duration
205 * has to be known in advance to estimate how much free space to reserve
206 * for the moov, and the downstream must be seekable.
207 * If the moov header grows larger than the reserved space, an error
208 * is generated - so it's better to over-estimate the amount of space
209 * to reserve. To ensure the file is playable at any point, the moov
210 * is updated using a 'ping-pong' strategy, so the output is never in
214 #ifndef GST_REMOVE_DEPRECATED
223 gst_qt_mux_dts_method_get_type (void)
225 static GType gst_qt_mux_dts_method = 0;
227 if (!gst_qt_mux_dts_method) {
228 static const GEnumValue dts_methods[] = {
229 {DTS_METHOD_DD, "delta/duration", "dd"},
230 {DTS_METHOD_REORDER, "reorder", "reorder"},
231 {DTS_METHOD_ASC, "ascending", "asc"},
235 gst_qt_mux_dts_method =
236 g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
239 return gst_qt_mux_dts_method;
242 #define GST_TYPE_QT_MUX_DTS_METHOD \
243 (gst_qt_mux_dts_method_get_type ())
246 /* QTMux signals and args */
256 PROP_MOVIE_TIMESCALE,
259 PROP_FAST_START_TEMP_FILE,
260 PROP_MOOV_RECOV_FILE,
261 PROP_FRAGMENT_DURATION,
263 PROP_RESERVED_MAX_DURATION,
264 PROP_RESERVED_DURATION_REMAINING,
265 PROP_RESERVED_MOOV_UPDATE_PERIOD,
266 PROP_RESERVED_BYTES_PER_SEC,
267 #ifndef GST_REMOVE_DEPRECATED
273 /* some spare for header size as well */
274 #define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
276 #define DEFAULT_MOVIE_TIMESCALE 1800
277 #define DEFAULT_TRAK_TIMESCALE 0
278 #define DEFAULT_DO_CTTS TRUE
279 #define DEFAULT_FAST_START FALSE
280 #define DEFAULT_FAST_START_TEMP_FILE NULL
281 #define DEFAULT_MOOV_RECOV_FILE NULL
282 #define DEFAULT_FRAGMENT_DURATION 0
283 #define DEFAULT_STREAMABLE TRUE
284 #ifndef GST_REMOVE_DEPRECATED
285 #define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
287 #define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
288 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
289 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
291 static void gst_qt_mux_finalize (GObject * object);
293 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
294 GstStateChange transition);
296 /* property functions */
297 static void gst_qt_mux_set_property (GObject * object,
298 guint prop_id, const GValue * value, GParamSpec * pspec);
299 static void gst_qt_mux_get_property (GObject * object,
300 guint prop_id, GValue * value, GParamSpec * pspec);
303 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
304 GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
305 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
308 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
309 GstCollectData * data, GstEvent * event, gpointer user_data);
311 static GstFlowReturn gst_qt_mux_handle_buffer (GstCollectPads * pads,
312 GstCollectData * cdata, GstBuffer * buf, gpointer user_data);
313 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
317 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
319 static GstElementClass *parent_class = NULL;
322 gst_qt_mux_base_init (gpointer g_class)
324 GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
325 GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
326 GstQTMuxClassParams *params;
327 GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
328 GstPadTemplate *srctempl;
329 gchar *longname, *description;
332 (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
333 GST_QT_MUX_PARAMS_QDATA);
334 g_assert (params != NULL);
336 /* construct the element details struct */
337 longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
338 description = g_strdup_printf ("Multiplex audio and video into a %s file",
339 params->prop->long_name);
340 gst_element_class_set_static_metadata (element_class, longname,
341 "Codec/Muxer", description,
342 "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
344 g_free (description);
347 srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
348 GST_PAD_ALWAYS, params->src_caps);
349 gst_element_class_add_pad_template (element_class, srctempl);
351 if (params->audio_sink_caps) {
352 audiosinktempl = gst_pad_template_new ("audio_%u",
353 GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
354 gst_element_class_add_pad_template (element_class, audiosinktempl);
357 if (params->video_sink_caps) {
358 videosinktempl = gst_pad_template_new ("video_%u",
359 GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
360 gst_element_class_add_pad_template (element_class, videosinktempl);
363 if (params->subtitle_sink_caps) {
364 subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
365 GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
366 gst_element_class_add_pad_template (element_class, subtitlesinktempl);
369 klass->format = params->prop->format;
373 gst_qt_mux_class_init (GstQTMuxClass * klass)
375 GObjectClass *gobject_class;
376 GstElementClass *gstelement_class;
377 GParamFlags streamable_flags;
378 const gchar *streamable_desc;
380 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
381 "be streamed and hence no indexes written or duration written."
383 gobject_class = (GObjectClass *) klass;
384 gstelement_class = (GstElementClass *) klass;
386 parent_class = g_type_class_peek_parent (klass);
388 gobject_class->finalize = gst_qt_mux_finalize;
389 gobject_class->get_property = gst_qt_mux_get_property;
390 gobject_class->set_property = gst_qt_mux_set_property;
392 streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
393 if (klass->format == GST_QT_MUX_FORMAT_ISML) {
394 streamable_desc = STREAMABLE_DESC;
395 streamable = DEFAULT_STREAMABLE;
398 STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
399 streamable_flags |= G_PARAM_DEPRECATED;
403 g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
404 g_param_spec_uint ("movie-timescale", "Movie timescale",
405 "Timescale to use in the movie (units per second)",
406 1, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
407 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
408 g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
409 g_param_spec_uint ("trak-timescale", "Track timescale",
410 "Timescale to use for the tracks (units per second, 0 is automatic)",
411 0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
412 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
413 g_object_class_install_property (gobject_class, PROP_DO_CTTS,
414 g_param_spec_boolean ("presentation-time",
415 "Include presentation-time info",
416 "Calculate and include presentation/composition time "
417 "(in addition to decoding time)", DEFAULT_DO_CTTS,
418 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
419 #ifndef GST_REMOVE_DEPRECATED
420 g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
421 g_param_spec_enum ("dts-method", "dts-method",
422 "Method to determine DTS time (DEPRECATED)",
423 GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
424 G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
425 G_PARAM_STATIC_STRINGS));
427 g_object_class_install_property (gobject_class, PROP_FAST_START,
428 g_param_spec_boolean ("faststart", "Format file to faststart",
429 "If the file should be formatted for faststart (headers first)",
430 DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
431 g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
432 g_param_spec_string ("faststart-file", "File to use for storing buffers",
433 "File that will be used temporarily to store data from the stream "
434 "when creating a faststart file. If null a filepath will be "
435 "created automatically", DEFAULT_FAST_START_TEMP_FILE,
436 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
437 g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
438 g_param_spec_string ("moov-recovery-file",
439 "File to store data for posterior moov atom recovery",
440 "File to be used to store "
441 "data for moov atom making movie file recovery possible in case "
442 "of a crash during muxing. Null for disabled. (Experimental)",
443 DEFAULT_MOOV_RECOV_FILE,
444 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
445 g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
446 g_param_spec_uint ("fragment-duration", "Fragment duration",
447 "Fragment durations in ms (produce a fragmented file if > 0)",
448 0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
449 2000 : DEFAULT_FRAGMENT_DURATION,
450 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
451 g_object_class_install_property (gobject_class, PROP_STREAMABLE,
452 g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
453 streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
454 g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
455 g_param_spec_uint64 ("reserved-max-duration",
456 "Reserved maximum file duration (ns)",
457 "When set to a value > 0, reserves space for index tables at the "
458 "beginning of the file.",
459 0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
460 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
461 g_object_class_install_property (gobject_class,
462 PROP_RESERVED_DURATION_REMAINING,
463 g_param_spec_uint64 ("reserved-duration-remaining",
464 "Report the approximate amount of remaining recording space (ns)",
465 "Reports the approximate amount of remaining moov header space "
466 "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
467 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
468 g_object_class_install_property (gobject_class,
469 PROP_RESERVED_MOOV_UPDATE_PERIOD,
470 g_param_spec_uint64 ("reserved-moov-update-period",
471 "Interval at which to update index tables (ns)",
472 "When used with reserved-max-duration, periodically updates the "
473 "index tables with information muxed so far.", 0, G_MAXUINT64,
474 DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
475 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
476 g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
477 g_param_spec_uint ("reserved-bytes-per-sec",
478 "Reserved MOOV bytes per second, per track",
479 "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
480 0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
481 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
483 gstelement_class->request_new_pad =
484 GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
485 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
486 gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
490 gst_qt_mux_pad_reset (GstQTPad * qtpad)
493 qtpad->is_out_of_order = FALSE;
494 qtpad->sample_size = 0;
497 qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
498 qtpad->first_ts = GST_CLOCK_TIME_NONE;
499 qtpad->first_dts = GST_CLOCK_TIME_NONE;
500 qtpad->prepare_buf_func = NULL;
501 qtpad->create_empty_buffer = NULL;
502 qtpad->avg_bitrate = 0;
503 qtpad->max_bitrate = 0;
504 qtpad->total_duration = 0;
505 qtpad->total_bytes = 0;
506 qtpad->sparse = FALSE;
507 qtpad->tc_trak = NULL;
512 gst_buffer_replace (&qtpad->last_buf, NULL);
515 gst_tag_list_unref (qtpad->tags);
519 /* reference owned elsewhere */
523 atom_traf_free (qtpad->traf);
526 atom_array_clear (&qtpad->fragment_buffers);
528 /* reference owned elsewhere */
533 * Takes GstQTMux back to its initial state
536 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
540 qtmux->state = GST_QT_MUX_STATE_NONE;
541 qtmux->header_size = 0;
542 qtmux->mdat_size = 0;
545 qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
546 qtmux->video_pads = 0;
547 qtmux->audio_pads = 0;
548 qtmux->fragment_sequence = 0;
551 atom_ftyp_free (qtmux->ftyp);
555 atom_moov_free (qtmux->moov);
559 atom_mfra_free (qtmux->mfra);
562 if (qtmux->fast_start_file) {
563 fclose (qtmux->fast_start_file);
564 g_remove (qtmux->fast_start_file_path);
565 qtmux->fast_start_file = NULL;
567 if (qtmux->moov_recov_file) {
568 fclose (qtmux->moov_recov_file);
569 qtmux->moov_recov_file = NULL;
571 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
572 AtomInfo *ainfo = (AtomInfo *) walk->data;
573 ainfo->free_func (ainfo->atom);
576 g_slist_free (qtmux->extra_atoms);
577 qtmux->extra_atoms = NULL;
579 GST_OBJECT_LOCK (qtmux);
580 gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
581 GST_OBJECT_UNLOCK (qtmux);
584 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
585 GstQTPad *qtpad = (GstQTPad *) walk->data;
586 gst_qt_mux_pad_reset (qtpad);
588 /* hm, moov_free above yanked the traks away from us,
589 * so do not free, but do clear */
594 qtmux->moov = atom_moov_new (qtmux->context);
595 /* ensure all is as nice and fresh as request_new_pad would provide it */
596 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
597 GstQTPad *qtpad = (GstQTPad *) walk->data;
599 qtpad->trak = atom_trak_new (qtmux->context);
600 atom_moov_add_trak (qtmux->moov, qtpad->trak);
604 qtmux->reserved_moov_size = 0;
605 qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
606 qtmux->muxed_since_last_update = 0;
607 qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
608 qtmux->first_pts = GST_CLOCK_TIME_NONE;
613 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
615 GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
616 GstPadTemplate *templ;
618 templ = gst_element_class_get_pad_template (klass, "src");
619 qtmux->srcpad = gst_pad_new_from_template (templ, "src");
620 gst_pad_use_fixed_caps (qtmux->srcpad);
621 gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
623 qtmux->sinkpads = NULL;
624 qtmux->collect = gst_collect_pads_new ();
625 gst_collect_pads_set_buffer_function (qtmux->collect,
626 GST_DEBUG_FUNCPTR (gst_qt_mux_handle_buffer), qtmux);
627 gst_collect_pads_set_event_function (qtmux->collect,
628 GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
629 gst_collect_pads_set_clip_function (qtmux->collect,
630 GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
632 /* properties set to default upon construction */
634 qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
635 qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
636 qtmux->reserved_bytes_per_sec_per_trak =
637 DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
639 /* always need this */
641 atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
643 /* internals to initial state */
644 gst_qt_mux_reset (qtmux, TRUE);
649 gst_qt_mux_finalize (GObject * object)
651 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
653 gst_qt_mux_reset (qtmux, FALSE);
655 g_free (qtmux->fast_start_file_path);
656 g_free (qtmux->moov_recov_file_path);
658 atoms_context_free (qtmux->context);
659 gst_object_unref (qtmux->collect);
661 g_slist_free (qtmux->sinkpads);
663 G_OBJECT_CLASS (parent_class)->finalize (object);
667 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
674 GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
679 size = gst_buffer_get_size (buf);
680 newbuf = gst_buffer_new_and_alloc (size + 8);
681 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
683 gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
684 GST_WRITE_UINT32_BE (map.data, map.size);
685 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
687 gst_buffer_unmap (buf, &map);
688 gst_buffer_unref (buf);
694 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
701 const guint8 *dataend;
703 GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
708 gst_buffer_map (buf, &frommap, GST_MAP_READ);
710 dataend = memchr (frommap.data, 0, frommap.size);
711 size = dataend ? dataend - frommap.data : frommap.size;
712 newbuf = gst_buffer_new_and_alloc (size + 2);
714 gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
716 GST_WRITE_UINT16_BE (tomap.data, size);
717 memcpy (tomap.data + 2, frommap.data, size);
719 gst_buffer_unmap (newbuf, &tomap);
720 gst_buffer_unmap (buf, &frommap);
722 gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
724 /* gst_buffer_copy_into is trying to be too clever and
725 * won't copy duration when size is different */
726 GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
728 gst_buffer_unref (buf);
734 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
735 guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
740 g_return_if_fail (qtpad->trak_ste);
742 ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
744 sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
748 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
752 GstByteReader reader;
755 if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
756 GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
760 if (G_UNLIKELY (map.size < 8))
763 gst_byte_reader_init (&reader, map.data, map.size);
764 off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
769 guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
771 GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
774 gst_bit_reader_init (&bits, map.data, map.size);
776 /* off + sync + crc */
777 gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
779 fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
780 frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
781 bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
782 bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
783 acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
785 if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
786 gst_bit_reader_skip_unchecked (&bits, 2);
787 if ((acmod & 0x4)) /* if a surround channel exists */
788 gst_bit_reader_skip_unchecked (&bits, 2);
789 if (acmod == 0x2) /* if in 2/0 mode */
790 gst_bit_reader_skip_unchecked (&bits, 2);
792 lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
794 gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
795 bsmod, acmod, lfe_on);
797 /* AC-3 spec says that those values should be constant for the
798 * whole stream when muxed in mp4. We trust the input follows it */
799 GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
800 "prepare buffer function");
801 qtpad->prepare_buf_func = NULL;
805 gst_buffer_unmap (buf, &map);
810 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
815 GST_WRITE_UINT16_BE (data, 0);
817 return gst_buffer_new_wrapped (data, 2);
821 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
822 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
824 switch (gst_tag_get_type (tag)) {
830 if (!gst_tag_list_get_string (list, tag, &str) || !str)
832 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
833 GST_FOURCC_ARGS (fourcc), str);
834 atom_udta_add_str_tag (udta, fourcc, str);
843 if (!gst_tag_list_get_double (list, tag, &value))
845 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
846 GST_FOURCC_ARGS (fourcc), (gint) value);
847 atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
854 /* paired unsigned integers */
858 got_tag = gst_tag_list_get_uint (list, tag, &value);
859 got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
862 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
863 GST_FOURCC_ARGS (fourcc), value, count);
864 atom_udta_add_uint_tag (udta, fourcc, 0,
865 value << 16 | (count & 0xFFFF));
867 /* unpaired unsigned integers */
868 if (!gst_tag_list_get_uint (list, tag, &value))
870 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
871 GST_FOURCC_ARGS (fourcc), value);
872 atom_udta_add_uint_tag (udta, fourcc, 1, value);
877 g_assert_not_reached ();
883 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
884 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
892 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
894 if (!gst_tag_list_get_date (list, tag, &date) || !date)
897 year = g_date_get_year (date);
898 month = g_date_get_month (date);
899 day = g_date_get_day (date);
903 if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
904 day == G_DATE_BAD_DAY) {
905 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
909 str = g_strdup_printf ("%u-%u-%u", year, month, day);
910 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
911 GST_FOURCC_ARGS (fourcc), str);
912 atom_udta_add_str_tag (udta, fourcc, str);
917 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
918 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
920 GValue value = { 0, };
924 GstStructure *structure;
928 g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
930 if (!gst_tag_list_copy_value (&value, list, tag))
933 sample = gst_value_get_sample (&value);
938 buf = gst_sample_get_buffer (sample);
942 caps = gst_sample_get_caps (sample);
944 GST_WARNING_OBJECT (qtmux, "preview image without caps");
948 GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
950 structure = gst_caps_get_structure (caps, 0);
951 if (gst_structure_has_name (structure, "image/jpeg"))
953 else if (gst_structure_has_name (structure, "image/png"))
957 GST_WARNING_OBJECT (qtmux, "preview image format not supported");
961 gst_buffer_map (buf, &map, GST_MAP_READ);
962 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
963 " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
964 atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
965 gst_buffer_unmap (buf, &map);
967 g_value_unset (&value);
971 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
972 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
977 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
978 g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
980 if (!gst_tag_list_get_string (list, tag, &str) || !str)
984 if (!gst_tag_list_get_uint (list, tag2, &number))
988 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
989 GST_FOURCC_ARGS (fourcc), str);
990 atom_udta_add_3gp_str_tag (udta, fourcc, str);
992 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
993 GST_FOURCC_ARGS (fourcc), str, number);
994 atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1001 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1002 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1007 g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1009 if (!gst_tag_list_get_date (list, tag, &date) || !date)
1012 year = g_date_get_year (date);
1015 if (year == G_DATE_BAD_YEAR) {
1016 GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1020 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1021 GST_FOURCC_ARGS (fourcc), year);
1022 atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1026 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1027 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1029 gdouble latitude = -360, longitude = -360, altitude = 0;
1030 gchar *location = NULL;
1031 guint8 *data, *ddata;
1032 gint size = 0, len = 0;
1033 gboolean ret = FALSE;
1035 g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1037 ret = gst_tag_list_get_string (list, tag, &location);
1038 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1040 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1042 ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1049 len = strlen (location);
1050 size += len + 1 + 2;
1052 /* role + (long, lat, alt) + body + notes */
1053 size += 1 + 3 * 4 + 1 + 1;
1055 data = ddata = g_malloc (size);
1058 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1061 memcpy (data + 2, location, len);
1062 GST_WRITE_UINT8 (data + 2 + len, 0);
1063 data += len + 1 + 2;
1065 GST_WRITE_UINT8 (data, 0);
1066 /* long, lat, alt */
1067 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1068 QT_WRITE_SFP32 (data + 1, longitude);
1069 QT_WRITE_SFP32 (data + 5, latitude);
1070 QT_WRITE_SFP32 (data + 9, altitude);
1071 /* neither astronomical body nor notes */
1072 GST_WRITE_UINT16_BE (data + 13, 0);
1074 GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1075 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1080 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1081 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1083 gchar *keywords = NULL;
1084 guint8 *data, *ddata;
1088 g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1090 if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1093 kwds = g_strsplit (keywords, ",", 0);
1097 for (i = 0; kwds[i]; i++) {
1098 /* size byte + null-terminator */
1099 size += strlen (kwds[i]) + 1 + 1;
1102 /* language tag + count + keywords */
1105 data = ddata = g_malloc (size);
1108 GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1110 GST_WRITE_UINT8 (data + 2, i);
1113 for (i = 0; kwds[i]; ++i) {
1114 gint len = strlen (kwds[i]);
1116 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1117 GST_FOURCC_ARGS (fourcc), kwds[i]);
1119 GST_WRITE_UINT8 (data, len + 1);
1120 memcpy (data + 1, kwds[i], len + 1);
1126 atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1131 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1132 guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1140 size = strlen (input);
1142 if (size < 4 + 3 + 1 + 1 + 1) {
1143 /* at least the minimum xxxx://y/z */
1144 GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1149 /* read the fourcc */
1150 memcpy (&fourcc, data, 4);
1154 if (strncmp (data, "://", 3) != 0) {
1160 /* read the table number */
1161 if (sscanf (data, "%d", &table) != 1) {
1165 GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1166 ", table numbers should be positive, ignoring tag", table);
1170 /* find the next / */
1171 while (size > 0 && data[0] != '/') {
1178 g_assert (data[0] == '/');
1187 /* read up the rest of the string */
1188 *p_content = g_strdup (data);
1189 *p_table = (guint16) table;
1195 GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1196 "input (%s) didn't match the expected entitycode://table/content",
1203 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1204 AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1206 gchar *clsf_data = NULL;
1210 gchar *content = NULL;
1213 g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1215 if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1218 GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1219 GST_FOURCC_ARGS (fourcc), clsf_data);
1221 /* parse the string, format is:
1222 * entityfourcc://table/content
1224 gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1228 size = strlen (content) + 1;
1230 /* now we have everything, build the atom
1231 * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1232 data = g_malloc (4 + 2 + 2 + size);
1233 GST_WRITE_UINT32_LE (data, entity);
1234 GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1235 GST_WRITE_UINT16_BE (data + 6, 0);
1236 memcpy (data + 8, content, size);
1239 atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1243 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1244 const GstTagList * list, AtomUDTA * udta, const char *tag,
1245 const char *tag2, guint32 fourcc);
1248 * Struct to record mappings from gstreamer tags to fourcc codes
1250 typedef struct _GstTagToFourcc
1253 const gchar *gsttag;
1254 const gchar *gsttag2;
1255 const GstQTMuxAddUdtaTagFunc func;
1258 /* tag list tags to fourcc matching */
1259 static const GstTagToFourcc tag_matches_mp4[] = {
1260 {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1261 {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1262 {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1263 {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1264 {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1265 {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1266 {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1267 {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1268 {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1269 {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1270 {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1271 {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1272 {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1273 {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1274 {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1275 {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1276 {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1277 {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1278 {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1279 {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1280 {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1281 {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1282 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1283 {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1284 {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1285 {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1286 {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1287 gst_qt_mux_add_mp4_tag},
1288 {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1289 gst_qt_mux_add_mp4_tag},
1290 {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1291 {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1295 static const GstTagToFourcc tag_matches_3gp[] = {
1296 {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1297 {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1298 {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1299 {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1300 {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1301 {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1302 {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1303 {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1304 {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1305 {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1306 {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1307 gst_qt_mux_add_3gp_classification},
1311 /* qtdemux produces these for atoms it cannot parse */
1312 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1315 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1317 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1318 GstBuffer *xmp = NULL;
1320 /* adobe specs only have 'quicktime' and 'mp4',
1321 * but I guess we can extrapolate to gpp.
1322 * Keep mj2 out for now as we don't add any tags for it yet.
1323 * If you have further info about xmp on these formats, please share */
1324 if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1327 GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1329 if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1330 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1333 atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1336 /* for isom/mp4, it is a top level uuid atom */
1337 xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1340 ainfo = build_uuid_xmp_atom (xmp);
1342 qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1347 gst_buffer_unref (xmp);
1351 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1354 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1357 const gchar *tag, *tag2;
1358 const GstTagToFourcc *tag_matches;
1360 switch (qtmux_klass->format) {
1361 case GST_QT_MUX_FORMAT_3GP:
1362 tag_matches = tag_matches_3gp;
1364 case GST_QT_MUX_FORMAT_MJ2:
1368 /* sort of iTunes style for mp4 and QT (?) */
1369 tag_matches = tag_matches_mp4;
1376 /* Clear existing tags so we don't add them over and over */
1377 atom_udta_clear_tags (udta);
1379 for (i = 0; tag_matches[i].fourcc; i++) {
1380 fourcc = tag_matches[i].fourcc;
1381 tag = tag_matches[i].gsttag;
1382 tag2 = tag_matches[i].gsttag2;
1384 g_assert (tag_matches[i].func);
1385 tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1388 /* add unparsed blobs if present */
1389 if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1392 num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1393 for (i = 0; i < num_tags; ++i) {
1394 GstSample *sample = NULL;
1396 const GstStructure *s;
1398 if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1401 buf = gst_sample_get_buffer (sample);
1403 if (buf && (s = gst_sample_get_info (sample))) {
1404 const gchar *style = NULL;
1407 gst_buffer_map (buf, &map, GST_MAP_READ);
1408 GST_DEBUG_OBJECT (qtmux,
1409 "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1410 GST_PTR_FORMAT, i, num_tags, map.size, s);
1411 if (s && (style = gst_structure_get_string (s, "style"))) {
1412 /* try to prevent some style tag ending up into another variant
1413 * (todo: make into a list if more cases) */
1414 if ((strcmp (style, "itunes") == 0 &&
1415 qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1416 (strcmp (style, "iso") == 0 &&
1417 qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1418 GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1419 atom_udta_add_blob_tag (udta, map.data, map.size);
1422 gst_buffer_unmap (buf, &map);
1424 gst_sample_unref (sample);
1432 * Gets the tagsetter iface taglist and puts the known tags
1433 * into the output stream
1436 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1438 const GstTagList *tags = NULL;
1441 GST_OBJECT_LOCK (qtmux);
1442 if (qtmux->tags_changed) {
1443 tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1444 qtmux->tags_changed = FALSE;
1446 GST_OBJECT_UNLOCK (qtmux);
1448 GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1450 if (tags && !gst_tag_list_is_empty (tags)) {
1451 GstTagList *copy = gst_tag_list_copy (tags);
1453 GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1454 gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1455 gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1456 gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1458 GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1459 gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1460 gst_qt_mux_add_xmp_tags (qtmux, copy);
1461 gst_tag_list_unref (copy);
1463 GST_DEBUG_OBJECT (qtmux, "No new tags received");
1466 for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1467 GstCollectData *cdata = (GstCollectData *) walk->data;
1468 GstQTPad *qpad = (GstQTPad *) cdata;
1469 GstPad *pad = qpad->collect.pad;
1471 if (qpad->tags_changed && qpad->tags) {
1472 GST_DEBUG_OBJECT (pad, "Adding tags");
1473 gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1474 gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1475 qpad->tags_changed = FALSE;
1476 GST_DEBUG_OBJECT (pad, "Tags added");
1478 GST_DEBUG_OBJECT (pad, "No new tags received");
1483 static inline GstBuffer *
1484 _gst_buffer_new_take_data (guint8 * data, guint size)
1488 buf = gst_buffer_new ();
1489 gst_buffer_append_memory (buf,
1490 gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1495 static GstFlowReturn
1496 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1502 g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1504 size = gst_buffer_get_size (buf);
1505 GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1507 if (mind_fast && qtmux->fast_start_file) {
1511 GST_LOG_OBJECT (qtmux, "to temporary file");
1512 gst_buffer_map (buf, &map, GST_MAP_READ);
1513 ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1514 gst_buffer_unmap (buf, &map);
1515 gst_buffer_unref (buf);
1521 GST_LOG_OBJECT (qtmux, "downstream");
1522 res = gst_pad_push (qtmux->srcpad, buf);
1525 if (G_LIKELY (offset))
1533 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1534 ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1535 return GST_FLOW_ERROR;
1540 gst_qt_mux_seek_to_beginning (FILE * f)
1543 if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1545 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1546 if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1549 if (fseek (f, (long) 0, SEEK_SET) != 0)
1555 static GstFlowReturn
1556 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1558 GstFlowReturn ret = GST_FLOW_OK;
1559 GstBuffer *buf = NULL;
1561 if (fflush (qtmux->fast_start_file))
1564 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1567 /* hm, this could all take a really really long time,
1568 * but there may not be another way to get moov atom first
1569 * (somehow optimize copy?) */
1570 GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1571 while (ret == GST_FLOW_OK) {
1572 const int bufsize = 4096;
1576 buf = gst_buffer_new_and_alloc (bufsize);
1577 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1578 size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1580 gst_buffer_unmap (buf, &map);
1583 GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1584 gst_buffer_unmap (buf, &map);
1585 if (size != bufsize)
1586 gst_buffer_set_size (buf, size);
1587 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1591 gst_buffer_unref (buf);
1593 if (ftruncate (fileno (qtmux->fast_start_file), 0))
1595 if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1603 GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1604 ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1605 ret = GST_FLOW_ERROR;
1610 GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1611 ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1612 ret = GST_FLOW_ERROR;
1617 /* clear descriptor so we don't remove temp file later on,
1618 * might be possible to recover */
1619 fclose (qtmux->fast_start_file);
1620 qtmux->fast_start_file = NULL;
1626 * Sends the initial mdat atom fields (size fields and fourcc type),
1627 * the subsequent buffers are considered part of it's data.
1628 * As we can't predict the amount of data that we are going to place in mdat
1629 * we need to record the position of the size field in the stream so we can
1630 * seek back to it later and update when the streams have finished.
1632 static GstFlowReturn
1633 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1634 gboolean extended, gboolean fsync_after)
1639 GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1640 "size %" G_GUINT64_FORMAT, size);
1642 /* if the qtmux state is EOS, really write the mdat, otherwise
1643 * allow size == 0 for a placeholder atom */
1644 if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1648 gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1649 /* Always write 16-bytes, but put a free atom first
1650 * if the size is < 4GB. */
1651 buf = gst_buffer_new_and_alloc (16);
1652 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1655 /* Write extended mdat header and large_size field */
1656 GST_WRITE_UINT32_BE (map.data, 1);
1657 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1658 GST_WRITE_UINT64_BE (map.data + 8, size + 8);
1660 /* Write an empty free atom, then standard 32-bit mdat */
1661 GST_WRITE_UINT32_BE (map.data, 8);
1662 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
1663 GST_WRITE_UINT32_BE (map.data + 8, size);
1664 GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
1666 gst_buffer_unmap (buf, &map);
1668 buf = gst_buffer_new_and_alloc (8);
1669 gst_buffer_map (buf, &map, GST_MAP_WRITE);
1671 /* Vanilla 32-bit mdat */
1672 GST_WRITE_UINT32_BE (map.data, size);
1673 GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
1674 gst_buffer_unmap (buf, &map);
1677 GST_LOG_OBJECT (qtmux, "Pushing mdat header");
1679 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1681 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1686 * We get the position of the mdat size field, seek back to it
1687 * and overwrite with the real value
1689 static GstFlowReturn
1690 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
1691 guint64 mdat_size, guint64 * offset, gboolean fsync_after)
1695 /* We must have recorded the mdat position for this to work */
1696 g_assert (mdat_pos != 0);
1698 /* seek and rewrite the header */
1699 gst_segment_init (&segment, GST_FORMAT_BYTES);
1700 segment.start = mdat_pos;
1701 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1703 return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
1707 static GstFlowReturn
1708 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
1711 guint64 size = 0, offset = 0;
1712 guint8 *data = NULL;
1714 GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
1716 if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
1717 goto serialize_error;
1719 buf = _gst_buffer_new_take_data (data, offset);
1721 GST_LOG_OBJECT (qtmux, "Pushing ftyp");
1722 return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1727 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1728 ("Failed to serialize ftyp"));
1729 return GST_FLOW_ERROR;
1734 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
1735 GstBuffer ** p_prefix)
1737 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1738 guint32 major, version;
1740 GstBuffer *prefix = NULL;
1741 AtomFTYP *ftyp = NULL;
1743 GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
1745 /* init and send context and ftyp based on current property state */
1746 gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
1747 &version, &comp, qtmux->moov, qtmux->longest_chunk,
1748 qtmux->fast_start_file != NULL);
1749 ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
1756 gst_buffer_unref (prefix);
1761 static GstFlowReturn
1762 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
1764 GstFlowReturn ret = GST_FLOW_OK;
1765 GstBuffer *prefix = NULL;
1767 GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
1769 /* init and send context and ftyp based on current property state */
1771 atom_ftyp_free (qtmux->ftyp);
1774 gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
1776 ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
1777 if (ret != GST_FLOW_OK)
1780 return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
1784 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
1786 GstStructure *structure;
1787 GValue array = { 0 };
1788 GValue value = { 0 };
1789 GstCaps *caps, *tcaps;
1791 tcaps = gst_pad_get_current_caps (mux->srcpad);
1792 caps = gst_caps_copy (tcaps);
1793 gst_caps_unref (tcaps);
1795 structure = gst_caps_get_structure (caps, 0);
1797 g_value_init (&array, GST_TYPE_ARRAY);
1799 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
1800 g_value_init (&value, GST_TYPE_BUFFER);
1801 gst_value_take_buffer (&value, gst_buffer_ref (buf));
1802 gst_value_array_append_value (&array, &value);
1803 g_value_unset (&value);
1805 gst_structure_set_value (structure, "streamheader", &array);
1806 g_value_unset (&array);
1807 gst_pad_set_caps (mux->srcpad, caps);
1808 gst_caps_unref (caps);
1812 * Write out a free space atom. The offset is adjusted by the full
1813 * size, but a smaller buffer is sent
1815 static GstFlowReturn
1816 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
1817 gboolean fsync_after)
1821 guint8 *data = NULL;
1822 guint64 offset = 0, bsize = 0;
1825 GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
1827 /* We can't make a free space atom smaller than the header */
1831 node_header = g_malloc0 (sizeof (Atom));
1832 node_header->type = FOURCC_free;
1833 node_header->size = size;
1836 if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
1837 goto serialize_error;
1839 buf = _gst_buffer_new_take_data (data, offset);
1840 g_free (node_header);
1843 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1845 GST_LOG_OBJECT (qtmux, "Pushing free atom");
1846 ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
1853 /* Make sure downstream position ends up at the end of this free box */
1854 gst_segment_init (&segment, GST_FORMAT_BYTES);
1855 segment.start = *off;
1856 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
1864 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1865 ("Not enough free reserved space"));
1866 return GST_FLOW_ERROR;
1870 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
1871 ("Failed to serialize mdat"));
1872 g_free (node_header);
1873 return GST_FLOW_ERROR;
1878 gst_qt_mux_configure_moov (GstQTMux * qtmux)
1880 gboolean fragmented = FALSE;
1883 GST_OBJECT_LOCK (qtmux);
1884 timescale = qtmux->timescale;
1885 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
1886 qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
1888 GST_OBJECT_UNLOCK (qtmux);
1890 /* inform lower layers of our property wishes, and determine duration.
1891 * Let moov take care of this using its list of traks;
1892 * so that released pads are also included */
1893 GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
1895 atom_moov_update_timescale (qtmux->moov, timescale);
1896 atom_moov_set_fragmented (qtmux->moov, fragmented);
1898 atom_moov_update_duration (qtmux->moov);
1901 static GstFlowReturn
1902 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
1903 guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
1905 guint64 offset = 0, size = 0;
1908 GstFlowReturn ret = GST_FLOW_OK;
1910 /* serialize moov */
1913 GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
1914 if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
1915 goto serialize_error;
1916 qtmux->last_moov_size = offset;
1918 /* Check we have enough reserved space for this and a Free atom */
1919 if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
1920 goto too_small_reserved;
1921 buf = _gst_buffer_new_take_data (data, offset);
1922 GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
1924 /* If at EOS, this is the final moov, put in the streamheader
1925 * (apparently used by a flumotion util) */
1926 if (qtmux->state == GST_QT_MUX_STATE_EOS)
1927 gst_qt_mux_set_header_on_caps (qtmux, buf);
1930 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
1931 ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
1933 /* Write out a free atom if needed */
1934 if (ret == GST_FLOW_OK && offset < padded_moov_size) {
1935 GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
1936 (guint32) (padded_moov_size - offset));
1938 gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
1945 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
1946 ("Not enough free reserved header space"),
1947 ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
1948 offset, padded_moov_size));
1949 return GST_FLOW_ERROR;
1954 return GST_FLOW_ERROR;
1958 /* either calculates size of extra atoms or pushes them */
1959 static GstFlowReturn
1960 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
1964 guint64 loffset = 0, size = 0;
1966 GstFlowReturn ret = GST_FLOW_OK;
1968 for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
1969 AtomInfo *ainfo = (AtomInfo *) walk->data;
1973 if (!ainfo->copy_data_func (ainfo->atom,
1974 send ? &data : NULL, &size, &loffset))
1975 goto serialize_error;
1980 GST_DEBUG_OBJECT (qtmux,
1981 "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
1982 GST_FOURCC_ARGS (ainfo->atom->type));
1983 buf = _gst_buffer_new_take_data (data, loffset);
1984 ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1985 if (ret != GST_FLOW_OK)
1998 return GST_FLOW_ERROR;
2003 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2005 gboolean seekable = FALSE;
2006 GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2008 if (gst_pad_peer_query (qtmux->srcpad, query)) {
2009 gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2010 GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2012 /* have to assume seeking is not supported if query not handled downstream */
2013 GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2016 gst_query_unref (query);
2022 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2025 gboolean fail = FALSE;
2026 AtomFTYP *ftyp = NULL;
2027 GstBuffer *prefix = NULL;
2029 GST_DEBUG_OBJECT (qtmux, "Openning moov recovery file: %s",
2030 qtmux->moov_recov_file_path);
2032 qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2033 if (qtmux->moov_recov_file == NULL) {
2034 GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2035 qtmux->moov_recov_file_path);
2039 gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2041 if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2042 qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2043 GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2047 atom_ftyp_free (ftyp);
2049 gst_buffer_unref (prefix);
2051 for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2052 GstCollectData *cdata = (GstCollectData *) walk->data;
2053 GstQTPad *qpad = (GstQTPad *) cdata;
2054 /* write info for each stream */
2055 fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2057 GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2065 fclose (qtmux->moov_recov_file);
2066 qtmux->moov_recov_file = NULL;
2067 GST_WARNING_OBJECT (qtmux, "An error was detected while writing to "
2068 "recover file, moov recovery won't work");
2071 static GstFlowReturn
2072 gst_qt_mux_start_file (GstQTMux * qtmux)
2074 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2075 GstFlowReturn ret = GST_FLOW_OK;
2079 GstClockTime reserved_max_duration;
2080 guint reserved_bytes_per_sec_per_trak;
2082 GST_DEBUG_OBJECT (qtmux, "starting file");
2084 GST_OBJECT_LOCK (qtmux);
2085 reserved_max_duration = qtmux->reserved_max_duration;
2086 reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2087 GST_OBJECT_UNLOCK (qtmux);
2089 /* stream-start (FIXME: create id based on input ids) */
2090 g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2091 gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2093 caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2094 /* qtmux has structure with and without variant, remove all but the first */
2095 while (gst_caps_get_size (caps) > 1)
2096 gst_caps_remove_structure (caps, 1);
2097 gst_pad_set_caps (qtmux->srcpad, caps);
2098 gst_caps_unref (caps);
2100 /* Default is 'normal' mode */
2101 qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2103 /* Require a sensible fragment duration when muxing
2104 * using the ISML muxer */
2105 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2106 qtmux->fragment_duration == 0)
2109 if (qtmux->fragment_duration > 0) {
2110 if (qtmux->streamable)
2111 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2113 qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2114 } else if (qtmux->fast_start) {
2115 qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2116 } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2117 qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2120 switch (qtmux->mux_mode) {
2121 case GST_QT_MUX_MODE_MOOV_AT_END:
2122 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2123 /* We have to be able to seek to rewrite the mdat header, or any
2124 * moov atom we write will not be visible in the file, because an
2125 * MDAT with 0 as the size covers the rest of the file. A file
2126 * with no moov is not playable, so error out now. */
2127 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2128 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2129 ("Downstream is not seekable - will not be able to create a playable file"),
2131 return GST_FLOW_ERROR;
2134 case GST_QT_MUX_MODE_FAST_START:
2135 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2136 break; /* Don't need seekability, ignore */
2137 case GST_QT_MUX_MODE_FRAGMENTED:
2138 if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2139 GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2140 "streamable=false. Will ignore that and create streamable output "
2142 qtmux->streamable = TRUE;
2143 g_object_notify (G_OBJECT (qtmux), "streamable");
2148 /* let downstream know we think in BYTES and expect to do seeking later on */
2149 gst_segment_init (&segment, GST_FORMAT_BYTES);
2150 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2152 /* initialize our moov recovery file */
2153 GST_OBJECT_LOCK (qtmux);
2154 if (qtmux->moov_recov_file_path) {
2155 gst_qt_mux_prepare_moov_recovery (qtmux);
2158 /* Make sure the first time we update the moov, we'll
2159 * include any tagsetter tags */
2160 qtmux->tags_changed = TRUE;
2162 GST_OBJECT_UNLOCK (qtmux);
2165 * send mdat header if already needed, and mark position for later update.
2166 * We don't send ftyp now if we are on fast start mode, because we can
2167 * better fine tune using the information we gather to create the whole moov
2170 switch (qtmux->mux_mode) {
2171 case GST_QT_MUX_MODE_MOOV_AT_END:
2172 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2173 if (ret != GST_FLOW_OK)
2176 /* Store this as the mdat offset for later updating
2177 * when we write the moov */
2178 qtmux->mdat_pos = qtmux->header_size;
2179 /* extended atom in case we go over 4GB while writing and need
2180 * the full 64-bit atom */
2182 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2185 case GST_QT_MUX_MODE_ROBUST_RECORDING:
2187 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2188 if (ret != GST_FLOW_OK)
2191 /* Pad ftyp out to an 8-byte boundary before starting the moov
2192 * ping pong region. It should be well less than 1 disk sector,
2193 * unless there's a bajillion compatible types listed,
2194 * but let's be sure the free atom doesn't cross a sector
2195 * boundary anyway */
2196 if (qtmux->header_size % 8) {
2197 /* Extra 8 bytes for the padding free atom header */
2198 guint padding = (guint) (16 - (qtmux->header_size % 8));
2199 GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
2201 gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
2203 if (ret != GST_FLOW_OK)
2207 /* Store this as the moov offset for later updating.
2208 * We record mdat position below */
2209 qtmux->moov_pos = qtmux->header_size;
2211 /* Set up the initial 'ping' state of the ping-pong buffers */
2212 qtmux->reserved_moov_first_active = TRUE;
2214 gst_qt_mux_configure_moov (qtmux);
2215 gst_qt_mux_setup_metadata (qtmux);
2216 /* Empty free atom to begin, starting on an 8-byte boundary */
2217 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
2218 if (ret != GST_FLOW_OK)
2220 /* Moov header, not padded yet */
2221 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2222 if (ret != GST_FLOW_OK)
2224 /* The moov we just sent contains the 'base' size of the moov, before
2225 * we put in any time-dependent per-trak data. Use that to make
2226 * a good estimate of how much extra to reserve */
2227 /* Calculate how much space to reserve for our MOOV atom.
2228 * We actually reserve twice that, for ping-pong buffers */
2229 qtmux->base_moov_size = qtmux->last_moov_size;
2230 GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
2231 qtmux->base_moov_size);
2232 qtmux->reserved_moov_size = qtmux->base_moov_size +
2233 gst_util_uint64_scale (reserved_max_duration,
2234 reserved_bytes_per_sec_per_trak *
2235 atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
2237 /* Need space for at least 4 atom headers. More really, but
2238 * this as an absolute minimum */
2239 if (qtmux->reserved_moov_size < 4 * 8)
2240 goto reserved_moov_too_small;
2242 GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
2243 2 * qtmux->reserved_moov_size + 16);
2245 GST_OBJECT_LOCK (qtmux);
2246 qtmux->reserved_duration_remaining =
2247 gst_util_uint64_scale (qtmux->reserved_moov_size -
2248 qtmux->base_moov_size, GST_SECOND,
2249 reserved_bytes_per_sec_per_trak *
2250 atom_moov_get_trak_count (qtmux->moov));
2251 GST_OBJECT_UNLOCK (qtmux);
2253 /* Now that we know how much reserved space is targetted,
2254 * output a free atom to fill the extra reserved */
2255 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2256 qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
2257 if (ret != GST_FLOW_OK)
2260 /* Then a free atom containing 'pong' buffer, with an
2261 * extra 8 bytes to account for the free atom header itself */
2262 ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
2263 qtmux->reserved_moov_size + 8, FALSE);
2264 if (ret != GST_FLOW_OK)
2267 /* extra atoms go after the free/moov(s), before the mdat */
2269 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2270 if (ret != GST_FLOW_OK)
2273 qtmux->mdat_pos = qtmux->header_size;
2274 /* extended atom in case we go over 4GB while writing and need
2275 * the full 64-bit atom */
2277 gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
2280 case GST_QT_MUX_MODE_FAST_START:
2281 GST_OBJECT_LOCK (qtmux);
2282 qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
2283 if (!qtmux->fast_start_file)
2285 GST_OBJECT_UNLOCK (qtmux);
2286 /* send a dummy buffer for preroll */
2287 ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
2289 case GST_QT_MUX_MODE_FRAGMENTED:
2290 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2291 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2292 if (ret != GST_FLOW_OK)
2294 /* store the moov pos so we can update the duration later
2295 * in non-streamable mode */
2296 qtmux->moov_pos = qtmux->header_size;
2298 GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
2299 qtmux->fragment_duration);
2300 /* also used as snapshot marker to indicate fragmented file */
2301 qtmux->fragment_sequence = 1;
2302 /* prepare moov and/or tags */
2303 gst_qt_mux_configure_moov (qtmux);
2304 gst_qt_mux_setup_metadata (qtmux);
2305 ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
2306 if (ret != GST_FLOW_OK)
2310 gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
2311 if (ret != GST_FLOW_OK)
2313 /* prepare index if not streamable */
2314 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
2315 qtmux->mfra = atom_mfra_new (qtmux->context);
2323 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2324 ("Cannot create an ISML file with 0 fragment duration"), (NULL));
2325 return GST_FLOW_ERROR;
2327 reserved_moov_too_small:
2329 GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2330 ("Not enough reserved space for creating headers"), (NULL));
2331 return GST_FLOW_ERROR;
2335 GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
2336 (("Could not open temporary file \"%s\""),
2337 qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
2338 GST_OBJECT_UNLOCK (qtmux);
2339 return GST_FLOW_ERROR;
2343 static GstFlowReturn
2344 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
2346 GstFlowReturn ret = GST_FLOW_OK;
2349 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2350 GstCollectData *cdata = (GstCollectData *) walk->data;
2351 GstQTPad *qtpad = (GstQTPad *) cdata;
2353 /* avoid add_buffer complaining if not negotiated
2354 * in which case no buffers either, so skipping */
2355 if (!qtpad->fourcc) {
2356 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2357 GST_PAD_NAME (qtpad->collect.pad));
2361 /* send last buffer; also flushes possibly queued buffers/ts */
2362 GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
2363 GST_PAD_NAME (qtpad->collect.pad));
2364 ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
2365 if (ret != GST_FLOW_OK) {
2366 GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
2367 "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
2368 gst_flow_get_name (ret));
2376 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
2380 /* for setting some subtitles fields */
2381 guint max_width = 0;
2382 guint max_height = 0;
2384 qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
2386 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2387 GstCollectData *cdata = (GstCollectData *) walk->data;
2388 GstQTPad *qtpad = (GstQTPad *) cdata;
2390 if (!qtpad->fourcc) {
2391 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2392 GST_PAD_NAME (qtpad->collect.pad));
2396 /* having flushed above, can check for buffers now */
2397 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2398 /* determine max stream duration */
2399 if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
2400 || qtpad->last_dts > qtmux->last_dts) {
2401 qtmux->last_dts = qtpad->last_dts;
2403 if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
2404 || qtpad->first_ts < qtmux->first_ts) {
2405 qtmux->first_ts = qtpad->first_ts;
2409 /* subtitles need to know the video width/height,
2410 * it is stored shifted 16 bits to the left according to the
2412 max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
2413 max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
2415 /* update average bitrate of streams if needed */
2417 guint32 avgbitrate = 0;
2418 guint32 maxbitrate = qtpad->max_bitrate;
2420 if (qtpad->avg_bitrate)
2421 avgbitrate = qtpad->avg_bitrate;
2422 else if (qtpad->total_duration > 0)
2423 avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
2424 8 * GST_SECOND, qtpad->total_duration);
2426 atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
2430 /* need to update values on subtitle traks now that we know the
2431 * max width and height */
2432 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2433 GstCollectData *cdata = (GstCollectData *) walk->data;
2434 GstQTPad *qtpad = (GstQTPad *) cdata;
2436 if (!qtpad->fourcc) {
2437 GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
2438 GST_PAD_NAME (qtpad->collect.pad));
2442 if (qtpad->fourcc == FOURCC_tx3g) {
2443 atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
2448 /* Called after gst_qt_mux_update_global_statistics() updates the
2449 * first_ts tracking, to create/set edit lists for delayed streams */
2451 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
2455 GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
2456 GST_TIME_ARGS (qtmux->first_ts));
2457 /* add/update EDTSs for late streams. configure_moov will have
2458 * set the trak durations above by summing the sample tables,
2459 * here we extend that if needing to insert an empty segment */
2460 for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2461 GstCollectData *cdata = (GstCollectData *) walk->data;
2462 GstQTPad *qtpad = (GstQTPad *) cdata;
2464 if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
2465 guint32 lateness = 0;
2466 guint32 duration = qtpad->trak->tkhd.duration;
2469 has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
2474 diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
2475 lateness = gst_util_uint64_scale_round (diff,
2476 qtmux->timescale, GST_SECOND);
2478 GST_DEBUG_OBJECT (qtmux, "Pad %s is a late stream by %" GST_TIME_FORMAT,
2479 GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (lateness));
2481 atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
2482 (guint32) (1 * 65536.0));
2486 if (has_gap || (qtpad->dts_adjustment > 0)) {
2487 GstClockTime ctts = 0;
2488 guint32 media_start;
2490 if (qtpad->first_ts > qtpad->first_dts)
2491 ctts = qtpad->first_ts - qtpad->first_dts;
2493 media_start = gst_util_uint64_scale_round (ctts,
2494 atom_trak_get_timescale (qtpad->trak), GST_SECOND);
2496 atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
2497 (guint32) (1 * 65536.0));
2500 /* need to add the empty time to the trak duration */
2501 duration += lateness;
2503 qtpad->trak->tkhd.duration = duration;
2504 if (qtpad->tc_trak) {
2505 qtpad->tc_trak->tkhd.duration = duration;
2506 qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
2509 /* And possibly grow the moov duration */
2510 if (duration > qtmux->moov->mvhd.time_info.duration) {
2511 qtmux->moov->mvhd.time_info.duration = duration;
2512 qtmux->moov->mvex.mehd.fragment_duration = duration;
2518 static GstFlowReturn
2519 gst_qt_mux_update_timecode (GstQTMux * qtmux)
2524 guint64 offset = qtmux->tc_pos;
2526 g_assert (qtmux->tc_pos != -1);
2528 gst_segment_init (&segment, GST_FORMAT_BYTES);
2529 segment.start = offset;
2530 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2532 buf = gst_buffer_new_and_alloc (4);
2533 gst_buffer_map (buf, &map, GST_MAP_WRITE);
2535 GST_WRITE_UINT32_BE (map.data,
2536 gst_video_time_code_frames_since_daily_jam (qtmux->first_tc));
2537 gst_buffer_unmap (buf, &map);
2539 /* Reset this value, so the timecode won't be re-rewritten */
2542 return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
2545 static GstFlowReturn
2546 gst_qt_mux_stop_file (GstQTMux * qtmux)
2548 gboolean ret = GST_FLOW_OK;
2549 guint64 offset = 0, size = 0;
2550 gboolean large_file;
2552 GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
2554 /* pushing last buffers for each pad */
2555 if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
2558 if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2559 /* Streamable mode; no need to write duration or MFRA */
2560 GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
2564 gst_qt_mux_update_global_statistics (qtmux);
2565 if (qtmux->tc_pos != -1) {
2566 /* File is being stopped and timecode hasn't been updated. Update it now
2567 * with whatever we have */
2568 ret = gst_qt_mux_update_timecode (qtmux);
2569 if (ret != GST_FLOW_OK)
2573 switch (qtmux->mux_mode) {
2574 case GST_QT_MUX_MODE_FRAGMENTED:{
2576 guint8 *data = NULL;
2580 GST_DEBUG_OBJECT (qtmux, "adding mfra");
2581 if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
2582 goto serialize_error;
2583 buf = _gst_buffer_new_take_data (data, offset);
2584 ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
2585 if (ret != GST_FLOW_OK)
2588 /* only mvex duration is updated,
2589 * mvhd should be consistent with empty moov
2590 * (but TODO maybe some clients do not handle that well ?) */
2591 qtmux->moov->mvex.mehd.fragment_duration =
2592 gst_util_uint64_scale (qtmux->last_dts, qtmux->timescale, GST_SECOND);
2593 GST_DEBUG_OBJECT (qtmux, "rewriting moov with mvex duration %"
2594 GST_TIME_FORMAT, GST_TIME_ARGS (qtmux->last_dts));
2595 /* seek and rewrite the header */
2596 gst_segment_init (&segment, GST_FORMAT_BYTES);
2597 segment.start = qtmux->moov_pos;
2598 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2599 /* no need to seek back */
2600 return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2602 case GST_QT_MUX_MODE_ROBUST_RECORDING:{
2603 ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
2604 if (G_UNLIKELY (ret != GST_FLOW_OK))
2606 /* Finalise by writing the final size into the mdat. Up until now
2607 * it's been 0, which means 'rest of the file'
2608 * No need to seek back after this, we won't write any more */
2609 return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2610 qtmux->mdat_size, NULL, TRUE);
2616 /* Moov-at-end or fast-start mode from here down */
2617 gst_qt_mux_configure_moov (qtmux);
2619 gst_qt_mux_update_edit_lists (qtmux);
2621 /* tags into file metadata */
2622 gst_qt_mux_setup_metadata (qtmux);
2624 large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
2626 switch (qtmux->mux_mode) {
2627 case GST_QT_MUX_MODE_FAST_START:{
2628 /* if faststart, update the offset of the atoms in the movie with the offset
2629 * that the movie headers before mdat will cause.
2630 * Also, send the ftyp */
2633 ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
2634 if (ret != GST_FLOW_OK) {
2637 /* copy into NULL to obtain size */
2638 if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
2639 goto serialize_error;
2640 GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
2642 offset += qtmux->header_size + (large_file ? 16 : 8);
2644 /* sum up with the extra atoms size */
2645 ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
2646 if (ret != GST_FLOW_OK)
2651 offset = qtmux->header_size;
2655 /* Now that we know the size of moov + extra atoms, we can adjust
2656 * the chunk offsets stored into the moov */
2657 atom_moov_chunks_set_offset (qtmux->moov, offset);
2659 /* write out moov and extra atoms */
2660 /* note: as of this point, we no longer care about tracking written data size,
2661 * since there is no more use for it anyway */
2662 ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
2663 if (ret != GST_FLOW_OK)
2667 ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
2668 if (ret != GST_FLOW_OK)
2671 switch (qtmux->mux_mode) {
2672 case GST_QT_MUX_MODE_MOOV_AT_END:
2674 /* mdat needs update iff not using faststart */
2675 GST_DEBUG_OBJECT (qtmux, "updating mdat size");
2676 ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
2677 qtmux->mdat_size, NULL, FALSE);
2678 /* note; no seeking back to the end of file is done,
2679 * since we no longer write anything anyway */
2682 case GST_QT_MUX_MODE_FAST_START:
2684 /* send mdat atom and move buffered data into it */
2685 /* mdat_size = accumulated (buffered data) */
2686 ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
2688 if (ret != GST_FLOW_OK)
2690 ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
2691 if (ret != GST_FLOW_OK)
2696 g_assert_not_reached ();
2704 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2705 ("Failed to serialize moov"));
2706 return GST_FLOW_ERROR;
2710 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
2711 return GST_FLOW_ERROR;
2715 static GstFlowReturn
2716 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
2717 GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
2718 guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
2720 GstFlowReturn ret = GST_FLOW_OK;
2722 /* setup if needed */
2723 if (G_UNLIKELY (!pad->traf || force))
2727 /* flush pad fragment if threshold reached,
2728 * or at new keyframe if we should be minding those in the first place */
2729 if (G_UNLIKELY (force || (sync && pad->sync) ||
2730 pad->fragment_duration < (gint64) delta)) {
2732 guint64 size = 0, offset = 0;
2733 guint8 *data = NULL;
2735 guint i, total_size;
2737 /* now we know where moof ends up, update offset in tfra */
2739 atom_tfra_update_offset (pad->tfra, qtmux->header_size);
2741 moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
2742 /* takes ownership */
2743 atom_moof_add_traf (moof, pad->traf);
2745 atom_moof_copy_data (moof, &data, &size, &offset);
2746 buffer = _gst_buffer_new_take_data (data, offset);
2747 GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
2748 gst_buffer_get_size (buffer));
2749 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
2751 /* and actual data */
2753 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2755 gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
2758 GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
2759 atom_array_get_len (&pad->fragment_buffers), total_size);
2760 if (ret == GST_FLOW_OK)
2761 ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
2763 for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
2764 if (G_LIKELY (ret == GST_FLOW_OK))
2765 ret = gst_qt_mux_send_buffer (qtmux,
2766 atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
2769 gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
2772 atom_array_clear (&pad->fragment_buffers);
2773 atom_moof_free (moof);
2774 qtmux->fragment_sequence++;
2779 if (G_UNLIKELY (!pad->traf)) {
2780 GST_LOG_OBJECT (qtmux, "setting up new fragment");
2781 pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
2782 atom_array_init (&pad->fragment_buffers, 512);
2783 pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
2784 atom_trak_get_timescale (pad->trak), 1000);
2786 if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
2787 pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
2788 atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
2792 /* add buffer and metadata */
2793 atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
2795 atom_array_append (&pad->fragment_buffers, buf, 256);
2796 pad->fragment_duration -= delta;
2799 guint32 sn = atom_traf_get_sample_num (pad->traf);
2801 if ((sync && pad->sync) || (sn == 1 && !pad->sync))
2802 atom_tfra_add_entry (pad->tfra, dts, sn);
2805 if (G_UNLIKELY (force))
2811 /* Here's the clever bit of robust recording: Updating the moov
2812 * header is done using a ping-pong scheme inside 2 blocks of size
2813 * 'reserved_moov_size' at the start of the file, in such a way that the
2814 * file on-disk is always valid if interrupted.
2815 * Inside the reserved space, we have 2 pairs of free + moov atoms
2816 * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
2817 * at offset "reserved_moov_size".
2819 * 1. Free-A has 0 size payload, moov-A immediately after is
2820 * active/current, and is padded with an internal Free atom to
2821 * end at reserved_space/2. Free-B is at reserved_space/2, sized
2822 * to cover the remaining free space (including moov-B).
2823 * 2. We write moov-B (which is invisible inside free-B), and pad it to
2824 * end at the end of free space. Then, we update free-A to size
2825 * reserved_space/2 + sizeof(free-B), which hides moov-A and the
2826 * free-B header, and makes moov-B active.
2827 * 3. Rewrite moov-A inside free-A, with padding out to free-B.
2828 * Change the size of free-A to make moov-A active again.
2829 * 4. Rinse and repeat.
2832 static GstFlowReturn
2833 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
2837 guint64 freeA_offset;
2838 guint32 new_freeA_size;
2839 guint64 new_moov_offset;
2841 /* Update moov info, then seek and rewrite the MOOV atom */
2842 gst_qt_mux_update_global_statistics (qtmux);
2843 gst_qt_mux_configure_moov (qtmux);
2845 gst_qt_mux_update_edit_lists (qtmux);
2847 /* tags into file metadata */
2848 gst_qt_mux_setup_metadata (qtmux);
2850 /* chunks position is set relative to the first byte of the
2851 * MDAT atom payload. Set the overall offset into the file */
2852 atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
2854 /* Calculate which moov to rewrite. qtmux->moov_pos points to
2855 * the start of the free-A header */
2856 freeA_offset = qtmux->moov_pos;
2857 if (qtmux->reserved_moov_first_active) {
2858 GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
2859 /* After this, freeA will include itself, moovA, plus the freeB
2861 new_freeA_size = qtmux->reserved_moov_size + 16;
2863 GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
2866 /* the moov we update is after free-A, calculate its offset */
2867 new_moov_offset = freeA_offset + new_freeA_size;
2869 /* Swap ping-pong cadence marker */
2870 qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
2872 /* seek and rewrite the MOOV atom */
2873 gst_segment_init (&segment, GST_FORMAT_BYTES);
2874 segment.start = new_moov_offset;
2875 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2878 gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
2880 if (ret != GST_FLOW_OK)
2883 /* Update the estimated recording space remaining, based on amount used so
2884 * far and duration muxed so far */
2885 if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
2886 GstClockTime remain;
2887 GstClockTime time_muxed = qtmux->last_dts;
2890 gst_util_uint64_scale (qtmux->reserved_moov_size -
2891 qtmux->last_moov_size, time_muxed,
2892 qtmux->last_moov_size - qtmux->base_moov_size);
2893 /* Always under-estimate slightly, so users
2894 * have time to stop muxing before we run out */
2895 if (remain < GST_SECOND / 2)
2898 remain -= GST_SECOND / 2;
2900 GST_INFO_OBJECT (qtmux,
2901 "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
2902 ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
2903 qtmux->reserved_moov_size, qtmux->last_moov_size,
2904 GST_TIME_ARGS (qtmux->last_dts),
2905 qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
2907 GST_OBJECT_LOCK (qtmux);
2908 qtmux->reserved_duration_remaining = remain;
2909 qtmux->muxed_since_last_update = 0;
2910 GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
2911 G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
2912 GST_OBJECT_UNLOCK (qtmux);
2916 /* Now update the moov-A size. Don't pass offset, since we don't need
2917 * send_free_atom() to seek for us - all our callers seek back to
2918 * where they need after this, or they don't need it */
2919 gst_segment_init (&segment, GST_FORMAT_BYTES);
2920 segment.start = freeA_offset;
2921 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2923 ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
2928 static GstFlowReturn
2929 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
2932 GstFlowReturn flow_ret;
2934 guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
2936 GST_OBJECT_LOCK (qtmux);
2937 if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
2938 GST_OBJECT_UNLOCK (qtmux);
2942 /* Update if position is > the threshold or there's been no update yet */
2943 if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
2944 (position <= qtmux->last_moov_update ||
2945 (position - qtmux->last_moov_update) <
2946 qtmux->reserved_moov_update_period)) {
2947 /* Update the offset of how much we've muxed, so the
2948 * report of remaining space keeps counting down */
2949 if (position > qtmux->last_moov_update &&
2950 position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
2951 GST_LOG_OBJECT (qtmux,
2952 "Muxed time %" G_GUINT64_FORMAT " since last moov update",
2953 qtmux->muxed_since_last_update);
2954 qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
2956 GST_OBJECT_UNLOCK (qtmux);
2957 return GST_FLOW_OK; /* No update needed yet */
2960 qtmux->last_moov_update = position;
2961 GST_OBJECT_UNLOCK (qtmux);
2963 GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
2964 " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
2965 GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
2967 flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
2968 if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
2971 /* Seek back to previous position */
2972 gst_segment_init (&segment, GST_FORMAT_BYTES);
2973 segment.start = mdat_offset;
2974 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2979 static GstFlowReturn
2980 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
2981 GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
2982 gint64 last_dts, gint64 scaled_duration, guint sample_size,
2983 guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
2985 GstFlowReturn ret = GST_FLOW_OK;
2987 /* note that a new chunk is started each time (not fancy but works) */
2988 if (qtmux->moov_recov_file) {
2989 if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
2990 nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
2991 do_pts, pts_offset)) {
2992 GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
2993 "recovery file, disabling recovery");
2994 fclose (qtmux->moov_recov_file);
2995 qtmux->moov_recov_file = NULL;
2999 switch (qtmux->mux_mode) {
3000 case GST_QT_MUX_MODE_MOOV_AT_END:
3001 case GST_QT_MUX_MODE_FAST_START:
3002 case GST_QT_MUX_MODE_ROBUST_RECORDING:
3003 atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
3004 sample_size, chunk_offset, sync, pts_offset);
3005 ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
3006 /* Check if it's time to re-write the headers in robust-recording mode */
3007 if (ret == GST_FLOW_OK
3008 && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
3009 ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
3011 case GST_QT_MUX_MODE_FRAGMENTED:
3012 case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3013 /* ensure that always sync samples are marked as such */
3014 ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
3015 is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
3016 sample_size, !pad->sync || sync, pts_offset);
3023 static GstFlowReturn
3024 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
3025 GstBuffer * buf, GstFlowReturn ret)
3027 if (buf != NULL && (pad->tc_trak == NULL || qtmux->tc_pos != -1)) {
3028 GstVideoTimeCodeMeta *tc_meta = gst_buffer_get_video_time_code_meta (buf);
3030 GstVideoTimeCode *tc = &tc_meta->tc;
3033 guint32 frames_since_daily_jam;
3035 /* This means we never got a timecode before */
3036 if (qtmux->first_tc == NULL) {
3037 #ifndef GST_DISABLE_GST_DEBUG
3038 gchar *tc_str = gst_video_time_code_to_string (tc);
3039 GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
3042 g_assert (pad->tc_trak == NULL);
3043 tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
3044 qtmux->first_tc = gst_video_time_code_copy (tc);
3045 /* If frames are out of order, the frame we're currently getting might
3046 * not be the first one. Just write a 0 timecode for now and wait
3047 * until we receive a timecode that's lower than the current one */
3048 if (pad->is_out_of_order) {
3049 qtmux->first_pts = GST_BUFFER_PTS (buf);
3050 frames_since_daily_jam = 0;
3051 /* Position to rewrite */
3052 qtmux->tc_pos = qtmux->mdat_size;
3054 frames_since_daily_jam =
3055 gst_video_time_code_frames_since_daily_jam (qtmux->first_tc);
3056 frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
3058 /* Write the timecode trak now */
3059 pad->tc_trak = atom_trak_new (qtmux->context);
3060 atom_moov_add_trak (qtmux->moov, pad->tc_trak);
3062 pad->trak->tref = atom_tref_new (FOURCC_tmcd);
3063 atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
3065 atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
3068 szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
3069 g_assert (szret == 4);
3071 atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE,
3073 ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
3074 } else if (pad->is_out_of_order) {
3075 /* Check for a lower timecode than the one stored */
3076 g_assert (pad->tc_trak != NULL);
3077 if (GST_BUFFER_DTS (buf) <= qtmux->first_pts) {
3078 if (gst_video_time_code_compare (tc, qtmux->first_tc) == -1) {
3079 gst_video_time_code_free (qtmux->first_tc);
3080 qtmux->first_tc = gst_video_time_code_copy (tc);
3083 guint64 bk_size = qtmux->mdat_size;
3085 /* If this frame's DTS is after the first PTS received, it means
3086 * we've already received the first frame to be presented. Otherwise
3087 * the decoder would need to go back in time */
3088 gst_qt_mux_update_timecode (qtmux);
3090 /* Reset writing position */
3091 gst_segment_init (&segment, GST_FORMAT_BYTES);
3092 segment.start = bk_size;
3093 gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3102 * Here we push the buffer and update the tables in the track atoms
3104 static GstFlowReturn
3105 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
3107 GstBuffer *last_buf = NULL;
3108 GstClockTime duration;
3109 guint nsamples, sample_size;
3110 guint64 chunk_offset;
3111 gint64 last_dts, scaled_duration;
3112 gint64 pts_offset = 0;
3113 gboolean sync = FALSE;
3114 GstFlowReturn ret = GST_FLOW_OK;
3117 goto not_negotiated;
3119 /* if this pad has a prepare function, call it */
3120 if (pad->prepare_buf_func != NULL) {
3121 buf = pad->prepare_buf_func (pad, buf, qtmux);
3124 last_buf = pad->last_buf;
3126 /* DTS delta is used to calculate sample duration.
3127 * If buffer has missing DTS, we take either segment start or
3128 * previous buffer end time, whichever is later.
3129 * This must only be done for non sparse streams, sparse streams
3130 * can have gaps between buffers (which is handled later by adding
3131 * extra empty buffer with duration that fills the gap). */
3132 if (!pad->sparse && buf && !GST_BUFFER_DTS_IS_VALID (buf)) {
3133 GstClockTime last_buf_duration = last_buf
3134 && GST_BUFFER_DURATION_IS_VALID (last_buf) ?
3135 GST_BUFFER_DURATION (last_buf) : 0;
3137 buf = gst_buffer_make_writable (buf);
3138 GST_BUFFER_DTS (buf) = 0; /* running-time 0 */
3141 && (GST_BUFFER_DTS (last_buf) + last_buf_duration) >
3142 GST_BUFFER_DTS (buf)) {
3143 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf) + last_buf_duration;
3147 ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
3149 if (last_buf && !buf && !GST_BUFFER_DURATION_IS_VALID (last_buf)) {
3150 /* this is last buffer; there is no next buffer so we need valid number as duration */
3151 last_buf = gst_buffer_make_writable (last_buf);
3152 GST_BUFFER_DURATION (last_buf) = 0;
3155 if (last_buf == NULL) {
3156 #ifndef GST_DISABLE_GST_DEBUG
3158 GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
3159 "received NULL buffer, doing nothing",
3160 GST_PAD_NAME (pad->collect.pad));
3162 GST_LOG_OBJECT (qtmux,
3163 "Pad %s has no previous buffer stored, storing now",
3164 GST_PAD_NAME (pad->collect.pad));
3167 pad->last_buf = buf;
3170 gst_buffer_ref (last_buf);
3172 /* if this is the first buffer, store the timestamp */
3173 if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE) && last_buf) {
3174 if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3175 pad->first_ts = GST_BUFFER_PTS (last_buf);
3176 } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3177 pad->first_ts = GST_BUFFER_DTS (last_buf);
3180 if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
3181 pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
3182 } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
3183 pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
3186 if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
3187 GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
3189 GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
3190 "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
3191 pad->first_ts = pad->first_dts = 0;
3193 GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
3194 GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
3195 GST_TIME_ARGS (pad->first_ts));
3198 if (last_buf && buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
3199 GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
3200 GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
3201 GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
3202 GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
3203 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
3204 GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
3207 /* duration actually means time delta between samples, so we calculate
3208 * the duration based on the difference in DTS or PTS, falling back
3209 * to DURATION if the other two don't exist, such as with the last
3210 * sample before EOS. */
3211 duration = GST_BUFFER_DURATION (last_buf);
3213 if (last_buf && buf && GST_BUFFER_DTS_IS_VALID (buf)
3214 && GST_BUFFER_DTS_IS_VALID (last_buf))
3215 duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
3216 else if (last_buf && buf && GST_BUFFER_PTS_IS_VALID (buf)
3217 && GST_BUFFER_PTS_IS_VALID (last_buf))
3218 duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
3221 gst_buffer_replace (&pad->last_buf, buf);
3223 /* for computing the avg bitrate */
3224 if (G_LIKELY (last_buf)) {
3225 pad->total_bytes += gst_buffer_get_size (last_buf);
3226 pad->total_duration += duration;
3229 last_dts = gst_util_uint64_scale_round (pad->last_dts,
3230 atom_trak_get_timescale (pad->trak), GST_SECOND);
3232 /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
3233 if (pad->sample_size && !qtmux->fragment_sequence) {
3234 /* Constant size packets: usually raw audio (with many samples per
3235 buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
3237 sample_size = pad->sample_size;
3238 if (gst_buffer_get_size (last_buf) % sample_size != 0)
3239 goto fragmented_sample;
3240 /* note: qt raw audio storage warps it implicitly into a timewise
3241 * perfect stream, discarding buffer times */
3242 if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
3243 nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
3244 atom_trak_get_timescale (pad->trak), GST_SECOND);
3246 nsamples = gst_buffer_get_size (last_buf) / sample_size;
3249 duration = GST_BUFFER_DURATION (last_buf) / nsamples;
3253 /* timescale = samplerate */
3254 scaled_duration = 1;
3255 pad->last_dts += duration * nsamples;
3258 sample_size = gst_buffer_get_size (last_buf);
3259 if ((pad->last_buf && GST_BUFFER_DTS_IS_VALID (pad->last_buf))
3260 || GST_BUFFER_DTS_IS_VALID (last_buf)) {
3262 if (pad->last_buf && GST_BUFFER_DTS_IS_VALID (pad->last_buf)) {
3263 pad->last_dts = GST_BUFFER_DTS (pad->last_buf);
3265 pad->last_dts = GST_BUFFER_DTS (last_buf) +
3266 GST_BUFFER_DURATION (last_buf);
3268 if ((gint64) (pad->last_dts) < 0) {
3269 scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
3270 atom_trak_get_timescale (pad->trak), GST_SECOND);
3272 scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
3273 atom_trak_get_timescale (pad->trak), GST_SECOND);
3275 scaled_duration = scaled_dts - last_dts;
3276 last_dts = scaled_dts;
3278 /* first convert intended timestamp (in GstClockTime resolution) to
3279 * trak timescale, then derive delta;
3280 * this ensures sums of (scale)delta add up to converted timestamp,
3281 * which only deviates at most 1/scale from timestamp itself */
3282 scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
3283 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
3284 pad->last_dts += duration;
3287 chunk_offset = qtmux->mdat_size;
3289 GST_LOG_OBJECT (qtmux,
3290 "Pad (%s) dts updated to %" GST_TIME_FORMAT,
3291 GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
3292 GST_LOG_OBJECT (qtmux,
3293 "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
3294 " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
3295 nsamples, scaled_duration, sample_size, chunk_offset);
3297 /* might be a sync sample */
3299 !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
3300 GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
3301 GST_PAD_NAME (pad->collect.pad));
3305 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf))) {
3306 last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
3307 atom_trak_get_timescale (pad->trak), GST_SECOND);
3309 (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3310 atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
3314 last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
3315 atom_trak_get_timescale (pad->trak), GST_SECOND);
3317 GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
3318 " timebase_dts: %d pts_offset: %d",
3319 GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
3320 GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
3321 (int) (last_dts), (int) (pts_offset));
3324 * Each buffer starts a new chunk, so we can assume the buffer
3325 * duration is the chunk duration
3327 if (GST_CLOCK_TIME_IS_VALID (duration) && (duration > qtmux->longest_chunk ||
3328 !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
3329 GST_DEBUG_OBJECT (qtmux, "New longest chunk found: %" GST_TIME_FORMAT
3330 ", pad %s", GST_TIME_ARGS (duration), GST_PAD_NAME (pad->collect.pad));
3331 qtmux->longest_chunk = duration;
3334 /* now we go and register this buffer/sample all over */
3335 ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
3336 buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
3337 chunk_offset, sync, TRUE, pts_offset);
3339 /* if this is sparse and we have a next buffer, check if there is any gap
3340 * between them to insert an empty sample */
3341 if (pad->sparse && buf) {
3342 if (pad->create_empty_buffer) {
3343 GstBuffer *empty_buf;
3344 gint64 empty_duration =
3345 GST_BUFFER_TIMESTAMP (buf) - (GST_BUFFER_TIMESTAMP (last_buf) +
3347 gint64 empty_duration_scaled;
3349 empty_buf = pad->create_empty_buffer (pad, empty_duration);
3351 empty_duration_scaled = gst_util_uint64_scale_round (empty_duration,
3352 atom_trak_get_timescale (pad->trak), GST_SECOND);
3354 pad->total_bytes += gst_buffer_get_size (empty_buf);
3355 pad->total_duration += duration;
3358 gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
3359 last_dts + scaled_duration, empty_duration_scaled,
3360 gst_buffer_get_size (empty_buf), qtmux->mdat_size, sync, TRUE, 0);
3362 /* our only case currently is tx3g subtitles, so there is no reason to fill this yet */
3363 g_assert_not_reached ();
3364 GST_WARNING_OBJECT (qtmux,
3365 "no empty buffer creation function found for pad %s",
3366 GST_PAD_NAME (pad->collect.pad));
3371 gst_buffer_unref (buf);
3381 gst_buffer_unref (buf);
3382 gst_buffer_unref (last_buf);
3383 return GST_FLOW_ERROR;
3387 GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3388 ("Audio buffer contains fragmented sample."));
3393 GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
3394 ("format wasn't negotiated before buffer flow on pad %s",
3395 GST_PAD_NAME (pad->collect.pad)));
3397 gst_buffer_unref (buf);
3398 return GST_FLOW_NOT_NEGOTIATED;
3403 * DTS running time can be negative. There is no way to represent that in
3404 * MP4 however, thus we need to offset DTS so that it starts from 0.
3407 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
3408 GstCollectData * cdata, GstBuffer ** buf)
3413 pts = GST_BUFFER_PTS (*buf);
3414 dts = GST_COLLECT_PADS_DTS (cdata);
3416 GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
3417 " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
3418 GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
3420 if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
3421 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
3422 pad->dts_adjustment = -dts;
3424 pad->dts_adjustment = 0;
3427 if (pad->dts_adjustment > 0) {
3428 *buf = gst_buffer_make_writable (*buf);
3430 dts += pad->dts_adjustment;
3432 if (GST_CLOCK_TIME_IS_VALID (pts))
3433 pts += pad->dts_adjustment;
3435 if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
3436 GST_WARNING_OBJECT (pad, "Decreasing DTS.");
3441 GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
3445 GST_BUFFER_PTS (*buf) = pts;
3446 GST_BUFFER_DTS (*buf) = dts;
3448 GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
3449 " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
3453 static GstFlowReturn
3454 gst_qt_mux_handle_buffer (GstCollectPads * pads, GstCollectData * cdata,
3455 GstBuffer * buf, gpointer user_data)
3457 GstFlowReturn ret = GST_FLOW_OK;
3458 GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
3459 GstQTPad *best_pad = NULL;
3461 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
3462 if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
3465 qtmux->state = GST_QT_MUX_STATE_DATA;
3468 if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
3469 return GST_FLOW_EOS;
3471 best_pad = (GstQTPad *) cdata;
3473 /* clipping already converted to running time */
3474 if (best_pad != NULL) {
3476 gst_qt_pad_adjust_buffer_dts (qtmux, best_pad, cdata, &buf);
3477 ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
3479 qtmux->state = GST_QT_MUX_STATE_EOS;
3480 ret = gst_qt_mux_stop_file (qtmux);
3481 if (ret == GST_FLOW_OK) {
3482 GST_DEBUG_OBJECT (qtmux, "Pushing eos");
3483 gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
3486 GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
3487 gst_flow_get_name (ret));
3495 check_field (GQuark field_id, const GValue * value, gpointer user_data)
3497 GstStructure *structure = (GstStructure *) user_data;
3498 const GValue *other = gst_structure_id_get_value (structure, field_id);
3501 return gst_value_compare (value, other) == GST_VALUE_EQUAL;
3505 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
3508 GstStructure *sub_s = gst_caps_get_structure (subset, 0);
3509 GstStructure *sup_s = gst_caps_get_structure (superset, 0);
3511 return gst_structure_foreach (sub_s, check_field, sup_s);
3515 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3517 GstPad *pad = qtpad->collect.pad;
3518 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3519 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3520 GstStructure *structure;
3521 const gchar *mimetype;
3522 gint rate, channels;
3523 const GValue *value = NULL;
3524 const GstBuffer *codec_data = NULL;
3525 GstQTMuxFormat format;
3526 AudioSampleEntry entry = { 0, };
3527 AtomInfo *ext_atom = NULL;
3528 gint constant_size = 0;
3529 const gchar *stream_format;
3531 qtpad->prepare_buf_func = NULL;
3533 /* does not go well to renegotiate stream mid-way, unless
3534 * the old caps are a subset of the new one (this means upstream
3535 * added more info to the caps, as both should be 'fixed' caps) */
3536 if (qtpad->fourcc) {
3537 GstCaps *current_caps;
3539 current_caps = gst_pad_get_current_caps (pad);
3540 g_assert (caps != NULL);
3542 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3543 gst_caps_unref (current_caps);
3544 goto refuse_renegotiation;
3546 GST_DEBUG_OBJECT (qtmux,
3547 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
3548 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
3549 gst_caps_unref (current_caps);
3552 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
3553 GST_DEBUG_PAD_NAME (pad), caps);
3555 format = qtmux_klass->format;
3556 structure = gst_caps_get_structure (caps, 0);
3557 mimetype = gst_structure_get_name (structure);
3560 if (!gst_structure_get_int (structure, "channels", &channels) ||
3561 !gst_structure_get_int (structure, "rate", &rate)) {
3566 value = gst_structure_get_value (structure, "codec_data");
3568 codec_data = gst_value_get_buffer (value);
3570 qtpad->is_out_of_order = FALSE;
3572 /* set common properties */
3573 entry.sample_rate = rate;
3574 entry.channels = channels;
3576 entry.sample_size = 16;
3577 /* this is the typical compressed case */
3578 if (format == GST_QT_MUX_FORMAT_QT) {
3580 entry.compression_id = -2;
3583 /* now map onto a fourcc, and some extra properties */
3584 if (strcmp (mimetype, "audio/mpeg") == 0) {
3585 gint mpegversion = 0, mpegaudioversion = 0;
3588 gst_structure_get_int (structure, "mpegversion", &mpegversion);
3589 switch (mpegversion) {
3591 gst_structure_get_int (structure, "layer", &layer);
3592 gst_structure_get_int (structure, "mpegaudioversion",
3596 /* note: QuickTime player does not like mp3 either way in iso/mp4 */
3597 if (format == GST_QT_MUX_FORMAT_QT)
3598 entry.fourcc = FOURCC__mp3;
3600 entry.fourcc = FOURCC_mp4a;
3602 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
3603 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3604 qtpad->max_bitrate);
3607 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3608 entry.samples_per_packet = 384;
3609 } else if (layer == 2) {
3610 g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4);
3611 entry.samples_per_packet = 1152;
3613 g_warn_if_fail (layer == 3);
3614 entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
3616 entry.bytes_per_sample = 2;
3620 /* check stream-format */
3621 stream_format = gst_structure_get_string (structure, "stream-format");
3622 if (stream_format) {
3623 if (strcmp (stream_format, "raw") != 0) {
3624 GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
3625 "please use 'raw'", stream_format);
3629 GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
3633 if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
3634 GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
3639 gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
3640 /* warn if not Low Complexity profile */
3643 GST_WARNING_OBJECT (qtmux,
3644 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
3648 entry.fourcc = FOURCC_mp4a;
3650 if (format == GST_QT_MUX_FORMAT_QT)
3651 ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
3652 qtpad->avg_bitrate, qtpad->max_bitrate);
3655 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
3656 ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
3657 qtpad->max_bitrate);
3662 } else if (strcmp (mimetype, "audio/AMR") == 0) {
3663 entry.fourcc = FOURCC_samr;
3664 entry.sample_size = 16;
3665 entry.samples_per_packet = 160;
3666 entry.bytes_per_sample = 2;
3667 ext_atom = build_amr_extension ();
3668 } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
3669 entry.fourcc = FOURCC_sawb;
3670 entry.sample_size = 16;
3671 entry.samples_per_packet = 320;
3672 entry.bytes_per_sample = 2;
3673 ext_atom = build_amr_extension ();
3674 } else if (strcmp (mimetype, "audio/x-raw") == 0) {
3677 gst_audio_info_init (&info);
3678 if (!gst_audio_info_from_caps (&info, caps))
3681 /* spec has no place for a distinction in these */
3682 if (info.finfo->width != info.finfo->depth) {
3683 GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
3687 if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
3688 if (info.finfo->endianness == G_LITTLE_ENDIAN)
3689 entry.fourcc = FOURCC_sowt;
3690 else if (info.finfo->endianness == G_BIG_ENDIAN)
3691 entry.fourcc = FOURCC_twos;
3693 entry.fourcc = FOURCC_sowt;
3694 /* maximum backward compatibility; only new version for > 16 bit */
3695 if (info.finfo->depth <= 16)
3697 /* not compressed in any case */
3698 entry.compression_id = 0;
3699 /* QT spec says: max at 16 bit even if sample size were actually larger,
3700 * however, most players (e.g. QuickTime!) seem to disagree, so ... */
3701 entry.sample_size = info.finfo->depth;
3702 entry.bytes_per_sample = info.finfo->depth / 8;
3703 entry.samples_per_packet = 1;
3704 entry.bytes_per_packet = info.finfo->depth / 8;
3705 entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
3707 if (info.finfo->width == 8 && info.finfo->depth == 8) {
3708 /* fall back to old 8-bit version */
3709 entry.fourcc = FOURCC_raw_;
3711 entry.compression_id = 0;
3712 entry.sample_size = 8;
3714 GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
3718 constant_size = (info.finfo->depth / 8) * info.channels;
3719 } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
3720 entry.fourcc = FOURCC_alaw;
3721 entry.samples_per_packet = 1023;
3722 entry.bytes_per_sample = 2;
3723 } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
3724 entry.fourcc = FOURCC_ulaw;
3725 entry.samples_per_packet = 1023;
3726 entry.bytes_per_sample = 2;
3727 } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
3729 if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
3730 GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
3733 /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
3735 entry.fourcc = MS_WAVE_FOURCC (0x11);
3736 /* 4 byte header per channel (including one sample). 2 samples per byte
3737 remaining. Simplifying gives the following (samples per block per
3739 entry.samples_per_packet = 2 * blocksize / channels - 7;
3740 entry.bytes_per_sample = 2;
3742 entry.bytes_per_frame = blocksize;
3743 entry.bytes_per_packet = blocksize / channels;
3744 /* ADPCM has constant size packets */
3746 /* TODO: I don't really understand why this helps, but it does! Constant
3747 * size and compression_id of -2 seem to be incompatible, and other files
3748 * in the wild use this too. */
3749 entry.compression_id = -1;
3751 ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
3752 } else if (strcmp (mimetype, "audio/x-alac") == 0) {
3753 GstBuffer *codec_config;
3757 entry.fourcc = FOURCC_alac;
3758 gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
3759 /* let's check if codec data already comes with 'alac' atom prefix */
3760 if (!codec_data || (len = map.size) < 28) {
3761 GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
3762 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3765 if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
3768 gst_buffer_copy_region ((GstBuffer *) codec_data,
3769 GST_BUFFER_COPY_MEMORY, 8, len);
3771 codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
3773 gst_buffer_unmap ((GstBuffer *) codec_data, &map);
3775 /* does not look good, but perhaps some trailing unneeded stuff */
3776 GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
3778 if (format == GST_QT_MUX_FORMAT_QT)
3779 ext_atom = build_mov_alac_extension (codec_config);
3781 ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
3782 /* set some more info */
3783 gst_buffer_map (codec_config, &map, GST_MAP_READ);
3784 entry.bytes_per_sample = 2;
3785 entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
3786 gst_buffer_unmap (codec_config, &map);
3787 gst_buffer_unref (codec_config);
3788 } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
3789 entry.fourcc = FOURCC_ac_3;
3791 /* Fixed values according to TS 102 366 but it also mentions that
3792 * they should be ignored */
3794 entry.sample_size = 16;
3796 /* AC-3 needs an extension atom but its data can only be obtained from
3797 * the stream itself. Abuse the prepare_buf_func so we parse a frame
3798 * and get the needed data */
3799 qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
3800 } else if (strcmp (mimetype, "audio/x-opus") == 0) {
3801 /* Based on the specification defined in:
3802 * https://www.opus-codec.org/docs/opus_in_isobmff.html */
3803 guint8 channels, mapping_family, stream_count, coupled_count;
3807 guint8 channel_mapping[256];
3808 const GValue *streamheader;
3809 const GValue *first_element;
3812 entry.fourcc = FOURCC_opus;
3813 entry.sample_size = 16;
3815 streamheader = gst_structure_get_value (structure, "streamheader");
3816 if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
3817 gst_value_array_get_size (streamheader) != 0) {
3818 first_element = gst_value_array_get_value (streamheader, 0);
3819 header = gst_value_get_buffer (first_element);
3820 if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
3821 &mapping_family, &stream_count, &coupled_count, channel_mapping,
3822 &pre_skip, &output_gain)) {
3823 GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
3827 GST_WARNING_OBJECT (qtmux,
3828 "no streamheader field in caps %" GST_PTR_FORMAT, caps);
3830 if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
3831 &mapping_family, &stream_count, &coupled_count,
3833 GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
3840 entry.channels = channels;
3841 ext_atom = build_opus_extension (rate, channels, mapping_family,
3842 stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
3848 /* ok, set the pad info accordingly */
3849 qtpad->fourcc = entry.fourcc;
3850 qtpad->sample_size = constant_size;
3852 (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
3853 qtmux->context, &entry,
3854 qtmux->trak_timescale ? qtmux->trak_timescale : entry.sample_rate,
3855 ext_atom, constant_size);
3857 gst_object_unref (qtmux);
3863 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
3864 GST_PAD_NAME (pad), caps);
3865 gst_object_unref (qtmux);
3868 refuse_renegotiation:
3870 GST_WARNING_OBJECT (qtmux,
3871 "pad %s refused renegotiation to %" GST_PTR_FORMAT,
3872 GST_PAD_NAME (pad), caps);
3873 gst_object_unref (qtmux);
3878 /* scale rate up or down by factor of 10 to fit into [1000,10000] interval */
3880 adjust_rate (guint64 rate)
3885 while (rate >= 10000)
3891 return (guint32) rate;
3895 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
3897 GstPad *pad = qtpad->collect.pad;
3898 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
3899 GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3900 GstStructure *structure;
3901 const gchar *mimetype;
3902 gint width, height, depth = -1;
3903 gint framerate_num, framerate_den;
3905 const GValue *value = NULL;
3906 const GstBuffer *codec_data = NULL;
3907 VisualSampleEntry entry = { 0, };
3908 GstQTMuxFormat format;
3909 AtomInfo *ext_atom = NULL;
3910 GList *ext_atom_list = NULL;
3911 gboolean sync = FALSE;
3912 int par_num, par_den;
3914 qtpad->prepare_buf_func = NULL;
3916 /* does not go well to renegotiate stream mid-way, unless
3917 * the old caps are a subset of the new one (this means upstream
3918 * added more info to the caps, as both should be 'fixed' caps) */
3919 if (qtpad->fourcc) {
3920 GstCaps *current_caps;
3922 current_caps = gst_pad_get_current_caps (pad);
3923 g_assert (caps != NULL);
3925 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
3926 gst_caps_unref (current_caps);
3927 goto refuse_renegotiation;
3929 GST_DEBUG_OBJECT (qtmux,
3930 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
3931 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
3932 gst_caps_unref (current_caps);
3935 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
3936 GST_DEBUG_PAD_NAME (pad), caps);
3938 format = qtmux_klass->format;
3939 structure = gst_caps_get_structure (caps, 0);
3940 mimetype = gst_structure_get_name (structure);
3942 /* required parts */
3943 if (!gst_structure_get_int (structure, "width", &width) ||
3944 !gst_structure_get_int (structure, "height", &height))
3949 /* works as a default timebase */
3950 framerate_num = 10000;
3952 gst_structure_get_fraction (structure, "framerate", &framerate_num,
3954 gst_structure_get_int (structure, "depth", &depth);
3955 value = gst_structure_get_value (structure, "codec_data");
3957 codec_data = gst_value_get_buffer (value);
3961 gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
3964 qtpad->is_out_of_order = FALSE;
3966 /* bring frame numerator into a range that ensures both reasonable resolution
3967 * as well as a fair duration */
3968 rate = qtmux->trak_timescale ?
3969 qtmux->trak_timescale : adjust_rate (framerate_num);
3970 GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
3973 /* set common properties */
3974 entry.width = width;
3975 entry.height = height;
3976 entry.par_n = par_num;
3977 entry.par_d = par_den;
3978 /* should be OK according to qt and iso spec, override if really needed */
3979 entry.color_table_id = -1;
3980 entry.frame_count = 1;
3983 /* sync entries by default */
3986 /* now map onto a fourcc, and some extra properties */
3987 if (strcmp (mimetype, "video/x-raw") == 0) {
3988 const gchar *format;
3990 const GstVideoFormatInfo *vinfo;
3992 format = gst_structure_get_string (structure, "format");
3993 fmt = gst_video_format_from_string (format);
3994 vinfo = gst_video_format_get_info (fmt);
3997 case GST_VIDEO_FORMAT_UYVY:
4000 entry.fourcc = FOURCC_2vuy;
4001 entry.depth = depth;
4004 case GST_VIDEO_FORMAT_v210:
4007 entry.fourcc = FOURCC_v210;
4008 entry.depth = depth;
4012 if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
4013 entry.fourcc = FOURCC_raw_;
4014 entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
4019 } else if (strcmp (mimetype, "video/x-h263") == 0) {
4021 if (format == GST_QT_MUX_FORMAT_QT)
4022 entry.fourcc = FOURCC_h263;
4024 entry.fourcc = FOURCC_s263;
4025 ext_atom = build_h263_extension ();
4026 if (ext_atom != NULL)
4027 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4028 } else if (strcmp (mimetype, "video/x-divx") == 0 ||
4029 strcmp (mimetype, "video/mpeg") == 0) {
4032 if (strcmp (mimetype, "video/x-divx") == 0) {
4033 gst_structure_get_int (structure, "divxversion", &version);
4034 version = version == 5 ? 1 : 0;
4036 gst_structure_get_int (structure, "mpegversion", &version);
4037 version = version == 4 ? 1 : 0;
4040 entry.fourcc = FOURCC_mp4v;
4042 build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
4043 ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
4044 qtpad->max_bitrate);
4045 if (ext_atom != NULL)
4046 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4048 GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
4049 "output might not play in Apple QuickTime (try global-headers?)");
4051 } else if (strcmp (mimetype, "video/x-h264") == 0) {
4052 /* check if we accept these caps */
4053 if (gst_structure_has_field (structure, "stream-format")) {
4054 const gchar *format;
4055 const gchar *alignment;
4057 format = gst_structure_get_string (structure, "stream-format");
4058 alignment = gst_structure_get_string (structure, "alignment");
4060 if (strcmp (format, "avc") != 0 || alignment == NULL ||
4061 strcmp (alignment, "au") != 0) {
4062 GST_WARNING_OBJECT (qtmux, "Rejecting h264 caps, qtmux only accepts "
4063 "avc format with AU aligned samples");
4067 GST_WARNING_OBJECT (qtmux, "no stream-format field in h264 caps");
4072 GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
4076 entry.fourcc = FOURCC_avc1;
4077 if (qtpad->avg_bitrate == 0) {
4078 gint avg_bitrate = 0;
4079 gst_structure_get_int (structure, "bitrate", &avg_bitrate);
4080 qtpad->avg_bitrate = avg_bitrate;
4082 ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
4083 if (ext_atom != NULL)
4084 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4085 ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
4086 if (ext_atom != NULL)
4087 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4088 } else if (strcmp (mimetype, "video/x-svq") == 0) {
4090 const GstBuffer *seqh = NULL;
4091 const GValue *seqh_value;
4094 gst_structure_get_int (structure, "svqversion", &version);
4096 entry.fourcc = FOURCC_SVQ3;
4100 seqh_value = gst_structure_get_value (structure, "seqh");
4102 seqh = gst_value_get_buffer (seqh_value);
4103 ext_atom = build_SMI_atom (seqh);
4105 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4108 /* we need to add the gamma anyway because quicktime might crash
4109 * when it doesn't find it */
4110 if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
4111 /* it seems that using 0 here makes it ignored */
4114 ext_atom = build_gama_atom (gamma);
4116 ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
4118 GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
4119 "a bug at http://bugzilla.gnome.org", version);
4121 } else if (strcmp (mimetype, "video/x-dv") == 0) {
4123 gboolean pal = TRUE;
4126 if (framerate_num != 25 || framerate_den != 1)
4128 gst_structure_get_int (structure, "dvversion", &version);
4129 /* fall back to typical one */
4135 entry.fourcc = FOURCC_dvcp;
4137 entry.fourcc = FOURCC_dvc_;
4141 entry.fourcc = FOURCC_dv5p;
4143 entry.fourcc = FOURCC_dv5n;
4146 GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
4149 } else if (strcmp (mimetype, "image/jpeg") == 0) {
4150 entry.fourcc = FOURCC_jpeg;
4152 } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
4153 strcmp (mimetype, "image/x-jpc") == 0) {
4154 const gchar *colorspace;
4155 const GValue *cmap_array;
4156 const GValue *cdef_array;
4160 if (strcmp (mimetype, "image/x-jpc") == 0) {
4161 qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
4164 gst_structure_get_int (structure, "num-components", &ncomp);
4165 gst_structure_get_int (structure, "fields", &fields);
4166 cmap_array = gst_structure_get_value (structure, "component-map");
4167 cdef_array = gst_structure_get_value (structure, "channel-definitions");
4170 entry.fourcc = FOURCC_mjp2;
4173 colorspace = gst_structure_get_string (structure, "colorspace");
4176 build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
4177 cdef_array)) != NULL) {
4178 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4180 ext_atom = build_fiel_extension (fields);
4182 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4184 ext_atom = build_jp2x_extension (codec_data);
4186 ext_atom_list = g_list_append (ext_atom_list, ext_atom);
4188 GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
4191 } else if (strcmp (mimetype, "video/x-vp8") == 0) {
4192 entry.fourcc = FOURCC_VP80;
4194 } else if (strcmp (mimetype, "video/x-dirac") == 0) {
4195 entry.fourcc = FOURCC_drac;
4196 } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
4199 gst_structure_get_uint (structure, "format", &fourcc);
4200 entry.fourcc = fourcc;
4201 } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
4204 gst_structure_get_uint (structure, "format", &fourcc);
4205 entry.fourcc = fourcc;
4206 } else if (strcmp (mimetype, "video/x-prores") == 0) {
4207 const gchar *variant;
4209 variant = gst_structure_get_string (structure, "variant");
4210 if (!variant || !g_strcmp0 (variant, "standard"))
4211 entry.fourcc = FOURCC_apcn;
4212 else if (!g_strcmp0 (variant, "lt"))
4213 entry.fourcc = FOURCC_apcs;
4214 else if (!g_strcmp0 (variant, "hq"))
4215 entry.fourcc = FOURCC_apch;
4216 else if (!g_strcmp0 (variant, "proxy"))
4217 entry.fourcc = FOURCC_apco;
4223 /* ok, set the pad info accordingly */
4224 qtpad->fourcc = entry.fourcc;
4227 (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
4228 qtmux->context, &entry, rate, ext_atom_list);
4230 gst_object_unref (qtmux);
4236 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4237 GST_PAD_NAME (pad), caps);
4238 gst_object_unref (qtmux);
4241 refuse_renegotiation:
4243 GST_WARNING_OBJECT (qtmux,
4244 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4246 gst_object_unref (qtmux);
4252 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
4254 GstPad *pad = qtpad->collect.pad;
4255 GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
4256 GstStructure *structure;
4257 SubtitleSampleEntry entry = { 0, };
4259 /* does not go well to renegotiate stream mid-way, unless
4260 * the old caps are a subset of the new one (this means upstream
4261 * added more info to the caps, as both should be 'fixed' caps) */
4262 if (qtpad->fourcc) {
4263 GstCaps *current_caps;
4265 current_caps = gst_pad_get_current_caps (pad);
4266 g_assert (caps != NULL);
4268 if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
4269 gst_caps_unref (current_caps);
4270 goto refuse_renegotiation;
4272 GST_DEBUG_OBJECT (qtmux,
4273 "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
4274 GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
4275 gst_caps_unref (current_caps);
4278 GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
4279 GST_DEBUG_PAD_NAME (pad), caps);
4281 /* subtitles default */
4282 subtitle_sample_entry_init (&entry);
4283 qtpad->is_out_of_order = FALSE;
4284 qtpad->sync = FALSE;
4285 qtpad->sparse = TRUE;
4286 qtpad->prepare_buf_func = NULL;
4288 structure = gst_caps_get_structure (caps, 0);
4290 if (gst_structure_has_name (structure, "text/x-raw")) {
4291 const gchar *format = gst_structure_get_string (structure, "format");
4292 if (format && strcmp (format, "utf8") == 0) {
4293 entry.fourcc = FOURCC_tx3g;
4294 qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
4295 qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
4302 qtpad->fourcc = entry.fourcc;
4304 (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
4305 qtmux->context, &entry);
4307 gst_object_unref (qtmux);
4313 GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
4314 GST_PAD_NAME (pad), caps);
4315 gst_object_unref (qtmux);
4318 refuse_renegotiation:
4320 GST_WARNING_OBJECT (qtmux,
4321 "pad %s refused renegotiation to %" GST_PTR_FORMAT, GST_PAD_NAME (pad),
4323 gst_object_unref (qtmux);
4329 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
4330 GstEvent * event, gpointer user_data)
4333 guint32 avg_bitrate = 0, max_bitrate = 0;
4334 GstPad *pad = data->pad;
4335 gboolean ret = TRUE;
4337 qtmux = GST_QT_MUX_CAST (user_data);
4338 switch (GST_EVENT_TYPE (event)) {
4339 case GST_EVENT_CAPS:
4342 GstQTPad *collect_pad;
4344 gst_event_parse_caps (event, &caps);
4346 /* find stream data */
4347 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4348 g_assert (collect_pad);
4349 g_assert (collect_pad->set_caps);
4351 ret = collect_pad->set_caps (collect_pad, caps);
4352 gst_event_unref (event);
4356 case GST_EVENT_TAG:{
4358 GstTagSetter *setter = GST_TAG_SETTER (qtmux);
4359 GstTagMergeMode mode;
4361 GstQTPad *collect_pad;
4363 GST_OBJECT_LOCK (qtmux);
4364 mode = gst_tag_setter_get_tag_merge_mode (setter);
4365 collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
4367 gst_event_parse_tag (event, &list);
4368 GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
4369 GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
4371 if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
4372 gst_tag_setter_merge_tags (setter, list, mode);
4373 qtmux->tags_changed = TRUE;
4375 if (!collect_pad->tags)
4376 collect_pad->tags = gst_tag_list_new_empty ();
4377 gst_tag_list_insert (collect_pad->tags, list, mode);
4378 collect_pad->tags_changed = TRUE;
4380 GST_OBJECT_UNLOCK (qtmux);
4382 if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
4383 gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
4384 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4387 if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
4388 qtpad->avg_bitrate = avg_bitrate;
4389 if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
4390 qtpad->max_bitrate = max_bitrate;
4393 if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
4394 const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
4396 GstQTPad *qtpad = gst_pad_get_element_private (pad);
4399 /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
4400 qtpad->trak->mdia.mdhd.language_code =
4401 (iso_code[0] - 0x60) * 0x400 + (iso_code[1] - 0x60) * 0x20 +
4402 (iso_code[2] - 0x60);
4408 gst_event_unref (event);
4418 return gst_collect_pads_event_default (pads, data, event, FALSE);
4424 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
4426 GstQTMux *mux = GST_QT_MUX_CAST (element);
4429 GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
4431 for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
4432 GstQTPad *qtpad = (GstQTPad *) walk->data;
4433 GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
4434 if (qtpad->collect.pad == pad) {
4435 /* this is it, remove */
4436 mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
4437 gst_element_remove_pad (element, pad);
4442 gst_collect_pads_remove_pad (mux->collect, pad);
4446 gst_qt_mux_request_new_pad (GstElement * element,
4447 GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
4449 GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
4450 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4451 GstQTPad *collect_pad;
4453 GstQTPadSetCapsFunc setcaps_func;
4456 gboolean lock = TRUE;
4458 if (templ->direction != GST_PAD_SINK)
4459 goto wrong_direction;
4461 if (qtmux->state > GST_QT_MUX_STATE_STARTED)
4464 if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
4465 setcaps_func = gst_qt_mux_audio_sink_set_caps;
4466 if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
4467 name = g_strdup (req_name);
4469 name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
4471 } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
4472 setcaps_func = gst_qt_mux_video_sink_set_caps;
4473 if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
4474 name = g_strdup (req_name);
4476 name = g_strdup_printf ("video_%u", qtmux->video_pads++);
4478 } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
4479 setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
4480 if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
4481 name = g_strdup (req_name);
4483 name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
4487 goto wrong_template;
4489 GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
4491 /* create pad and add to collections */
4492 newpad = gst_pad_new_from_template (templ, name);
4494 collect_pad = (GstQTPad *)
4495 gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
4496 (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
4498 gst_qt_mux_pad_reset (collect_pad);
4499 collect_pad->trak = atom_trak_new (qtmux->context);
4500 atom_moov_add_trak (qtmux->moov, collect_pad->trak);
4502 qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
4504 /* set up pad functions */
4505 collect_pad->set_caps = setcaps_func;
4507 gst_pad_set_active (newpad, TRUE);
4508 gst_element_add_pad (element, newpad);
4515 GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
4520 GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
4525 GST_WARNING_OBJECT (qtmux, "This is not our template!");
4531 gst_qt_mux_get_property (GObject * object,
4532 guint prop_id, GValue * value, GParamSpec * pspec)
4534 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4536 GST_OBJECT_LOCK (qtmux);
4538 case PROP_MOVIE_TIMESCALE:
4539 g_value_set_uint (value, qtmux->timescale);
4541 case PROP_TRAK_TIMESCALE:
4542 g_value_set_uint (value, qtmux->trak_timescale);
4545 g_value_set_boolean (value, qtmux->guess_pts);
4547 #ifndef GST_REMOVE_DEPRECATED
4548 case PROP_DTS_METHOD:
4549 g_value_set_enum (value, qtmux->dts_method);
4552 case PROP_FAST_START:
4553 g_value_set_boolean (value, qtmux->fast_start);
4555 case PROP_FAST_START_TEMP_FILE:
4556 g_value_set_string (value, qtmux->fast_start_file_path);
4558 case PROP_MOOV_RECOV_FILE:
4559 g_value_set_string (value, qtmux->moov_recov_file_path);
4561 case PROP_FRAGMENT_DURATION:
4562 g_value_set_uint (value, qtmux->fragment_duration);
4564 case PROP_STREAMABLE:
4565 g_value_set_boolean (value, qtmux->streamable);
4567 case PROP_RESERVED_MAX_DURATION:
4568 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4570 case PROP_RESERVED_DURATION_REMAINING:
4571 if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
4572 g_value_set_uint64 (value, qtmux->reserved_max_duration);
4574 GstClockTime remaining = qtmux->reserved_duration_remaining;
4576 /* Report the remaining space as the calculated remaining, minus
4577 * however much we've muxed since the last update */
4578 if (remaining > qtmux->muxed_since_last_update)
4579 remaining -= qtmux->muxed_since_last_update;
4582 GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
4583 G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
4584 remaining, qtmux->reserved_duration_remaining,
4585 qtmux->muxed_since_last_update);
4586 g_value_set_uint64 (value, remaining);
4589 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4590 g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
4592 case PROP_RESERVED_BYTES_PER_SEC:
4593 g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
4596 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4599 GST_OBJECT_UNLOCK (qtmux);
4603 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
4607 g_free (qtmux->fast_start_file_path);
4608 qtmux->fast_start_file_path = NULL;
4610 tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
4611 qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
4616 gst_qt_mux_set_property (GObject * object,
4617 guint prop_id, const GValue * value, GParamSpec * pspec)
4619 GstQTMux *qtmux = GST_QT_MUX_CAST (object);
4621 GST_OBJECT_LOCK (qtmux);
4623 case PROP_MOVIE_TIMESCALE:
4624 qtmux->timescale = g_value_get_uint (value);
4626 case PROP_TRAK_TIMESCALE:
4627 qtmux->trak_timescale = g_value_get_uint (value);
4630 qtmux->guess_pts = g_value_get_boolean (value);
4632 #ifndef GST_REMOVE_DEPRECATED
4633 case PROP_DTS_METHOD:
4634 qtmux->dts_method = g_value_get_enum (value);
4637 case PROP_FAST_START:
4638 qtmux->fast_start = g_value_get_boolean (value);
4640 case PROP_FAST_START_TEMP_FILE:
4641 g_free (qtmux->fast_start_file_path);
4642 qtmux->fast_start_file_path = g_value_dup_string (value);
4643 /* NULL means to generate a random one */
4644 if (!qtmux->fast_start_file_path) {
4645 gst_qt_mux_generate_fast_start_file_path (qtmux);
4648 case PROP_MOOV_RECOV_FILE:
4649 g_free (qtmux->moov_recov_file_path);
4650 qtmux->moov_recov_file_path = g_value_dup_string (value);
4652 case PROP_FRAGMENT_DURATION:
4653 qtmux->fragment_duration = g_value_get_uint (value);
4655 case PROP_STREAMABLE:{
4656 GstQTMuxClass *qtmux_klass =
4657 (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4658 if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
4659 qtmux->streamable = g_value_get_boolean (value);
4663 case PROP_RESERVED_MAX_DURATION:
4664 qtmux->reserved_max_duration = g_value_get_uint64 (value);
4666 case PROP_RESERVED_MOOV_UPDATE_PERIOD:
4667 qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
4669 case PROP_RESERVED_BYTES_PER_SEC:
4670 qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
4673 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4676 GST_OBJECT_UNLOCK (qtmux);
4679 static GstStateChangeReturn
4680 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
4682 GstStateChangeReturn ret;
4683 GstQTMux *qtmux = GST_QT_MUX_CAST (element);
4685 switch (transition) {
4686 case GST_STATE_CHANGE_NULL_TO_READY:
4688 case GST_STATE_CHANGE_READY_TO_PAUSED:
4689 gst_collect_pads_start (qtmux->collect);
4690 qtmux->state = GST_QT_MUX_STATE_STARTED;
4691 qtmux->first_tc = NULL;
4694 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4696 case GST_STATE_CHANGE_PAUSED_TO_READY:
4697 gst_collect_pads_stop (qtmux->collect);
4703 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4705 switch (transition) {
4706 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4708 case GST_STATE_CHANGE_PAUSED_TO_READY:
4709 gst_qt_mux_reset (qtmux, TRUE);
4711 case GST_STATE_CHANGE_READY_TO_NULL:
4721 gst_qt_mux_register (GstPlugin * plugin)
4723 GTypeInfo typeinfo = {
4724 sizeof (GstQTMuxClass),
4725 (GBaseInitFunc) gst_qt_mux_base_init,
4727 (GClassInitFunc) gst_qt_mux_class_init,
4732 (GInstanceInitFunc) gst_qt_mux_init,
4734 static const GInterfaceInfo tag_setter_info = {
4737 static const GInterfaceInfo tag_xmp_writer_info = {
4740 static const GInterfaceInfo preset_info = {
4744 GstQTMuxFormat format;
4745 GstQTMuxClassParams *params;
4748 GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
4750 GST_LOG ("Registering muxers");
4753 GstQTMuxFormatProp *prop;
4754 GstCaps *subtitle_caps;
4756 prop = &gst_qt_mux_format_list[i];
4757 format = prop->format;
4758 if (format == GST_QT_MUX_FORMAT_NONE)
4761 /* create a cache for these properties */
4762 params = g_new0 (GstQTMuxClassParams, 1);
4763 params->prop = prop;
4764 params->src_caps = gst_static_caps_get (&prop->src_caps);
4765 params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
4766 params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
4767 subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
4768 if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
4769 params->subtitle_sink_caps = subtitle_caps;
4771 gst_caps_unref (subtitle_caps);
4774 /* create the type now */
4775 type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
4777 g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
4778 g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
4779 g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
4780 &tag_xmp_writer_info);
4781 g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
4783 if (!gst_element_register (plugin, prop->name, prop->rank, type))
4789 GST_LOG ("Finished registering muxers");
4791 /* FIXME: ideally classification tag should be added and
4792 registered in gstreamer core gsttaglist
4795 GST_LOG ("Registering tags");
4797 gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
4798 G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
4799 gst_tag_merge_use_first);
4801 GST_LOG ("Finished registering tags");