blob: 195fa2f01ce015160e104f724630ce60799f2065 [file] [log] [blame]
/* Quicktime muxer plugin for GStreamer
* Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
* Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
* Copyright (C) 2010 Nokia Corporation. All rights reserved.
* Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
* Contact: Stefan Kost <stefan.kost@nokia.com>
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* Unless otherwise indicated, Source Code is licensed under MIT license.
* See further explanation attached in License Statement (distributed in the file
* LICENSE).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* SECTION:element-qtmux
* @short_description: Muxer for quicktime(.mov) files
*
* This element merges streams (audio and video) into QuickTime(.mov) files.
*
* The following background intends to explain why various similar muxers
* are present in this plugin.
*
* The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
* QuickTime file format specification</ulink> served as basis for the MP4 file
* format specification (mp4mux), and as such the QuickTime file structure is
* nearly identical to the so-called ISO Base Media file format defined in
* ISO 14496-12 (except for some media specific parts).
* In turn, the latter ISO Base Media format was further specialized as a
* Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
* and in various 3GPP(2) specs (gppmux).
* The fragmented file features defined (only) in ISO Base Media are used by
* ISMV files making up (a.o.) Smooth Streaming (ismlmux).
*
* A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale,
* #GstQTMuxPad:trak-timescale) allow adjusting some technical parameters,
* which might be useful in (rare) cases to resolve compatibility issues in
* some situations.
*
* Some other properties influence the result more fundamentally.
* A typical mov/mp4 file's metadata (aka moov) is located at the end of the
* file, somewhat contrary to this usually being called "the header".
* However, a #GstQTMux:faststart file will (with some effort) arrange this to
* be located near start of the file, which then allows it e.g. to be played
* while downloading. Alternatively, rather than having one chunk of metadata at
* start (or end), there can be some metadata at start and most of the other
* data can be spread out into fragments of #GstQTMux:fragment-duration.
* If such fragmented layout is intended for streaming purposes, then
* #GstQTMux:streamable allows foregoing to add index metadata (at the end of
* file).
*
* When the maximum duration to be recorded can be known in advance, #GstQTMux
* also supports a 'Robust Muxing' mode. In robust muxing mode, space for the
* headers are reserved at the start of muxing, and rewritten at a configurable
* interval, so that the output file is always playable, even if the recording
* is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
* output, such as filesink, because it needs to rewrite the start of the file.
*
* To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
* and #GstQTMux::reserved-max-duration property. Also present is the
* #GstQTMux::reserved-bytes-per-sec property, which can be increased if
* for some reason the default is not large enough and the initial reserved
* space for headers is too small. Applications can monitor the
* #GstQTMux::reserved-duration-remaining property to see how close to full
* the reserved space is becoming.
*
* Applications that wish to be able to use/edit a file while it is being
* written to by live content, can use the "Robust Prefill Muxing" mode. That
* mode is a variant of the "Robust Muxing" mode in that it will pre-allocate a
* completely valid header from the start for all tracks (i.e. it appears as
* though the file is "reserved-max-duration" long with all samples
* present). This mode can be enabled by setting the
* #GstQTMux::reserved-moov-update-period and #GstQTMux::reserved-prefill
* properties. Note that this mode is only possible with input streams that have
* a fixed sample size (such as raw audio and Prores Video) and that don't
* have reordered samples.
*
* <refsect2>
* <title>Example pipelines</title>
* |[
* gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
* ]|
* Records a video stream captured from a v4l2 device and muxes it into a qt file.
* </refsect2>
*/
/*
* Based on avimux
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <glib/gstdio.h>
#include <gst/gst.h>
#include <gst/base/gstcollectpads.h>
#include <gst/base/gstbytereader.h>
#include <gst/base/gstbitreader.h>
#include <gst/audio/audio.h>
#include <gst/video/video.h>
#include <gst/tag/tag.h>
#include <gst/pbutils/pbutils.h>
#include <sys/types.h>
#ifdef G_OS_WIN32
#include <io.h> /* lseek, open, close, read */
#undef lseek
#define lseek _lseeki64
#undef off_t
#define off_t guint64
#endif
#ifdef _MSC_VER
#define ftruncate g_win32_ftruncate
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "gstqtmux.h"
GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
#define GST_CAT_DEFAULT gst_qt_mux_debug
#ifndef ABSDIFF
#define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
#endif
/* Hacker notes.
*
* The basic building blocks of MP4 files are:
* - an 'ftyp' box at the very start
* - an 'mdat' box which contains the raw audio/video/subtitle data;
* this is just a bunch of bytes, completely unframed and possibly
* unordered with no additional meta-information
* - a 'moov' box that contains information about the different streams
* and what they contain, as well as sample tables for each stream
* that tell the demuxer where in the mdat box each buffer/sample is
* and what its duration/timestamp etc. is, and whether it's a
* keyframe etc.
* Additionally, fragmented MP4 works by writing chunks of data in
* pairs of 'moof' and 'mdat' boxes:
* - 'moof' boxes, header preceding each mdat fragment describing the
* contents, like a moov but only for that fragment.
* - a 'mfra' box for Fragmented MP4, which is written at the end and
* contains a summary of all fragments and seek tables.
*
* Currently mp4mux can work in 4 different modes / generate 4 types
* of output files/streams:
*
* - Normal mp4: mp4mux will write a little ftyp identifier at the
* beginning, then start an mdat box into which it will write all the
* sample data. At EOS it will then write the moov header with track
* headers and sample tables at the end of the file, and rewrite the
* start of the file to fix up the mdat box size at the beginning.
* It has to wait for EOS to write the moov (which includes the
* sample tables) because it doesn't know how much space those
* tables will be. The output downstream must be seekable to rewrite
* the mdat box at EOS.
*
* - Fragmented mp4: moov header with track headers at start
* but no sample table, followed by N fragments, each containing
* track headers with sample tables followed by some data. Downstream
* does not need to be seekable if the 'streamable' flag is TRUE,
* as the final mfra and total duration will be omitted.
*
* - Fast-start mp4: the goal here is to create a file where the moov
* headers are at the beginning; what mp4mux will do is write all
* sample data into a temp file and build moov header plus sample
* tables in memory and then when EOS comes, it will push out the
* moov header plus sample tables at the beginning, followed by the
* mdat sample data at the end which is read in from the temp file
* Files created in this mode are better for streaming over the
* network, since the client doesn't have to seek to the end of the
* file to get the headers, but it requires copying all sample data
* out of the temp file at EOS, which can be expensive. Downstream does
* not need to be seekable, because of the use of the temp file.
*
* - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
* and reserved-moov-update-period properties to reserve free space
* at the start of the file and periodically write the MOOV atom out
* to it. That means that killing the muxing at any point still
* results in a playable file, at the cost of wasting some amount of
* free space at the start of file. The approximate recording duration
* has to be known in advance to estimate how much free space to reserve
* for the moov, and the downstream must be seekable.
* If the moov header grows larger than the reserved space, an error
* is generated - so it's better to over-estimate the amount of space
* to reserve. To ensure the file is playable at any point, the moov
* is updated using a 'ping-pong' strategy, so the output is never in
* an invalid state.
*/
#ifndef GST_REMOVE_DEPRECATED
enum
{
DTS_METHOD_DD,
DTS_METHOD_REORDER,
DTS_METHOD_ASC
};
static GType
gst_qt_mux_dts_method_get_type (void)
{
static GType gst_qt_mux_dts_method = 0;
if (!gst_qt_mux_dts_method) {
static const GEnumValue dts_methods[] = {
{DTS_METHOD_DD, "delta/duration", "dd"},
{DTS_METHOD_REORDER, "reorder", "reorder"},
{DTS_METHOD_ASC, "ascending", "asc"},
{0, NULL, NULL},
};
gst_qt_mux_dts_method =
g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
}
return gst_qt_mux_dts_method;
}
#define GST_TYPE_QT_MUX_DTS_METHOD \
(gst_qt_mux_dts_method_get_type ())
#endif
enum
{
PROP_PAD_0,
PROP_PAD_TRAK_TIMESCALE,
};
#define DEFAULT_PAD_TRAK_TIMESCALE 0
GType gst_qt_mux_pad_get_type (void);
#define GST_TYPE_QT_MUX_PAD \
(gst_qt_mux_pad_get_type())
#define GST_QT_MUX_PAD(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_QT_MUX_PAD, GstQTMuxPad))
#define GST_QT_MUX_PAD_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_QT_MUX_PAD, GstQTMuxPadClass))
#define GST_IS_QT_MUX_PAD(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_QT_MUX_PAD))
#define GST_IS_QT_MUX_PAD_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_QT_MUX_PAD))
#define GST_QT_MUX_PAD_CAST(obj) \
((GstQTMuxPad *)(obj))
typedef struct _GstQTMuxPad GstQTMuxPad;
typedef struct _GstQTMuxPadClass GstQTMuxPadClass;
struct _GstQTMuxPad
{
GstPad parent;
guint32 trak_timescale;
};
struct _GstQTMuxPadClass
{
GstPadClass parent;
};
G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_PAD);
static void
gst_qt_mux_pad_set_property (GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec)
{
GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
GST_OBJECT_LOCK (pad);
switch (prop_id) {
case PROP_PAD_TRAK_TIMESCALE:
pad->trak_timescale = g_value_get_uint (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
GST_OBJECT_UNLOCK (pad);
}
static void
gst_qt_mux_pad_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec)
{
GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
GST_OBJECT_LOCK (pad);
switch (prop_id) {
case PROP_PAD_TRAK_TIMESCALE:
g_value_set_uint (value, pad->trak_timescale);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
GST_OBJECT_UNLOCK (pad);
}
static void
gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
{
GObjectClass *gobject_class = (GObjectClass *) klass;
gobject_class->get_property = gst_qt_mux_pad_get_property;
gobject_class->set_property = gst_qt_mux_pad_set_property;
g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
g_param_spec_uint ("trak-timescale", "Track timescale",
"Timescale to use for this pad's trak (units per second, 0 is automatic)",
0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
}
static void
gst_qt_mux_pad_init (GstQTMuxPad * pad)
{
pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
}
static guint32
gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
{
guint32 timescale;
GST_OBJECT_LOCK (pad);
timescale = pad->trak_timescale;
GST_OBJECT_UNLOCK (pad);
return timescale;
}
/* QTMux signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_MOVIE_TIMESCALE,
PROP_TRAK_TIMESCALE,
PROP_FAST_START,
PROP_FAST_START_TEMP_FILE,
PROP_MOOV_RECOV_FILE,
PROP_FRAGMENT_DURATION,
PROP_STREAMABLE,
PROP_RESERVED_MAX_DURATION,
PROP_RESERVED_DURATION_REMAINING,
PROP_RESERVED_MOOV_UPDATE_PERIOD,
PROP_RESERVED_BYTES_PER_SEC,
PROP_RESERVED_PREFILL,
#ifndef GST_REMOVE_DEPRECATED
PROP_DTS_METHOD,
#endif
PROP_DO_CTTS,
PROP_INTERLEAVE_BYTES,
PROP_INTERLEAVE_TIME,
PROP_MAX_RAW_AUDIO_DRIFT,
};
/* some spare for header size as well */
#define MDAT_LARGE_FILE_LIMIT ((guint64) 1024 * 1024 * 1024 * 2)
#define DEFAULT_MOVIE_TIMESCALE 0
#define DEFAULT_TRAK_TIMESCALE 0
#define DEFAULT_DO_CTTS TRUE
#define DEFAULT_FAST_START FALSE
#define DEFAULT_FAST_START_TEMP_FILE NULL
#define DEFAULT_MOOV_RECOV_FILE NULL
#define DEFAULT_FRAGMENT_DURATION 0
#define DEFAULT_STREAMABLE TRUE
#ifndef GST_REMOVE_DEPRECATED
#define DEFAULT_DTS_METHOD DTS_METHOD_REORDER
#endif
#define DEFAULT_RESERVED_MAX_DURATION GST_CLOCK_TIME_NONE
#define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD GST_CLOCK_TIME_NONE
#define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
#define DEFAULT_RESERVED_PREFILL FALSE
#define DEFAULT_INTERLEAVE_BYTES 0
#define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
#define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
static void gst_qt_mux_finalize (GObject * object);
static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
GstStateChange transition);
/* property functions */
static void gst_qt_mux_set_property (GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_qt_mux_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec);
/* pad functions */
static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
/* event */
static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
GstCollectData * data, GstEvent * event, gpointer user_data);
static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
gpointer user_data);
static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
GstBuffer * buf);
static GstFlowReturn
gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
static GstElementClass *parent_class = NULL;
static void
gst_qt_mux_base_init (gpointer g_class)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
GstQTMuxClassParams *params;
GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
GstPadTemplate *srctempl;
gchar *longname, *description;
params =
(GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
GST_QT_MUX_PARAMS_QDATA);
g_assert (params != NULL);
/* construct the element details struct */
longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
description = g_strdup_printf ("Multiplex audio and video into a %s file",
params->prop->long_name);
gst_element_class_set_static_metadata (element_class, longname,
"Codec/Muxer", description,
"Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
g_free (longname);
g_free (description);
/* pad templates */
srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
GST_PAD_ALWAYS, params->src_caps);
gst_element_class_add_pad_template (element_class, srctempl);
if (params->audio_sink_caps) {
audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
GST_TYPE_QT_MUX_PAD);
gst_element_class_add_pad_template (element_class, audiosinktempl);
}
if (params->video_sink_caps) {
videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
GST_TYPE_QT_MUX_PAD);
gst_element_class_add_pad_template (element_class, videosinktempl);
}
if (params->subtitle_sink_caps) {
subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
GST_TYPE_QT_MUX_PAD);
gst_element_class_add_pad_template (element_class, subtitlesinktempl);
}
klass->format = params->prop->format;
}
static void
gst_qt_mux_class_init (GstQTMuxClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GParamFlags streamable_flags;
const gchar *streamable_desc;
gboolean streamable;
#define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
"be streamed and hence no indexes written or duration written."
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = gst_qt_mux_finalize;
gobject_class->get_property = gst_qt_mux_get_property;
gobject_class->set_property = gst_qt_mux_set_property;
streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
if (klass->format == GST_QT_MUX_FORMAT_ISML) {
streamable_desc = STREAMABLE_DESC;
streamable = DEFAULT_STREAMABLE;
} else {
streamable_desc =
STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
streamable_flags |= G_PARAM_DEPRECATED;
streamable = FALSE;
}
g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
g_param_spec_uint ("movie-timescale", "Movie timescale",
"Timescale to use in the movie (units per second, 0 == default)",
0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
g_param_spec_uint ("trak-timescale", "Track timescale",
"Timescale to use for the tracks (units per second, 0 is automatic)",
0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_DO_CTTS,
g_param_spec_boolean ("presentation-time",
"Include presentation-time info",
"Calculate and include presentation/composition time "
"(in addition to decoding time)", DEFAULT_DO_CTTS,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
#ifndef GST_REMOVE_DEPRECATED
g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
g_param_spec_enum ("dts-method", "dts-method",
"Method to determine DTS time (DEPRECATED)",
GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
G_PARAM_STATIC_STRINGS));
#endif
g_object_class_install_property (gobject_class, PROP_FAST_START,
g_param_spec_boolean ("faststart", "Format file to faststart",
"If the file should be formatted for faststart (headers first)",
DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
g_param_spec_string ("faststart-file", "File to use for storing buffers",
"File that will be used temporarily to store data from the stream "
"when creating a faststart file. If null a filepath will be "
"created automatically", DEFAULT_FAST_START_TEMP_FILE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
g_param_spec_string ("moov-recovery-file",
"File to store data for posterior moov atom recovery",
"File to be used to store "
"data for moov atom making movie file recovery possible in case "
"of a crash during muxing. Null for disabled. (Experimental)",
DEFAULT_MOOV_RECOV_FILE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
g_param_spec_uint ("fragment-duration", "Fragment duration",
"Fragment durations in ms (produce a fragmented file if > 0)",
0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
2000 : DEFAULT_FRAGMENT_DURATION,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_STREAMABLE,
g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
g_param_spec_uint64 ("reserved-max-duration",
"Reserved maximum file duration (ns)",
"When set to a value > 0, reserves space for index tables at the "
"beginning of the file.",
0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class,
PROP_RESERVED_DURATION_REMAINING,
g_param_spec_uint64 ("reserved-duration-remaining",
"Report the approximate amount of remaining recording space (ns)",
"Reports the approximate amount of remaining moov header space "
"reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class,
PROP_RESERVED_MOOV_UPDATE_PERIOD,
g_param_spec_uint64 ("reserved-moov-update-period",
"Interval at which to update index tables (ns)",
"When used with reserved-max-duration, periodically updates the "
"index tables with information muxed so far.", 0, G_MAXUINT64,
DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
g_param_spec_uint ("reserved-bytes-per-sec",
"Reserved MOOV bytes per second, per track",
"Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
g_param_spec_boolean ("reserved-prefill",
"Reserved Prefill Samples Table",
"Prefill samples table of reserved duration",
DEFAULT_RESERVED_PREFILL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
"Interleave between streams in bytes",
0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
g_param_spec_uint64 ("interleave-time", "Interleave (time)",
"Interleave between streams in nanoseconds",
0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
"Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
gstelement_class->request_new_pad =
GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
}
static void
gst_qt_mux_pad_reset (GstQTPad * qtpad)
{
qtpad->fourcc = 0;
qtpad->is_out_of_order = FALSE;
qtpad->sample_size = 0;
qtpad->sync = FALSE;
qtpad->last_dts = 0;
qtpad->sample_offset = 0;
qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
qtpad->first_ts = GST_CLOCK_TIME_NONE;
qtpad->first_dts = GST_CLOCK_TIME_NONE;
qtpad->prepare_buf_func = NULL;
qtpad->create_empty_buffer = NULL;
qtpad->avg_bitrate = 0;
qtpad->max_bitrate = 0;
qtpad->total_duration = 0;
qtpad->total_bytes = 0;
qtpad->sparse = FALSE;
gst_buffer_replace (&qtpad->last_buf, NULL);
if (qtpad->tags) {
gst_tag_list_unref (qtpad->tags);
qtpad->tags = NULL;
}
/* reference owned elsewhere */
qtpad->trak = NULL;
qtpad->tc_trak = NULL;
if (qtpad->traf) {
atom_traf_free (qtpad->traf);
qtpad->traf = NULL;
}
atom_array_clear (&qtpad->fragment_buffers);
if (qtpad->samples)
g_array_unref (qtpad->samples);
qtpad->samples = NULL;
/* reference owned elsewhere */
qtpad->tfra = NULL;
qtpad->first_pts = GST_CLOCK_TIME_NONE;
qtpad->tc_pos = -1;
if (qtpad->first_tc)
gst_video_time_code_free (qtpad->first_tc);
qtpad->first_tc = NULL;
if (qtpad->raw_audio_adapter)
gst_object_unref (qtpad->raw_audio_adapter);
qtpad->raw_audio_adapter = NULL;
}
/*
* Takes GstQTMux back to its initial state
*/
static void
gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
{
GSList *walk;
qtmux->state = GST_QT_MUX_STATE_NONE;
qtmux->header_size = 0;
qtmux->mdat_size = 0;
qtmux->moov_pos = 0;
qtmux->mdat_pos = 0;
qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
qtmux->fragment_sequence = 0;
if (qtmux->ftyp) {
atom_ftyp_free (qtmux->ftyp);
qtmux->ftyp = NULL;
}
if (qtmux->moov) {
atom_moov_free (qtmux->moov);
qtmux->moov = NULL;
}
if (qtmux->mfra) {
atom_mfra_free (qtmux->mfra);
qtmux->mfra = NULL;
}
if (qtmux->fast_start_file) {
fclose (qtmux->fast_start_file);
g_remove (qtmux->fast_start_file_path);
qtmux->fast_start_file = NULL;
}
if (qtmux->moov_recov_file) {
fclose (qtmux->moov_recov_file);
qtmux->moov_recov_file = NULL;
}
for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
AtomInfo *ainfo = (AtomInfo *) walk->data;
ainfo->free_func (ainfo->atom);
g_free (ainfo);
}
g_slist_free (qtmux->extra_atoms);
qtmux->extra_atoms = NULL;
GST_OBJECT_LOCK (qtmux);
gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
GST_OBJECT_UNLOCK (qtmux);
/* reset pad data */
for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
GstQTPad *qtpad = (GstQTPad *) walk->data;
gst_qt_mux_pad_reset (qtpad);
/* hm, moov_free above yanked the traks away from us,
* so do not free, but do clear */
qtpad->trak = NULL;
}
if (alloc) {
qtmux->moov = atom_moov_new (qtmux->context);
/* ensure all is as nice and fresh as request_new_pad would provide it */
for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
GstQTPad *qtpad = (GstQTPad *) walk->data;
qtpad->trak = atom_trak_new (qtmux->context);
atom_moov_add_trak (qtmux->moov, qtpad->trak);
}
}
qtmux->current_pad = NULL;
qtmux->current_chunk_size = 0;
qtmux->current_chunk_duration = 0;
qtmux->current_chunk_offset = -1;
qtmux->reserved_moov_size = 0;
qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
qtmux->muxed_since_last_update = 0;
qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
}
static void
gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
{
GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
GstPadTemplate *templ;
templ = gst_element_class_get_pad_template (klass, "src");
qtmux->srcpad = gst_pad_new_from_template (templ, "src");
gst_pad_use_fixed_caps (qtmux->srcpad);
gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
qtmux->sinkpads = NULL;
qtmux->collect = gst_collect_pads_new ();
gst_collect_pads_set_event_function (qtmux->collect,
GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
gst_collect_pads_set_clip_function (qtmux->collect,
GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
gst_collect_pads_set_function (qtmux->collect,
GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
/* properties set to default upon construction */
qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
qtmux->reserved_bytes_per_sec_per_trak =
DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
/* always need this */
qtmux->context =
atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
/* internals to initial state */
gst_qt_mux_reset (qtmux, TRUE);
}
static void
gst_qt_mux_finalize (GObject * object)
{
GstQTMux *qtmux = GST_QT_MUX_CAST (object);
gst_qt_mux_reset (qtmux, FALSE);
g_free (qtmux->fast_start_file_path);
g_free (qtmux->moov_recov_file_path);
atoms_context_free (qtmux->context);
gst_object_unref (qtmux->collect);
g_slist_free (qtmux->sinkpads);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static GstBuffer *
gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
GstQTMux * qtmux)
{
GstBuffer *newbuf;
GstMapInfo map;
gsize size;
GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
if (buf == NULL)
return NULL;
size = gst_buffer_get_size (buf);
newbuf = gst_buffer_new_and_alloc (size + 8);
gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
GST_WRITE_UINT32_BE (map.data, map.size);
GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
gst_buffer_unmap (buf, &map);
gst_buffer_unref (buf);
return newbuf;
}
static GstBuffer *
gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
GstQTMux * qtmux)
{
GstBuffer *newbuf;
GstMapInfo frommap;
GstMapInfo tomap;
gsize size;
const guint8 *dataend;
GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
if (buf == NULL)
return NULL;
gst_buffer_map (buf, &frommap, GST_MAP_READ);
dataend = memchr (frommap.data, 0, frommap.size);
size = dataend ? dataend - frommap.data : frommap.size;
newbuf = gst_buffer_new_and_alloc (size + 2);
gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
GST_WRITE_UINT16_BE (tomap.data, size);
memcpy (tomap.data + 2, frommap.data, size);
gst_buffer_unmap (newbuf, &tomap);
gst_buffer_unmap (buf, &frommap);
gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
/* gst_buffer_copy_into is trying to be too clever and
* won't copy duration when size is different */
GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
gst_buffer_unref (buf);
return newbuf;
}
static void
gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
guint8 lfe_on)
{
AtomInfo *ext;
g_return_if_fail (qtpad->trak_ste);
ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1); /* bitrate_code is inside frmsizcod */
sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
}
static GstBuffer *
gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
GstQTMux * qtmux)
{
GstMapInfo map;
GstByteReader reader;
guint off;
if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
return buf;
}
if (G_UNLIKELY (map.size < 8))
goto done;
gst_byte_reader_init (&reader, map.data, map.size);
off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
0, map.size);
if (off != -1) {
GstBitReader bits;
guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
off);
gst_bit_reader_init (&bits, map.data, map.size);
/* off + sync + crc */
gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
if ((acmod & 0x1) && (acmod != 0x1)) /* 3 front channels */
gst_bit_reader_skip_unchecked (&bits, 2);
if ((acmod & 0x4)) /* if a surround channel exists */
gst_bit_reader_skip_unchecked (&bits, 2);
if (acmod == 0x2) /* if in 2/0 mode */
gst_bit_reader_skip_unchecked (&bits, 2);
lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
bsmod, acmod, lfe_on);
/* AC-3 spec says that those values should be constant for the
* whole stream when muxed in mp4. We trust the input follows it */
GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
"prepare buffer function");
qtpad->prepare_buf_func = NULL;
}
done:
gst_buffer_unmap (buf, &map);
return buf;
}
static GstBuffer *
gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
{
guint8 *data;
data = g_malloc (2);
GST_WRITE_UINT16_BE (data, 0);
return gst_buffer_new_wrapped (data, 2);
}
static void
gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
switch (gst_tag_get_type (tag)) {
/* strings */
case G_TYPE_STRING:
{
gchar *str = NULL;
if (!gst_tag_list_get_string (list, tag, &str) || !str)
break;
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
GST_FOURCC_ARGS (fourcc), str);
atom_udta_add_str_tag (udta, fourcc, str);
g_free (str);
break;
}
/* double */
case G_TYPE_DOUBLE:
{
gdouble value;
if (!gst_tag_list_get_double (list, tag, &value))
break;
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
GST_FOURCC_ARGS (fourcc), (gint) value);
atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
break;
}
case G_TYPE_UINT:
{
guint value = 0;
if (tag2) {
/* paired unsigned integers */
guint count = 0;
gboolean got_tag;
got_tag = gst_tag_list_get_uint (list, tag, &value);
got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
if (!got_tag)
break;
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
GST_FOURCC_ARGS (fourcc), value, count);
atom_udta_add_uint_tag (udta, fourcc, 0,
value << 16 | (count & 0xFFFF));
} else {
/* unpaired unsigned integers */
if (!gst_tag_list_get_uint (list, tag, &value))
break;
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
GST_FOURCC_ARGS (fourcc), value);
atom_udta_add_uint_tag (udta, fourcc, 1, value);
}
break;
}
default:
g_assert_not_reached ();
break;
}
}
static void
gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
GDate *date = NULL;
GDateYear year;
GDateMonth month;
GDateDay day;
gchar *str;
g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
if (!gst_tag_list_get_date (list, tag, &date) || !date)
return;
year = g_date_get_year (date);
month = g_date_get_month (date);
day = g_date_get_day (date);
g_date_free (date);
if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
day == G_DATE_BAD_DAY) {
GST_WARNING_OBJECT (qtmux, "invalid date in tag");
return;
}
str = g_strdup_printf ("%u-%u-%u", year, month, day);
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
GST_FOURCC_ARGS (fourcc), str);
atom_udta_add_str_tag (udta, fourcc, str);
g_free (str);
}
static void
gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
GValue value = { 0, };
GstBuffer *buf;
GstSample *sample;
GstCaps *caps;
GstStructure *structure;
gint flags = 0;
GstMapInfo map;
g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
if (!gst_tag_list_copy_value (&value, list, tag))
return;
sample = gst_value_get_sample (&value);
if (!sample)
goto done;
buf = gst_sample_get_buffer (sample);
if (!buf)
goto done;
caps = gst_sample_get_caps (sample);
if (!caps) {
GST_WARNING_OBJECT (qtmux, "preview image without caps");
goto done;
}
GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
structure = gst_caps_get_structure (caps, 0);
if (gst_structure_has_name (structure, "image/jpeg"))
flags = 13;
else if (gst_structure_has_name (structure, "image/png"))
flags = 14;
if (!flags) {
GST_WARNING_OBJECT (qtmux, "preview image format not supported");
goto done;
}
gst_buffer_map (buf, &map, GST_MAP_READ);
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
" -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
gst_buffer_unmap (buf, &map);
done:
g_value_unset (&value);
}
static void
gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
gchar *str = NULL;
guint number;
g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
if (!gst_tag_list_get_string (list, tag, &str) || !str)
return;
if (tag2)
if (!gst_tag_list_get_uint (list, tag2, &number))
tag2 = NULL;
if (!tag2) {
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
GST_FOURCC_ARGS (fourcc), str);
atom_udta_add_3gp_str_tag (udta, fourcc, str);
} else {
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
GST_FOURCC_ARGS (fourcc), str, number);
atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
}
g_free (str);
}
static void
gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
GDate *date = NULL;
GDateYear year;
g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
if (!gst_tag_list_get_date (list, tag, &date) || !date)
return;
year = g_date_get_year (date);
g_date_free (date);
if (year == G_DATE_BAD_YEAR) {
GST_WARNING_OBJECT (qtmux, "invalid date in tag");
return;
}
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
GST_FOURCC_ARGS (fourcc), year);
atom_udta_add_3gp_uint_tag (udta, fourcc, year);
}
static void
gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
gdouble latitude = -360, longitude = -360, altitude = 0;
gchar *location = NULL;
guint8 *data, *ddata;
gint size = 0, len = 0;
gboolean ret = FALSE;
g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
ret = gst_tag_list_get_string (list, tag, &location);
ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
&longitude);
ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
&latitude);
ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
&altitude);
if (!ret)
return;
if (location)
len = strlen (location);
size += len + 1 + 2;
/* role + (long, lat, alt) + body + notes */
size += 1 + 3 * 4 + 1 + 1;
data = ddata = g_malloc (size);
/* language tag */
GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
/* location */
if (location)
memcpy (data + 2, location, len);
GST_WRITE_UINT8 (data + 2 + len, 0);
data += len + 1 + 2;
/* role */
GST_WRITE_UINT8 (data, 0);
/* long, lat, alt */
#define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
QT_WRITE_SFP32 (data + 1, longitude);
QT_WRITE_SFP32 (data + 5, latitude);
QT_WRITE_SFP32 (data + 9, altitude);
/* neither astronomical body nor notes */
GST_WRITE_UINT16_BE (data + 13, 0);
GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
g_free (ddata);
}
static void
gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
gchar *keywords = NULL;
guint8 *data, *ddata;
gint size = 0, i;
gchar **kwds;
g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
return;
kwds = g_strsplit (keywords, ",", 0);
g_free (keywords);
size = 0;
for (i = 0; kwds[i]; i++) {
/* size byte + null-terminator */
size += strlen (kwds[i]) + 1 + 1;
}
/* language tag + count + keywords */
size += 2 + 1;
data = ddata = g_malloc (size);
/* language tag */
GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
/* count */
GST_WRITE_UINT8 (data + 2, i);
data += 3;
/* keywords */
for (i = 0; kwds[i]; ++i) {
gint len = strlen (kwds[i]);
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
GST_FOURCC_ARGS (fourcc), kwds[i]);
/* size */
GST_WRITE_UINT8 (data, len + 1);
memcpy (data + 1, kwds[i], len + 1);
data += len + 2;
}
g_strfreev (kwds);
atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
g_free (ddata);
}
static gboolean
gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
{
guint32 fourcc;
gint table;
gint size;
const gchar *data;
data = input;
size = strlen (input);
if (size < 4 + 3 + 1 + 1 + 1) {
/* at least the minimum xxxx://y/z */
GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
"ignoring", input);
return FALSE;
}
/* read the fourcc */
memcpy (&fourcc, data, 4);
size -= 4;
data += 4;
if (strncmp (data, "://", 3) != 0) {
goto mismatch;
}
data += 3;
size -= 3;
/* read the table number */
if (sscanf (data, "%d", &table) != 1) {
goto mismatch;
}
if (table < 0) {
GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
", table numbers should be positive, ignoring tag", table);
return FALSE;
}
/* find the next / */
while (size > 0 && data[0] != '/') {
data += 1;
size -= 1;
}
if (size == 0) {
goto mismatch;
}
g_assert (data[0] == '/');
/* skip the '/' */
data += 1;
size -= 1;
if (size == 0) {
goto mismatch;
}
/* read up the rest of the string */
*p_content = g_strdup (data);
*p_table = (guint16) table;
*p_fourcc = fourcc;
return TRUE;
mismatch:
{
GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
"input (%s) didn't match the expected entitycode://table/content",
input);
return FALSE;
}
}
static void
gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
{
gchar *clsf_data = NULL;
gint size = 0;
guint32 entity = 0;
guint16 table = 0;
gchar *content = NULL;
guint8 *data;
g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
return;
GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
GST_FOURCC_ARGS (fourcc), clsf_data);
/* parse the string, format is:
* entityfourcc://table/content
*/
gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
&content);
g_free (clsf_data);
/* +1 for the \0 */
size = strlen (content) + 1;
/* now we have everything, build the atom
* atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
data = g_malloc (4 + 2 + 2 + size);
GST_WRITE_UINT32_LE (data, entity);
GST_WRITE_UINT16_BE (data + 4, (guint16) table);
GST_WRITE_UINT16_BE (data + 6, 0);
memcpy (data + 8, content, size);
g_free (content);
atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
g_free (data);
}
typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
const GstTagList * list, AtomUDTA * udta, const char *tag,
const char *tag2, guint32 fourcc);
/*
* Struct to record mappings from gstreamer tags to fourcc codes
*/
typedef struct _GstTagToFourcc
{
guint32 fourcc;
const gchar *gsttag;
const gchar *gsttag2;
const GstQTMuxAddUdtaTagFunc func;
} GstTagToFourcc;
/* tag list tags to fourcc matching */
static const GstTagToFourcc tag_matches_mp4[] = {
{FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
{FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
{FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
gst_qt_mux_add_mp4_tag},
{FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
gst_qt_mux_add_mp4_tag},
{FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
{FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
{0, NULL,}
};
static const GstTagToFourcc tag_matches_3gp[] = {
{FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
{FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
{FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
{FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
{FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
{FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
gst_qt_mux_add_3gp_classification},
{0, NULL,}
};
/* qtdemux produces these for atoms it cannot parse */
#define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
static void
gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
{
GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
GstBuffer *xmp = NULL;
/* adobe specs only have 'quicktime' and 'mp4',
* but I guess we can extrapolate to gpp.
* Keep mj2 out for now as we don't add any tags for it yet.
* If you have further info about xmp on these formats, please share */
if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
return;
GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
list, TRUE);
if (xmp)
atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
} else {
AtomInfo *ainfo;
/* for isom/mp4, it is a top level uuid atom */
xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
list, TRUE);
if (xmp) {
ainfo = build_uuid_xmp_atom (xmp);
if (ainfo) {
qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
}
}
}
if (xmp)
gst_buffer_unref (xmp);
}
static void
gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
AtomUDTA * udta)
{
GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
guint32 fourcc;
gint i;
const gchar *tag, *tag2;
const GstTagToFourcc *tag_matches;
switch (qtmux_klass->format) {
case GST_QT_MUX_FORMAT_3GP:
tag_matches = tag_matches_3gp;
break;
case GST_QT_MUX_FORMAT_MJ2:
tag_matches = NULL;
break;
default:
/* sort of iTunes style for mp4 and QT (?) */
tag_matches = tag_matches_mp4;
break;
}
if (!tag_matches)
return;
/* Clear existing tags so we don't add them over and over */
atom_udta_clear_tags (udta);
for (i = 0; tag_matches[i].fourcc; i++) {
fourcc = tag_matches[i].fourcc;
tag = tag_matches[i].gsttag;
tag2 = tag_matches[i].gsttag2;
g_assert (tag_matches[i].func);
tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
}
/* add unparsed blobs if present */
if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
guint num_tags;
num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
for (i = 0; i < num_tags; ++i) {
GstSample *sample = NULL;
GstBuffer *buf;
const GstStructure *s;
if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
&sample))
continue;
buf = gst_sample_get_buffer (sample);
if (buf && (s = gst_sample_get_info (sample))) {
const gchar *style = NULL;
GstMapInfo map;
gst_buffer_map (buf, &map, GST_MAP_READ);
GST_DEBUG_OBJECT (qtmux,
"Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
GST_PTR_FORMAT, i, num_tags, map.size, s);
if (s && (style = gst_structure_get_string (s, "style"))) {
/* try to prevent some style tag ending up into another variant
* (todo: make into a list if more cases) */
if ((strcmp (style, "itunes") == 0 &&
qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
(strcmp (style, "iso") == 0 &&
qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
GST_DEBUG_OBJECT (qtmux, "Adding private tag");
atom_udta_add_blob_tag (udta, map.data, map.size);
}
}
gst_buffer_unmap (buf, &map);
}
gst_sample_unref (sample);
}
}
return;
}
/*
* Gets the tagsetter iface taglist and puts the known tags
* into the output stream
*/
static void
gst_qt_mux_setup_metadata (GstQTMux * qtmux)
{
const GstTagList *tags = NULL;
GSList *walk;
GST_OBJECT_LOCK (qtmux);
if (qtmux->tags_changed) {
tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
qtmux->tags_changed = FALSE;
}
GST_OBJECT_UNLOCK (qtmux);
GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
if (tags && !gst_tag_list_is_empty (tags)) {
GstTagList *copy = gst_tag_list_copy (tags);
GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
GST_DEBUG_OBJECT (qtmux, "Formatting tags");
gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
gst_qt_mux_add_xmp_tags (qtmux, copy);
gst_tag_list_unref (copy);
} else {
GST_DEBUG_OBJECT (qtmux, "No new tags received");
}
for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qpad = (GstQTPad *) cdata;
GstPad *pad = qpad->collect.pad;
if (qpad->tags_changed && qpad->tags) {
GST_DEBUG_OBJECT (pad, "Adding tags");
gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
qpad->tags_changed = FALSE;
GST_DEBUG_OBJECT (pad, "Tags added");
} else {
GST_DEBUG_OBJECT (pad, "No new tags received");
}
}
}
static inline GstBuffer *
_gst_buffer_new_take_data (guint8 * data, guint size)
{
GstBuffer *buf;
buf = gst_buffer_new ();
gst_buffer_append_memory (buf,
gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
return buf;
}
static GstFlowReturn
gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
gboolean mind_fast)
{
GstFlowReturn res;
gsize size;
g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
size = gst_buffer_get_size (buf);
GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
if (mind_fast && qtmux->fast_start_file) {
GstMapInfo map;
gint ret;
GST_LOG_OBJECT (qtmux, "to temporary file");
gst_buffer_map (buf, &map, GST_MAP_READ);
ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
gst_buffer_unmap (buf, &map);
gst_buffer_unref (buf);
if (ret != size)
goto write_error;
else
res = GST_FLOW_OK;
} else {
GST_LOG_OBJECT (qtmux, "downstream");
res = gst_pad_push (qtmux->srcpad, buf);
}
if (G_LIKELY (offset))
*offset += size;
return res;
/* ERRORS */
write_error:
{
GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
("Failed to write to temporary file"), GST_ERROR_SYSTEM);
return GST_FLOW_ERROR;
}
}
static gboolean
gst_qt_mux_seek_to_beginning (FILE * f)
{
#ifdef HAVE_FSEEKO
if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
return FALSE;
#elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
return FALSE;
#else
if (fseek (f, (long) 0, SEEK_SET) != 0)
return FALSE;
#endif
return TRUE;
}
static GstFlowReturn
gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
{
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *buf = NULL;
if (fflush (qtmux->fast_start_file))
goto flush_failed;
if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
goto seek_failed;
/* hm, this could all take a really really long time,
* but there may not be another way to get moov atom first
* (somehow optimize copy?) */
GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
while (ret == GST_FLOW_OK) {
const int bufsize = 4096;
GstMapInfo map;
gsize size;
buf = gst_buffer_new_and_alloc (bufsize);
gst_buffer_map (buf, &map, GST_MAP_WRITE);
size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
if (size == 0) {
gst_buffer_unmap (buf, &map);
break;
}
GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
gst_buffer_unmap (buf, &map);
if (size != bufsize)
gst_buffer_set_size (buf, size);
ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
buf = NULL;
}
if (buf)
gst_buffer_unref (buf);
if (ftruncate (fileno (qtmux->fast_start_file), 0))
goto seek_failed;
if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
goto seek_failed;
return ret;
/* ERRORS */
flush_failed:
{
GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
("Failed to flush temporary file"), GST_ERROR_SYSTEM);
ret = GST_FLOW_ERROR;
goto fail;
}
seek_failed:
{
GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
("Failed to seek temporary file"), GST_ERROR_SYSTEM);
ret = GST_FLOW_ERROR;
goto fail;
}
fail:
{
/* clear descriptor so we don't remove temp file later on,
* might be possible to recover */
fclose (qtmux->fast_start_file);
qtmux->fast_start_file = NULL;
return ret;
}
}
/*
* Sends the initial mdat atom fields (size fields and fourcc type),
* the subsequent buffers are considered part of it's data.
* As we can't predict the amount of data that we are going to place in mdat
* we need to record the position of the size field in the stream so we can
* seek back to it later and update when the streams have finished.
*/
static GstFlowReturn
gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
gboolean extended, gboolean fsync_after)
{
GstBuffer *buf;
GstMapInfo map;
GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
"size %" G_GUINT64_FORMAT, size);
/* if the qtmux state is EOS, really write the mdat, otherwise
* allow size == 0 for a placeholder atom */
if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
size += 8;
if (extended) {
gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
/* Always write 16-bytes, but put a free atom first
* if the size is < 4GB. */
buf = gst_buffer_new_and_alloc (16);
gst_buffer_map (buf, &map, GST_MAP_WRITE);
if (large_file) {
/* Write extended mdat header and large_size field */
GST_WRITE_UINT32_BE (map.data, 1);
GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
GST_WRITE_UINT64_BE (map.data + 8, size + 8);
} else {
/* Write an empty free atom, then standard 32-bit mdat */
GST_WRITE_UINT32_BE (map.data, 8);
GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
GST_WRITE_UINT32_BE (map.data + 8, size);
GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
}
gst_buffer_unmap (buf, &map);
} else {
buf = gst_buffer_new_and_alloc (8);
gst_buffer_map (buf, &map, GST_MAP_WRITE);
/* Vanilla 32-bit mdat */
GST_WRITE_UINT32_BE (map.data, size);
GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
gst_buffer_unmap (buf, &map);
}
GST_LOG_OBJECT (qtmux, "Pushing mdat header");
if (fsync_after)
GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
}
/*
* We get the position of the mdat size field, seek back to it
* and overwrite with the real value
*/
static GstFlowReturn
gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
guint64 mdat_size, guint64 * offset, gboolean fsync_after)
{
GstSegment segment;
/* We must have recorded the mdat position for this to work */
g_assert (mdat_pos != 0);
/* seek and rewrite the header */
gst_segment_init (&segment, GST_FORMAT_BYTES);
segment.start = mdat_pos;
gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
fsync_after);
}
static GstFlowReturn
gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
{
GstBuffer *buf;
guint64 size = 0, offset = 0;
guint8 *data = NULL;
GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
goto serialize_error;
buf = _gst_buffer_new_take_data (data, offset);
GST_LOG_OBJECT (qtmux, "Pushing ftyp");
return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
/* ERRORS */
serialize_error:
{
GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
("Failed to serialize ftyp"));
return GST_FLOW_ERROR;
}
}
static void
gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
GstBuffer ** p_prefix)
{
GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
guint32 major, version;
GList *comp;
GstBuffer *prefix = NULL;
AtomFTYP *ftyp = NULL;
GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
/* init and send context and ftyp based on current property state */
gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
&version, &comp, qtmux->moov, qtmux->longest_chunk,
qtmux->fast_start_file != NULL);
ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
if (comp)
g_list_free (comp);
if (prefix) {
if (p_prefix)
*p_prefix = prefix;
else
gst_buffer_unref (prefix);
}
*p_ftyp = ftyp;
}
static GstFlowReturn
gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
{
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *prefix = NULL;
GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
/* init and send context and ftyp based on current property state */
if (qtmux->ftyp) {
atom_ftyp_free (qtmux->ftyp);
qtmux->ftyp = NULL;
}
gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
if (prefix) {
ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
if (ret != GST_FLOW_OK)
return ret;
}
return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
}
static void
gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
{
GstStructure *structure;
GValue array = { 0 };
GValue value = { 0 };
GstCaps *caps, *tcaps;
tcaps = gst_pad_get_current_caps (mux->srcpad);
caps = gst_caps_copy (tcaps);
gst_caps_unref (tcaps);
structure = gst_caps_get_structure (caps, 0);
g_value_init (&array, GST_TYPE_ARRAY);
GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
g_value_init (&value, GST_TYPE_BUFFER);
gst_value_take_buffer (&value, gst_buffer_ref (buf));
gst_value_array_append_value (&array, &value);
g_value_unset (&value);
gst_structure_set_value (structure, "streamheader", &array);
g_value_unset (&array);
gst_pad_set_caps (mux->srcpad, caps);
gst_caps_unref (caps);
}
/*
* Write out a free space atom. The offset is adjusted by the full
* size, but a smaller buffer is sent
*/
static GstFlowReturn
gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
gboolean fsync_after)
{
Atom *node_header;
GstBuffer *buf;
guint8 *data = NULL;
guint64 offset = 0, bsize = 0;
GstFlowReturn ret;
GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
/* We can't make a free space atom smaller than the header */
if (size < 8)
goto too_small;
node_header = g_malloc0 (sizeof (Atom));
node_header->type = FOURCC_free;
node_header->size = size;
bsize = offset = 0;
if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
goto serialize_error;
buf = _gst_buffer_new_take_data (data, offset);
g_free (node_header);
if (fsync_after)
GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
GST_LOG_OBJECT (qtmux, "Pushing free atom");
ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
if (off) {
GstSegment segment;
*off += size - 8;
/* Make sure downstream position ends up at the end of this free box */
gst_segment_init (&segment, GST_FORMAT_BYTES);
segment.start = *off;
gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
}
return ret;
/* ERRORS */
too_small:
{
GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
("Not enough free reserved space"));
return GST_FLOW_ERROR;
}
serialize_error:
{
GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
("Failed to serialize mdat"));
g_free (node_header);
return GST_FLOW_ERROR;
}
}
static void
gst_qt_mux_configure_moov (GstQTMux * qtmux)
{
gboolean fragmented = FALSE;
guint32 timescale;
GST_OBJECT_LOCK (qtmux);
timescale = qtmux->timescale;
if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
fragmented = TRUE;
GST_OBJECT_UNLOCK (qtmux);
/* inform lower layers of our property wishes, and determine duration.
* Let moov take care of this using its list of traks;
* so that released pads are also included */
GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
timescale);
atom_moov_update_timescale (qtmux->moov, timescale);
atom_moov_set_fragmented (qtmux->moov, fragmented);
atom_moov_update_duration (qtmux->moov);
}
static GstFlowReturn
gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
{
guint64 offset = 0, size = 0;
guint8 *data;
GstBuffer *buf;
GstFlowReturn ret = GST_FLOW_OK;
GSList *walk;
guint64 current_time = atoms_get_current_qt_time ();
/* update modification times */
qtmux->moov->mvhd.time_info.modification_time = current_time;
for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qtpad = (GstQTPad *) cdata;
qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
qtpad->trak->tkhd.modification_time = current_time;
}
/* serialize moov */
offset = size = 0;
data = NULL;
GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
goto serialize_error;
qtmux->last_moov_size = offset;
/* Check we have enough reserved space for this and a Free atom */
if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
goto too_small_reserved;
buf = _gst_buffer_new_take_data (data, offset);
GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
/* If at EOS, this is the final moov, put in the streamheader
* (apparently used by a flumotion util) */
if (qtmux->state == GST_QT_MUX_STATE_EOS)
gst_qt_mux_set_header_on_caps (qtmux, buf);
if (fsync_after)
GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
/* Write out a free atom if needed */
if (ret == GST_FLOW_OK && offset < padded_moov_size) {
GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
(guint32) (padded_moov_size - offset));
ret =
gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
fsync_after);
}
return ret;
too_small_reserved:
{
GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
("Not enough free reserved header space"),
("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
offset, padded_moov_size));
return GST_FLOW_ERROR;
}
serialize_error:
{
g_free (data);
return GST_FLOW_ERROR;
}
}
/* either calculates size of extra atoms or pushes them */
static GstFlowReturn
gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
gboolean mind_fast)
{
GSList *walk;
guint64 loffset = 0, size = 0;
guint8 *data;
GstFlowReturn ret = GST_FLOW_OK;
for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
AtomInfo *ainfo = (AtomInfo *) walk->data;
loffset = size = 0;
data = NULL;
if (!ainfo->copy_data_func (ainfo->atom,
send ? &data : NULL, &size, &loffset))
goto serialize_error;
if (send) {
GstBuffer *buf;
GST_DEBUG_OBJECT (qtmux,
"Pushing extra top-level atom %" GST_FOURCC_FORMAT,
GST_FOURCC_ARGS (ainfo->atom->type));
buf = _gst_buffer_new_take_data (data, loffset);
ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
if (ret != GST_FLOW_OK)
break;
} else {
if (offset)
*offset += loffset;
}
}
return ret;
serialize_error:
{
g_free (data);
return GST_FLOW_ERROR;
}
}
static gboolean
gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
{
gboolean seekable = FALSE;
GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
if (gst_pad_peer_query (qtmux->srcpad, query)) {
gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
} else {
/* have to assume seeking is not supported if query not handled downstream */
GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
seekable = FALSE;
}
gst_query_unref (query);
return seekable;
}
static void
gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
{
GSList *walk;
gboolean fail = FALSE;
AtomFTYP *ftyp = NULL;
GstBuffer *prefix = NULL;
GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
qtmux->moov_recov_file_path);
qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
if (qtmux->moov_recov_file == NULL) {
GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
qtmux->moov_recov_file_path);
return;
}
gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
goto fail;
}
atom_ftyp_free (ftyp);
if (prefix)
gst_buffer_unref (prefix);
for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qpad = (GstQTPad *) cdata;
/* write info for each stream */
fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
if (fail) {
GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
"file");
break;
}
}
return;
fail:
/* cleanup */
fclose (qtmux->moov_recov_file);
qtmux->moov_recov_file = NULL;
}
static guint64
prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
{
switch (qpad->fourcc) {
case FOURCC_apch:
case FOURCC_apcn:
case FOURCC_apcs:
case FOURCC_apco:
case FOURCC_ap4h:
case FOURCC_ap4x:
return qpad->sample_offset;
case FOURCC_sowt:
case FOURCC_twos:
return gst_util_uint64_scale_ceil (qpad->sample_offset,
qpad->expected_sample_duration_n,
qpad->expected_sample_duration_d *
atom_trak_get_timescale (qpad->trak));
default:
return -1;
}
}
static guint
prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
{
switch (qpad->fourcc) {
case FOURCC_apch:
if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
return 300000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
return 350000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
return 525000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
return 1050000;
} else {
return 4150000;
}
break;
case FOURCC_apcn:
if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
return 200000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
return 250000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
return 350000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
return 700000;
} else {
return 2800000;
}
break;
case FOURCC_apcs:
if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
return 150000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
return 200000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
return 250000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
return 500000;
} else {
return 2800000;
}
break;
case FOURCC_apco:
if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
return 80000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
return 100000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
return 150000;
} else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
return 250000;
} else {
return 900000;
}
break;
case FOURCC_sowt:
case FOURCC_twos:{
guint64 block_idx;
guint64 next_sample_offset;
block_idx = prefill_get_block_index (qtmux, qpad);
next_sample_offset =
gst_util_uint64_scale (block_idx + 1,
qpad->expected_sample_duration_d *
atom_trak_get_timescale (qpad->trak),
qpad->expected_sample_duration_n);
return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
}
case FOURCC_ap4h:
case FOURCC_ap4x:
default:
GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
return -1;
}
return -1;
}
static GstClockTime
prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
{
switch (qpad->fourcc) {
case FOURCC_apch:
case FOURCC_apcn:
case FOURCC_apcs:
case FOURCC_apco:
case FOURCC_ap4h:
case FOURCC_ap4x:
return gst_util_uint64_scale (qpad->sample_offset + 1,
qpad->expected_sample_duration_d * GST_SECOND,
qpad->expected_sample_duration_n);
case FOURCC_sowt:
case FOURCC_twos:{
guint64 block_idx;
guint64 next_sample_offset;
block_idx = prefill_get_block_index (qtmux, qpad);
next_sample_offset =
gst_util_uint64_scale (block_idx + 1,
qpad->expected_sample_duration_d *
atom_trak_get_timescale (qpad->trak),
qpad->expected_sample_duration_n);
return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
atom_trak_get_timescale (qpad->trak));
}
default:
GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
return -1;
}
return -1;
}
static GstBuffer *
prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
GstQTMux * qtmux)
{
guint64 block_idx;
guint64 nsamples;
GstClockTime input_timestamp;
guint64 input_timestamp_distance;
if (buf)
gst_adapter_push (qtpad->raw_audio_adapter, buf);
block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
qtpad->expected_sample_duration_n,
qtpad->expected_sample_duration_d *
atom_trak_get_timescale (qtpad->trak));
nsamples =
gst_util_uint64_scale (block_idx + 1,
qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
GST_COLLECT_PADS_STATE_EOS)
&& gst_adapter_available (qtpad->raw_audio_adapter) <
nsamples * qtpad->sample_size)
|| gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
return NULL;
}
input_timestamp =
gst_adapter_prev_pts (qtpad->raw_audio_adapter,
&input_timestamp_distance);
if (input_timestamp != GST_CLOCK_TIME_NONE)
input_timestamp +=
gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
buf =
gst_adapter_take_buffer (qtpad->raw_audio_adapter,
!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
GST_COLLECT_PADS_STATE_EOS) ? nsamples *
qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
GST_BUFFER_PTS (buf) = input_timestamp;
GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
qtpad->raw_audio_adapter_offset += nsamples;
/* Check if we have yet another block of raw audio in the adapter */
nsamples =
gst_util_uint64_scale (block_idx + 2,
qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
if (gst_adapter_available (qtpad->raw_audio_adapter) >=
nsamples * qtpad->sample_size) {
input_timestamp =
gst_adapter_prev_pts (qtpad->raw_audio_adapter,
&input_timestamp_distance);
if (input_timestamp != GST_CLOCK_TIME_NONE)
input_timestamp +=
gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
qtpad->raw_audio_adapter_pts = input_timestamp;
} else {
qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
}
return buf;
}
static gboolean
prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
{
switch (qpad->fourcc) {
case FOURCC_apch:
case FOURCC_apcn:
case FOURCC_apcs:
case FOURCC_apco:
case FOURCC_ap4h:
case FOURCC_ap4x:{
guint sample_size = prefill_get_sample_size (qtmux, qpad);
atom_trak_set_constant_size_samples (qpad->trak, sample_size);
return TRUE;
}
case FOURCC_sowt:
case FOURCC_twos:{
GSList *walk;
/* Find the (first) video track and assume that we have to output
* in that size */
for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *tmp_qpad = (GstQTPad *) cdata;
if (tmp_qpad->trak->is_video) {
qpad->expected_sample_duration_n =
tmp_qpad->expected_sample_duration_n;
qpad->expected_sample_duration_d =
tmp_qpad->expected_sample_duration_d;
break;
}
}
if (walk == NULL) {
GST_INFO_OBJECT (qpad->collect.pad,
"Found no video framerate, using 40ms audio buffers");
qpad->expected_sample_duration_n = 25;
qpad->expected_sample_duration_d = 1;
}
/* Set a prepare_buf_func that ensures this */
qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
qpad->raw_audio_adapter = gst_adapter_new ();
qpad->raw_audio_adapter_offset = 0;
qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
return TRUE;
}
default:
return TRUE;
}
}
/* Only called at startup when doing the "fake" iteration of all tracks in order
* to prefill the sample tables in the header. */
static GstQTPad *
find_best_pad_prefill_start (GstQTMux * qtmux)
{
GSList *walk;
GstQTPad *best_pad = NULL;
/* If interleave limits have been specified and the current pad is within
* those interleave limits, pick that one, otherwise let's try to figure out
* the next best one. */
if (qtmux->current_pad &&
(qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
(qtmux->interleave_bytes == 0
|| qtmux->current_chunk_size <= qtmux->interleave_bytes)
&& (qtmux->interleave_time == 0
|| qtmux->current_chunk_duration <= qtmux->interleave_time)
&& qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
&& qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
best_pad = qtmux->current_pad;
}
} else if (qtmux->collect->data->next) {
/* Attempt to try another pad if we have one. Otherwise use the only pad
* present */
best_pad = qtmux->current_pad = NULL;
}
/* The next best pad is the one which has the lowest timestamp and hasn't
* exceeded the reserved max duration */
if (!best_pad) {
GstClockTime best_time = GST_CLOCK_TIME_NONE;
for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qtpad = (GstQTPad *) cdata;
GstClockTime timestamp;
if (qtpad->total_duration >= qtmux->reserved_max_duration)
continue;
timestamp = qtpad->total_duration;
if (best_pad == NULL ||
!GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
best_pad = qtpad;
best_time = timestamp;
}
}
}
return best_pad;
}
/* Called when starting the file in prefill_mode to figure out all the entries
* of the header based on the input stream and reserved maximum duration.
*
* The _actual_ header (i.e. with the proper duration and trimmed sample tables)
* will be updated and written on EOS. */
static gboolean
gst_qt_mux_prefill_samples (GstQTMux * qtmux)
{
GstQTPad *qpad;
GSList *walk;
GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
/* Update expected sample sizes/durations as needed, this is for raw
* audio where samples are actual audio samples. */
for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qpad = (GstQTPad *) cdata;
if (!prefill_update_sample_size (qtmux, qpad))
return FALSE;
}
if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
/* For the first sample check/update timecode as needed. We do that before
* all actual samples as the code in gst_qt_mux_add_buffer() does it with
* initial buffer directly, not with last_buf */
for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
GstCollectData *cdata = (GstCollectData *) walk->data;
GstQTPad *qpad = (GstQTPad *) cdata;
GstBuffer *buffer =
gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
GstVideoTimeCodeMeta *tc_meta;
if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))) {
GstVideoTimeCode *tc = &tc_meta->tc;
qpad->tc_trak = atom_trak_new (qtmux->context);
atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
qpad->trak->mdia.mdhd.time_info.timescale, tc);
atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
qtmux->mdat_size, FALSE, 0);
qpad->tc_pos = qtmux->mdat_size;
qpad->first_tc = gst_video_time_code_copy (tc);
qpad->first_pts = GST_BUFFER_PTS (buffer);
qtmux->current_chunk_offset = -1;
qtmux->current_chunk_size = 0;
qtmux->current_chunk_duration = 0;
qtmux->mdat_size += 4;
}
if (buffer)
gst_buffer_unref (buffer);
}
}
while ((qpad = find_best_pad_prefill_start (qtmux))) {
GstClockTime timestamp, next_timestamp, duration;
guint nsamples, sample_size;
guint64 chunk_offset;
gint64 scaled_duration;
gint64 pts_offset = 0;
gboolean sync = FALSE;
TrakBufferEntryInfo sample_entry;
sample_size = prefill_get_sample_size (qtmux, qpad);
if (sample_size == -1) {
return FALSE;
}
if (!qpad->samples)
qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
timestamp = qpad->total_duration;
next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
duration = next_timestamp - timestamp;
if (qpad->first_ts == GST_CLOCK_TIME_NONE)
qpad->first_ts = timestamp;
if (qpad->first_dts == GST_CLOCK_TIME_NONE)
qpad->first_dts = timestamp;
if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
qtmux->current_pad = qpad;
if (qtmux->current_chunk_offset == -1)
qtmux->current_chunk_offset = qtmux->mdat_size;
else
qtmux->current_chunk_offset += qtmux->current_chunk_size;
qtmux->current_chunk_size = 0;
qtmux->current_chunk_duration = 0;
}
if (qpad->sample_size)
nsamples = sample_size / qpad->sample_size;
else
nsamples = 1;
qpad->last_dts = timestamp;
scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
atom_trak_get_timescale (qpad->trak),
GST_SECOND) - gst_util_uint64_scale_round (timestamp,
atom_trak_get_timescale (qpad->trak), GST_SECOND);
qtmux->current_chunk_size += sample_size;
qtmux->current_chunk_duration += duration;
qpad->total_bytes += sample_size;
chunk_offset = qtmux->current_chunk_offset;
/* I-frame only, no frame reordering */
sync = FALSE;
pts_offset = 0;
if (qtmux->current_chunk_duration > qtmux->longest_chunk
|| !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
qtmux->longest_chunk = qtmux->current_chunk_duration;
}
sample_entry.track_id = qpad->trak->tkhd.track_ID;
sample_entry.nsamples = nsamples;
sample_entry.delta = scaled_duration / nsamples;
sample_entry.size = sample_size / nsamples;
sample_entry.chunk_offset = chunk_offset;
sample_entry.pts_offset = pts_offset;
sample_entry.sync = sync;
sample_entry.do_pts = TRUE;
g_array_append_val (qpad->samples, sample_entry);
atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
sample_size / nsamples, chunk_offset, sync, pts_offset);
qpad->total_duration = next_timestamp;
qtmux->mdat_size += sample_size;
qpad->sample_offset += nsamples;
}
return TRUE;
}
static GstFlowReturn
gst_qt_mux_start_file (GstQTMux * qtmux)
{
GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
GstFlowReturn ret = GST_FLOW_OK;
GstCaps *caps;
GstSegment segment;
gchar s_id[32];