gstqtmux.c 165 KB
Newer Older
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
7
 * Contact: Stefan Kost <stefan.kost@nokia.com>

8
9
10
11
12
13
14
15
16
17
18
19
 * 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
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
20
21
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
22
 */
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
 * 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.
 */
46
47
48


/**
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
49
 * SECTION:element-qtmux
50
51
 * @short_description: Muxer for quicktime(.mov) files
 *
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 * 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).
 *
68
69
70
 * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale) allow
 * adjusting some technical parameters, which might be useful in (rare) cases to
 * resolve compatibility issues in some situations.
71
72
 *
 * Some other properties influence the result more fundamentally.
73
74
75
76
77
78
79
 * 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.
80
 * If such fragmented layout is intended for streaming purposes, then
81
82
 * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
 * file).
83
 *
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
 * 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.
 *
99
100
 * <refsect2>
 * <title>Example pipelines</title>
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
101
 * |[
102
 * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
103
 * ]|
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
 * 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>
119
#include <gst/base/gstcollectpads.h>
Thiago Santos's avatar
Thiago Santos committed
120
121
#include <gst/base/gstbytereader.h>
#include <gst/base/gstbitreader.h>
122
#include <gst/audio/audio.h>
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
123
#include <gst/video/video.h>
124
#include <gst/tag/tag.h>
125
#include <gst/pbutils/pbutils.h>
126

Wim Taymans's avatar
Wim Taymans committed
127
#include <sys/types.h>
LRN's avatar
LRN committed
128
129
130
131
132
133
134
135
#ifdef G_OS_WIN32
#include <io.h>                 /* lseek, open, close, read */
#undef lseek
#define lseek _lseeki64
#undef off_t
#define off_t guint64
#endif

136
137
138
139
#ifdef _MSC_VER
#define ftruncate g_win32_ftruncate
#endif

Wim Taymans's avatar
Wim Taymans committed
140
141
142
143
#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif

144
145
146
147
148
#include "gstqtmux.h"

GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
#define GST_CAT_DEFAULT gst_qt_mux_debug

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/* 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.
 *
168
 * Currently mp4mux can work in 4 different modes / generate 4 types
169
170
171
172
173
174
175
176
177
178
179
180
181
 * 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
182
 *   but no sample table, followed by N fragments, each containing
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
 *   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.
 *
199
200
201
202
203
204
205
206
207
208
209
210
211
 * - 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.
212
213
 */

214
#ifndef GST_REMOVE_DEPRECATED
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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 ())
244
#endif
245

246
247
248
249
250
251
252
253
254
255
256
/* QTMux signals and args */
enum
{
  /* FILL ME */
  LAST_SIGNAL
};

enum
{
  PROP_0,
  PROP_MOVIE_TIMESCALE,
257
  PROP_TRAK_TIMESCALE,
258
  PROP_FAST_START,
259
  PROP_FAST_START_TEMP_FILE,
260
  PROP_MOOV_RECOV_FILE,
261
  PROP_FRAGMENT_DURATION,
262
  PROP_STREAMABLE,
263
264
265
266
  PROP_RESERVED_MAX_DURATION,
  PROP_RESERVED_DURATION_REMAINING,
  PROP_RESERVED_MOOV_UPDATE_PERIOD,
  PROP_RESERVED_BYTES_PER_SEC,
267
#ifndef GST_REMOVE_DEPRECATED
268
  PROP_DTS_METHOD,
269
#endif
270
  PROP_DO_CTTS,
271
272
  PROP_INTERLEAVE_BYTES,
  PROP_INTERLEAVE_TIME,
273
274
};

275
276
277
/* some spare for header size as well */
#define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)

278
#define DEFAULT_MOVIE_TIMESCALE         0
279
#define DEFAULT_TRAK_TIMESCALE          0
280
#define DEFAULT_DO_CTTS                 TRUE
281
282
#define DEFAULT_FAST_START              FALSE
#define DEFAULT_FAST_START_TEMP_FILE    NULL
283
#define DEFAULT_MOOV_RECOV_FILE         NULL
284
#define DEFAULT_FRAGMENT_DURATION       0
285
#define DEFAULT_STREAMABLE              TRUE
286
#ifndef GST_REMOVE_DEPRECATED
287
#define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
288
#endif
289
290
291
#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
292
#define DEFAULT_INTERLEAVE_BYTES 0
293
#define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
294

295
296
297
298
299
300
301
302
303
304
305
306
307
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,
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
308
    GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
309
310
311
static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);

/* event */
312
313
static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
    GstCollectData * data, GstEvent * event, gpointer user_data);
314

315
316
static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
    gpointer user_data);
317
318
319
static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
    GstBuffer * buf);

320
321
322
static GstFlowReturn
gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);

323
324
325
326
327
328
329
330
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;
331
332
  GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl;
  GstPadTemplate *srctempl;
333
  gchar *longname, *description;
334
335
336
337
338
339
340

  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 */
341
  longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
342
343
  description = g_strdup_printf ("Multiplex audio and video into a %s file",
      params->prop->long_name);
344
  gst_element_class_set_static_metadata (element_class, longname,
345
346
347
348
      "Codec/Muxer", description,
      "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
  g_free (longname);
  g_free (description);
349
350
351
352
353
354
355

  /* 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) {
356
    audiosinktempl = gst_pad_template_new ("audio_%u",
357
358
359
360
361
        GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps);
    gst_element_class_add_pad_template (element_class, audiosinktempl);
  }

  if (params->video_sink_caps) {
362
    videosinktempl = gst_pad_template_new ("video_%u",
363
364
365
366
        GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps);
    gst_element_class_add_pad_template (element_class, videosinktempl);
  }

367
368
369
370
371
372
  if (params->subtitle_sink_caps) {
    subtitlesinktempl = gst_pad_template_new ("subtitle_%u",
        GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps);
    gst_element_class_add_pad_template (element_class, subtitlesinktempl);
  }

373
374
375
376
377
378
379
380
  klass->format = params->prop->format;
}

static void
gst_qt_mux_class_init (GstQTMuxClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
381
  GParamFlags streamable_flags;
382
  const gchar *streamable_desc;
383
  gboolean streamable;
384
385
#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."
386
387
388
389
390
391
392
393
394
395

  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;

396
  streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
397
398
  if (klass->format == GST_QT_MUX_FORMAT_ISML) {
    streamable_desc = STREAMABLE_DESC;
399
    streamable = DEFAULT_STREAMABLE;
400
401
402
  } else {
    streamable_desc =
        STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
403
    streamable_flags |= G_PARAM_DEPRECATED;
404
    streamable = FALSE;
405
406
  }

407
408
  g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
      g_param_spec_uint ("movie-timescale", "Movie timescale",
409
410
          "Timescale to use in the movie (units per second, 0 == default)",
          0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
411
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
412
413
414
415
416
  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));
417
418
419
  g_object_class_install_property (gobject_class, PROP_DO_CTTS,
      g_param_spec_boolean ("presentation-time",
          "Include presentation-time info",
420
          "Calculate and include presentation/composition time "
421
          "(in addition to decoding time)", DEFAULT_DO_CTTS,
422
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
423
#ifndef GST_REMOVE_DEPRECATED
424
425
  g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
      g_param_spec_enum ("dts-method", "dts-method",
426
          "Method to determine DTS time (DEPRECATED)",
427
          GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
428
429
430
          G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
          G_PARAM_STATIC_STRINGS));
#endif
431
432
  g_object_class_install_property (gobject_class, PROP_FAST_START,
      g_param_spec_boolean ("faststart", "Format file to faststart",
433
          "If the file should be formatted for faststart (headers first)",
434
          DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
435
436
  g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
      g_param_spec_string ("faststart-file", "File to use for storing buffers",
437
438
439
          "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,
440
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
441
  g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
442
443
444
      g_param_spec_string ("moov-recovery-file",
          "File to store data for posterior moov atom recovery",
          "File to be used to store "
445
446
          "data for moov atom making movie file recovery possible in case "
          "of a crash during muxing. Null for disabled. (Experimental)",
447
448
          DEFAULT_MOOV_RECOV_FILE,
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
449
450
451
  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)",
452
453
          0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
          2000 : DEFAULT_FRAGMENT_DURATION,
454
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
455
  g_object_class_install_property (gobject_class, PROP_STREAMABLE,
456
      g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
457
          streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
  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));
486
487
488
489
490
491
492
493
494
495
  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));
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

  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;
511
  qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
Thiago Santos's avatar
Thiago Santos committed
512
  qtpad->first_ts = GST_CLOCK_TIME_NONE;
513
  qtpad->first_dts = GST_CLOCK_TIME_NONE;
Thiago Santos's avatar
Thiago Santos committed
514
  qtpad->prepare_buf_func = NULL;
515
  qtpad->create_empty_buffer = NULL;
516
517
  qtpad->avg_bitrate = 0;
  qtpad->max_bitrate = 0;
518
519
  qtpad->total_duration = 0;
  qtpad->total_bytes = 0;
520
  qtpad->sparse = FALSE;
521
  qtpad->tc_trak = NULL;
522
523
524

  qtpad->buf_head = 0;
  qtpad->buf_tail = 0;
525

526
  gst_buffer_replace (&qtpad->last_buf, NULL);
527

528
529
530
531
532
  if (qtpad->tags) {
    gst_tag_list_unref (qtpad->tags);
    qtpad->tags = NULL;
  }

533
534
  /* reference owned elsewhere */
  qtpad->trak = NULL;
535
536
537
538
539
540

  if (qtpad->traf) {
    atom_traf_free (qtpad->traf);
    qtpad->traf = NULL;
  }
  atom_array_clear (&qtpad->fragment_buffers);
541
542
543

  /* reference owned elsewhere */
  qtpad->tfra = NULL;
544
545
546
547
548
549
550
551
552
553
554
555
556
}

/*
 * 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;
557
  qtmux->moov_pos = 0;
558
  qtmux->mdat_pos = 0;
Thiago Santos's avatar
Thiago Santos committed
559
  qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
560
561
  qtmux->video_pads = 0;
  qtmux->audio_pads = 0;
562
  qtmux->fragment_sequence = 0;
563
564
565
566
567
568
569
570
571

  if (qtmux->ftyp) {
    atom_ftyp_free (qtmux->ftyp);
    qtmux->ftyp = NULL;
  }
  if (qtmux->moov) {
    atom_moov_free (qtmux->moov);
    qtmux->moov = NULL;
  }
572
573
574
575
  if (qtmux->mfra) {
    atom_mfra_free (qtmux->mfra);
    qtmux->mfra = NULL;
  }
576
577
  if (qtmux->fast_start_file) {
    fclose (qtmux->fast_start_file);
578
    g_remove (qtmux->fast_start_file_path);
579
580
    qtmux->fast_start_file = NULL;
  }
581
582
583
584
  if (qtmux->moov_recov_file) {
    fclose (qtmux->moov_recov_file);
    qtmux->moov_recov_file = NULL;
  }
585
586
587
  for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
    AtomInfo *ainfo = (AtomInfo *) walk->data;
    ainfo->free_func (ainfo->atom);
588
    g_free (ainfo);
589
590
591
  }
  g_slist_free (qtmux->extra_atoms);
  qtmux->extra_atoms = NULL;
592
593

  GST_OBJECT_LOCK (qtmux);
594
  gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
595
  GST_OBJECT_UNLOCK (qtmux);
596
597

  /* reset pad data */
598
  for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
599
600
601
602
603
604
605
606
607
608
    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);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
609
    /* ensure all is as nice and fresh as request_new_pad would provide it */
610
    for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
611
612
      GstQTPad *qtpad = (GstQTPad *) walk->data;

613
614
      qtpad->trak = atom_trak_new (qtmux->context);
      atom_moov_add_trak (qtmux->moov, qtpad->trak);
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
615
    }
616
  }
617

618
619
620
621
622
  qtmux->current_pad = NULL;
  qtmux->current_chunk_size = 0;
  qtmux->current_chunk_duration = 0;
  qtmux->current_chunk_offset = -1;

623
624
625
626
  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;
627
628
  qtmux->first_pts = GST_CLOCK_TIME_NONE;
  qtmux->tc_pos = -1;
629
630
631
632
633
634
635
636
637
638
639
640
641
}

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);

642
  qtmux->sinkpads = NULL;
643
644
  qtmux->collect = gst_collect_pads_new ();
  gst_collect_pads_set_event_function (qtmux->collect,
645
      GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
646
647
  gst_collect_pads_set_clip_function (qtmux->collect,
      GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
648
649
  gst_collect_pads_set_function (qtmux->collect,
      GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
650
651
652

  /* properties set to default upon construction */

653
654
655
656
  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;
657
658
  qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
  qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
659

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
  /* 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);

Thiago Santos's avatar
Thiago Santos committed
676
  g_free (qtmux->fast_start_file_path);
677
  g_free (qtmux->moov_recov_file_path);
678
679
680
681

  atoms_context_free (qtmux->context);
  gst_object_unref (qtmux->collect);

682
683
  g_slist_free (qtmux->sinkpads);

684
685
686
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

Thiago Santos's avatar
Thiago Santos committed
687
688
689
690
691
static GstBuffer *
gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
    GstQTMux * qtmux)
{
  GstBuffer *newbuf;
Wim Taymans's avatar
Wim Taymans committed
692
  GstMapInfo map;
Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
693
  gsize size;
Thiago Santos's avatar
Thiago Santos committed
694
695
696
697
698
699

  GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");

  if (buf == NULL)
    return NULL;

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
700
701
702
  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);
Thiago Santos's avatar
Thiago Santos committed
703

Wim Taymans's avatar
Wim Taymans committed
704
705
706
  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);
Thiago Santos's avatar
Thiago Santos committed
707

Wim Taymans's avatar
Wim Taymans committed
708
  gst_buffer_unmap (buf, &map);
Thiago Santos's avatar
Thiago Santos committed
709
710
711
712
713
  gst_buffer_unref (buf);

  return newbuf;
}

714
715
716
717
718
719
720
721
static GstBuffer *
gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
    GstQTMux * qtmux)
{
  GstBuffer *newbuf;
  GstMapInfo frommap;
  GstMapInfo tomap;
  gsize size;
722
  const guint8 *dataend;
723
724
725
726
727
728

  GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);

  if (buf == NULL)
    return NULL;

729
730
  gst_buffer_map (buf, &frommap, GST_MAP_READ);

731
732
  dataend = memchr (frommap.data, 0, frommap.size);
  size = dataend ? dataend - frommap.data : frommap.size;
733
734
735
736
737
738
739
740
741
742
743
744
  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);

745
746
747
748
  /* 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);

749
750
751
752
753
  gst_buffer_unref (buf);

  return newbuf;
}

Thiago Santos's avatar
Thiago Santos committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
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;
}

830
831
832
833
834
835
836
837
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);

838
  return gst_buffer_new_wrapped (data, 2);
839
840
}

841
842
static void
gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
843
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
844
845
846
847
848
849
850
851
852
853
854
{
  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);
855
      atom_udta_add_str_tag (udta, fourcc, str);
856
857
858
859
860
861
862
863
864
865
866
867
      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);
868
      atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
869
870
871
872
      break;
    }
    case G_TYPE_UINT:
    {
873
      guint value = 0;
874
875
      if (tag2) {
        /* paired unsigned integers */
876
        guint count = 0;
877
        gboolean got_tag;
878

879
880
881
        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)
882
883
884
          break;
        GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
            GST_FOURCC_ARGS (fourcc), value, count);
885
        atom_udta_add_uint_tag (udta, fourcc, 0,
886
887
888
889
890
891
892
            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);
893
        atom_udta_add_uint_tag (udta, fourcc, 1, value);
894
      }
895
896
897
898
899
900
901
902
903
904
      break;
    }
    default:
      g_assert_not_reached ();
      break;
  }
}

static void
gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
905
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
906
907
908
909
910
911
912
{
  GDate *date = NULL;
  GDateYear year;
  GDateMonth month;
  GDateDay day;
  gchar *str;

913
  g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
914
915
916
917
918
919
920
921

  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);

Mark Nauwelaerts's avatar
Mark Nauwelaerts committed
922
923
  g_date_free (date);

924
925
926
927
928
929
930
931
932
  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);
933
  atom_udta_add_str_tag (udta, fourcc, str);
934
  g_free (str);
935
936
937
938
}

static void
gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
939
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
940
941
942
{
  GValue value = { 0, };
  GstBuffer *buf;
943
  GstSample *sample;
944
945
946
  GstCaps *caps;
  GstStructure *structure;
  gint flags = 0;
Wim Taymans's avatar
Wim Taymans committed
947
  GstMapInfo map;
948

949
  g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
950
951
952
953

  if (!gst_tag_list_copy_value (&value, list, tag))
    return;

954
955
956
957
958
959
  sample = gst_value_get_sample (&value);

  if (!sample)
    goto done;

  buf = gst_sample_get_buffer (sample);
960
961
962
  if (!buf)
    goto done;

963
  caps = gst_sample_get_caps (sample);
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
  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;
  }

Wim Taymans's avatar
Wim Taymans committed
982
  gst_buffer_map (buf, &map, GST_MAP_READ);
983
  GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
Wim Taymans's avatar
Wim Taymans committed
984
      " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
985
  atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
Wim Taymans's avatar
Wim Taymans committed
986
  gst_buffer_unmap (buf, &map);
987
988
989
990
991
992
done:
  g_value_unset (&value);
}

static void
gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
993
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
{
  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);
1011
    atom_udta_add_3gp_str_tag (udta, fourcc, str);
1012
1013
1014
  } else {
    GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
        GST_FOURCC_ARGS (fourcc), str, number);
1015
    atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1016
1017
1018
1019
1020
1021
1022
  }

  g_free (str);
}

static void
gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1023
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1024
1025
1026
1027
{
  GDate *date = NULL;
  GDateYear year;

1028
  g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1029
1030
1031
1032
1033

  if (!gst_tag_list_get_date (list, tag, &date) || !date)
    return;

  year = g_date_get_year (date);
Vineeth TM's avatar
Vineeth TM committed
1034
  g_date_free (date);
1035
1036
1037
1038
1039
1040

  if (year == G_DATE_BAD_YEAR) {
    GST_WARNING_OBJECT (qtmux, "invalid date in tag");
    return;
  }

Edward Hervey's avatar
Edward Hervey committed
1041
1042
  GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
      GST_FOURCC_ARGS (fourcc), year);
1043
  atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1044
1045
1046
1047
}

static void
gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1048
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
{
  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 */
1088
1089
1090
1091
#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);
1092
1093
1094
1095
  /* neither astronomical body nor notes */
  GST_WRITE_UINT16_BE (data + 13, 0);

  GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1096
  atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1097
1098
1099
1100
1101
  g_free (ddata);
}

static void
gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1102
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
{
  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);
1115
  g_free (keywords);
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146

  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);

1147
  atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1148
1149
1150
  g_free (ddata);
}

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
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,
1225
    AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
{
  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);

1260
  atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1261
1262
  g_free (data);
}
1263

1264
1265
1266
typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
    const GstTagList * list, AtomUDTA * udta, const char *tag,
    const char *tag2, guint32 fourcc);
1267
1268
1269
1270
1271
1272
1273
1274
1275

/*
 * Struct to record mappings from gstreamer tags to fourcc codes
 */
typedef struct _GstTagToFourcc
{
  guint32 fourcc;
  const gchar *gsttag;
  const gchar *gsttag2;
1276
  const GstQTMuxAddUdtaTagFunc func;
1277
1278
1279
} GstTagToFourcc;

/* tag list tags to fourcc matching */
1280
1281
static const GstTagToFourcc tag_matches_mp4[] = {
  {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
Thiago Santos's avatar
Thiago Santos committed
1282
  {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1283
  {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
Thiago Santos's avatar
Thiago Santos committed
1284
1285
1286
  {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},
1287
  {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1288
1289
  {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
  {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
Thiago Santos's avatar
Thiago Santos committed
1290
1291
1292
1293
1294
  {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},
1295
1296
  {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
  {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
Thiago Santos's avatar
Thiago Santos committed
1297
1298
1299
  {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},
1300
  {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
Thiago Santos's avatar
Thiago Santos committed
1301
  {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
  {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},
1312
  {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
  {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},
1327
1328
  {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
      gst_qt_mux_add_3gp_classification},
1329
1330
1331
1332
1333
1334
  {0, NULL,}
};

/* qtdemux produces these for atoms it cannot parse */
#define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"

Thiago Santos's avatar
Thiago Santos committed
1335
1336
1337
1338
static void
gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
{
  GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1339
  GstBuffer *xmp = NULL;
Thiago Santos's avatar
Thiago Santos committed
1340

1341
1342
1343
  /* 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.
1344
1345
1346
   * If you have further info about xmp on these formats, please share */
  if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
    return;
Thiago Santos's avatar
Thiago Santos committed
1347
1348
1349

  GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");

1350
  if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1351
1352
1353
    xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
        list, TRUE);
    if (xmp)
1354
      atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1355
  } else {
1356
    AtomInfo *ainfo;
1357
    /* for isom/mp4, it is a top level uuid atom */
1358
1359
1360
1361
1362
1363
1364
    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);
      }
1365
1366
    }
  }
1367
1368
  if (xmp