1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4  * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5  * Copyright (C) 2014 Jan Schmidt <jan@centricular.com>
6  * Contact: Stefan Kost <stefan.kost@nokia.com>
7 
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /*
24  * Unless otherwise indicated, Source Code is licensed under MIT license.
25  * See further explanation attached in License Statement (distributed in the file
26  * LICENSE).
27  *
28  * Permission is hereby granted, free of charge, to any person obtaining a copy of
29  * this software and associated documentation files (the "Software"), to deal in
30  * the Software without restriction, including without limitation the rights to
31  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
32  * of the Software, and to permit persons to whom the Software is furnished to do
33  * so, subject to the following conditions:
34  *
35  * The above copyright notice and this permission notice shall be included in all
36  * copies or substantial portions of the Software.
37  *
38  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44  * SOFTWARE.
45  */
46 
47 
48 /**
49  * SECTION:element-qtmux
50  * @short_description: Muxer for quicktime(.mov) files
51  *
52  * This element merges streams (audio and video) into QuickTime(.mov) files.
53  *
54  * The following background intends to explain why various similar muxers
55  * are present in this plugin.
56  *
57  * The <ulink url="http://www.apple.com/quicktime/resources/qtfileformat.pdf">
58  * QuickTime file format specification</ulink> served as basis for the MP4 file
59  * format specification (mp4mux), and as such the QuickTime file structure is
60  * nearly identical to the so-called ISO Base Media file format defined in
61  * ISO 14496-12 (except for some media specific parts).
62  * In turn, the latter ISO Base Media format was further specialized as a
63  * Motion JPEG-2000 file format in ISO 15444-3 (mj2mux)
64  * and in various 3GPP(2) specs (gppmux).
65  * The fragmented file features defined (only) in ISO Base Media are used by
66  * ISMV files making up (a.o.) Smooth Streaming (ismlmux).
67  *
68  * A few properties (#GstQTMux:movie-timescale, #GstQTMux:trak-timescale,
69  * #GstQTMuxPad:trak-timescale) allow adjusting some technical parameters,
70  * which might be useful in (rare) cases to resolve compatibility issues in
71  * some situations.
72  *
73  * Some other properties influence the result more fundamentally.
74  * A typical mov/mp4 file's metadata (aka moov) is located at the end of the
75  * file, somewhat contrary to this usually being called "the header".
76  * However, a #GstQTMux:faststart file will (with some effort) arrange this to
77  * be located near start of the file, which then allows it e.g. to be played
78  * while downloading. Alternatively, rather than having one chunk of metadata at
79  * start (or end), there can be some metadata at start and most of the other
80  * data can be spread out into fragments of #GstQTMux:fragment-duration.
81  * If such fragmented layout is intended for streaming purposes, then
82  * #GstQTMux:streamable allows foregoing to add index metadata (at the end of
83  * file).
84  *
85  * When the maximum duration to be recorded can be known in advance, #GstQTMux
86  * also supports a 'Robust Muxing' mode. In robust muxing mode,  space for the
87  * headers are reserved at the start of muxing, and rewritten at a configurable
88  * interval, so that the output file is always playable, even if the recording
89  * is interrupted uncleanly by a crash. Robust muxing mode requires a seekable
90  * output, such as filesink, because it needs to rewrite the start of the file.
91  *
92  * To enable robust muxing mode, set the #GstQTMux::reserved-moov-update-period
93  * and #GstQTMux::reserved-max-duration property. Also present is the
94  * #GstQTMux::reserved-bytes-per-sec property, which can be increased if
95  * for some reason the default is not large enough and the initial reserved
96  * space for headers is too small. Applications can monitor the
97  * #GstQTMux::reserved-duration-remaining property to see how close to full
98  * the reserved space is becoming.
99  *
100  * Applications that wish to be able to use/edit a file while it is being
101  * written to by live content, can use the "Robust Prefill Muxing" mode. That
102  * mode is a variant of the "Robust Muxing" mode in that it will pre-allocate a
103  * completely valid header from the start for all tracks (i.e. it appears as
104  * though the file is "reserved-max-duration" long with all samples
105  * present). This mode can be enabled by setting the
106  * #GstQTMux::reserved-moov-update-period and #GstQTMux::reserved-prefill
107  * properties. Note that this mode is only possible with input streams that have
108  * a fixed sample size (such as raw audio and Prores Video) and that don't
109  * have reordered samples.
110  *
111  * <refsect2>
112  * <title>Example pipelines</title>
113  * |[
114  * gst-launch-1.0 v4l2src num-buffers=500 ! video/x-raw,width=320,height=240 ! videoconvert ! qtmux ! filesink location=video.mov
115  * ]|
116  * Records a video stream captured from a v4l2 device and muxes it into a qt file.
117  * </refsect2>
118  */
119 
120 /*
121  * Based on avimux
122  */
123 
124 #ifdef HAVE_CONFIG_H
125 #include "config.h"
126 #endif
127 
128 #include <glib/gstdio.h>
129 
130 #include <gst/gst.h>
131 #include <gst/base/gstcollectpads.h>
132 #include <gst/base/gstbytereader.h>
133 #include <gst/base/gstbitreader.h>
134 #include <gst/audio/audio.h>
135 #include <gst/video/video.h>
136 #include <gst/tag/tag.h>
137 #include <gst/pbutils/pbutils.h>
138 
139 #include <sys/types.h>
140 #ifdef G_OS_WIN32
141 #include <io.h>                 /* lseek, open, close, read */
142 #undef lseek
143 #define lseek _lseeki64
144 #undef off_t
145 #define off_t guint64
146 #endif
147 
148 #ifdef _MSC_VER
149 #define ftruncate g_win32_ftruncate
150 #endif
151 
152 #ifdef HAVE_UNISTD_H
153 #  include <unistd.h>
154 #endif
155 
156 #include "gstqtmux.h"
157 
158 GST_DEBUG_CATEGORY_STATIC (gst_qt_mux_debug);
159 #define GST_CAT_DEFAULT gst_qt_mux_debug
160 
161 #ifndef ABSDIFF
162 #define ABSDIFF(a, b) ((a) > (b) ? (a) - (b) : (b) - (a))
163 #endif
164 
165 /* Hacker notes.
166  *
167  * The basic building blocks of MP4 files are:
168  *  - an 'ftyp' box at the very start
169  *  - an 'mdat' box which contains the raw audio/video/subtitle data;
170  *    this is just a bunch of bytes, completely unframed and possibly
171  *    unordered with no additional meta-information
172  *  - a 'moov' box that contains information about the different streams
173  *    and what they contain, as well as sample tables for each stream
174  *    that tell the demuxer where in the mdat box each buffer/sample is
175  *    and what its duration/timestamp etc. is, and whether it's a
176  *    keyframe etc.
177  * Additionally, fragmented MP4 works by writing chunks of data in
178  * pairs of 'moof' and 'mdat' boxes:
179  *  - 'moof' boxes, header preceding each mdat fragment describing the
180  *    contents, like a moov but only for that fragment.
181  *  - a 'mfra' box for Fragmented MP4, which is written at the end and
182  *    contains a summary of all fragments and seek tables.
183  *
184  * Currently mp4mux can work in 4 different modes / generate 4 types
185  * of output files/streams:
186  *
187  * - Normal mp4: mp4mux will write a little ftyp identifier at the
188  *   beginning, then start an mdat box into which it will write all the
189  *   sample data. At EOS it will then write the moov header with track
190  *   headers and sample tables at the end of the file, and rewrite the
191  *   start of the file to fix up the mdat box size at the beginning.
192  *   It has to wait for EOS to write the moov (which includes the
193  *   sample tables) because it doesn't know how much space those
194  *   tables will be. The output downstream must be seekable to rewrite
195  *   the mdat box at EOS.
196  *
197  * - Fragmented mp4: moov header with track headers at start
198  *   but no sample table, followed by N fragments, each containing
199  *   track headers with sample tables followed by some data. Downstream
200  *   does not need to be seekable if the 'streamable' flag is TRUE,
201  *   as the final mfra and total duration will be omitted.
202  *
203  * - Fast-start mp4: the goal here is to create a file where the moov
204  *   headers are at the beginning; what mp4mux will do is write all
205  *   sample data into a temp file and build moov header plus sample
206  *   tables in memory and then when EOS comes, it will push out the
207  *   moov header plus sample tables at the beginning, followed by the
208  *   mdat sample data at the end which is read in from the temp file
209  *   Files created in this mode are better for streaming over the
210  *   network, since the client doesn't have to seek to the end of the
211  *   file to get the headers, but it requires copying all sample data
212  *   out of the temp file at EOS, which can be expensive. Downstream does
213  *   not need to be seekable, because of the use of the temp file.
214  *
215  * - Robust Muxing mode: In this mode, qtmux uses the reserved-max-duration
216  *   and reserved-moov-update-period properties to reserve free space
217  *   at the start of the file and periodically write the MOOV atom out
218  *   to it. That means that killing the muxing at any point still
219  *   results in a playable file, at the cost of wasting some amount of
220  *   free space at the start of file. The approximate recording duration
221  *   has to be known in advance to estimate how much free space to reserve
222  *   for the moov, and the downstream must be seekable.
223  *   If the moov header grows larger than the reserved space, an error
224  *   is generated - so it's better to over-estimate the amount of space
225  *   to reserve. To ensure the file is playable at any point, the moov
226  *   is updated using a 'ping-pong' strategy, so the output is never in
227  *   an invalid state.
228  */
229 
230 #ifndef GST_REMOVE_DEPRECATED
231 enum
232 {
233   DTS_METHOD_DD,
234   DTS_METHOD_REORDER,
235   DTS_METHOD_ASC
236 };
237 
238 static GType
gst_qt_mux_dts_method_get_type(void)239 gst_qt_mux_dts_method_get_type (void)
240 {
241   static GType gst_qt_mux_dts_method = 0;
242 
243   if (!gst_qt_mux_dts_method) {
244     static const GEnumValue dts_methods[] = {
245       {DTS_METHOD_DD, "delta/duration", "dd"},
246       {DTS_METHOD_REORDER, "reorder", "reorder"},
247       {DTS_METHOD_ASC, "ascending", "asc"},
248       {0, NULL, NULL},
249     };
250 
251     gst_qt_mux_dts_method =
252         g_enum_register_static ("GstQTMuxDtsMethods", dts_methods);
253   }
254 
255   return gst_qt_mux_dts_method;
256 }
257 
258 #define GST_TYPE_QT_MUX_DTS_METHOD \
259   (gst_qt_mux_dts_method_get_type ())
260 #endif
261 
262 enum
263 {
264   PROP_PAD_0,
265   PROP_PAD_TRAK_TIMESCALE,
266 };
267 
268 #define DEFAULT_PAD_TRAK_TIMESCALE          0
269 
270 GType gst_qt_mux_pad_get_type (void);
271 
272 #define GST_TYPE_QT_MUX_PAD \
273   (gst_qt_mux_pad_get_type())
274 #define GST_QT_MUX_PAD(obj) \
275   (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_QT_MUX_PAD, GstQTMuxPad))
276 #define GST_QT_MUX_PAD_CLASS(klass) \
277   (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_QT_MUX_PAD, GstQTMuxPadClass))
278 #define GST_IS_QT_MUX_PAD(obj) \
279   (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_QT_MUX_PAD))
280 #define GST_IS_QT_MUX_PAD_CLASS(klass) \
281   (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_QT_MUX_PAD))
282 #define GST_QT_MUX_PAD_CAST(obj) \
283   ((GstQTMuxPad *)(obj))
284 
285 typedef struct _GstQTMuxPad GstQTMuxPad;
286 typedef struct _GstQTMuxPadClass GstQTMuxPadClass;
287 
288 struct _GstQTMuxPad
289 {
290   GstPad parent;
291 
292   guint32 trak_timescale;
293 };
294 
295 struct _GstQTMuxPadClass
296 {
297   GstPadClass parent;
298 };
299 
300 G_DEFINE_TYPE (GstQTMuxPad, gst_qt_mux_pad, GST_TYPE_PAD);
301 
302 static void
gst_qt_mux_pad_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)303 gst_qt_mux_pad_set_property (GObject * object,
304     guint prop_id, const GValue * value, GParamSpec * pspec)
305 {
306   GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
307 
308   GST_OBJECT_LOCK (pad);
309   switch (prop_id) {
310     case PROP_PAD_TRAK_TIMESCALE:
311       pad->trak_timescale = g_value_get_uint (value);
312       break;
313     default:
314       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
315       break;
316   }
317   GST_OBJECT_UNLOCK (pad);
318 }
319 
320 static void
gst_qt_mux_pad_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)321 gst_qt_mux_pad_get_property (GObject * object,
322     guint prop_id, GValue * value, GParamSpec * pspec)
323 {
324   GstQTMuxPad *pad = GST_QT_MUX_PAD_CAST (object);
325 
326   GST_OBJECT_LOCK (pad);
327   switch (prop_id) {
328     case PROP_PAD_TRAK_TIMESCALE:
329       g_value_set_uint (value, pad->trak_timescale);
330       break;
331     default:
332       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
333       break;
334   }
335   GST_OBJECT_UNLOCK (pad);
336 }
337 
338 static void
gst_qt_mux_pad_class_init(GstQTMuxPadClass * klass)339 gst_qt_mux_pad_class_init (GstQTMuxPadClass * klass)
340 {
341   GObjectClass *gobject_class = (GObjectClass *) klass;
342 
343   gobject_class->get_property = gst_qt_mux_pad_get_property;
344   gobject_class->set_property = gst_qt_mux_pad_set_property;
345 
346   g_object_class_install_property (gobject_class, PROP_PAD_TRAK_TIMESCALE,
347       g_param_spec_uint ("trak-timescale", "Track timescale",
348           "Timescale to use for this pad's trak (units per second, 0 is automatic)",
349           0, G_MAXUINT32, DEFAULT_PAD_TRAK_TIMESCALE,
350           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
351 }
352 
353 static void
gst_qt_mux_pad_init(GstQTMuxPad * pad)354 gst_qt_mux_pad_init (GstQTMuxPad * pad)
355 {
356   pad->trak_timescale = DEFAULT_PAD_TRAK_TIMESCALE;
357 }
358 
359 static guint32
gst_qt_mux_pad_get_timescale(GstQTMuxPad * pad)360 gst_qt_mux_pad_get_timescale (GstQTMuxPad * pad)
361 {
362   guint32 timescale;
363 
364   GST_OBJECT_LOCK (pad);
365   timescale = pad->trak_timescale;
366   GST_OBJECT_UNLOCK (pad);
367 
368   return timescale;
369 }
370 
371 /* QTMux signals and args */
372 enum
373 {
374   /* FILL ME */
375   LAST_SIGNAL
376 };
377 
378 enum
379 {
380   PROP_0,
381   PROP_MOVIE_TIMESCALE,
382   PROP_TRAK_TIMESCALE,
383   PROP_FAST_START,
384   PROP_FAST_START_TEMP_FILE,
385   PROP_MOOV_RECOV_FILE,
386   PROP_FRAGMENT_DURATION,
387   PROP_STREAMABLE,
388   PROP_RESERVED_MAX_DURATION,
389   PROP_RESERVED_DURATION_REMAINING,
390   PROP_RESERVED_MOOV_UPDATE_PERIOD,
391   PROP_RESERVED_BYTES_PER_SEC,
392   PROP_RESERVED_PREFILL,
393 #ifndef GST_REMOVE_DEPRECATED
394   PROP_DTS_METHOD,
395 #endif
396   PROP_DO_CTTS,
397   PROP_INTERLEAVE_BYTES,
398   PROP_INTERLEAVE_TIME,
399   PROP_MAX_RAW_AUDIO_DRIFT,
400   PROP_START_GAP_THRESHOLD,
401 };
402 
403 /* some spare for header size as well */
404 #define MDAT_LARGE_FILE_LIMIT           ((guint64) 1024 * 1024 * 1024 * 2)
405 
406 #define DEFAULT_MOVIE_TIMESCALE         0
407 #define DEFAULT_TRAK_TIMESCALE          0
408 #define DEFAULT_DO_CTTS                 TRUE
409 #define DEFAULT_FAST_START              FALSE
410 #define DEFAULT_FAST_START_TEMP_FILE    NULL
411 #define DEFAULT_MOOV_RECOV_FILE         NULL
412 #define DEFAULT_FRAGMENT_DURATION       0
413 #define DEFAULT_STREAMABLE              TRUE
414 #ifndef GST_REMOVE_DEPRECATED
415 #define DEFAULT_DTS_METHOD              DTS_METHOD_REORDER
416 #endif
417 #define DEFAULT_RESERVED_MAX_DURATION   GST_CLOCK_TIME_NONE
418 #define DEFAULT_RESERVED_MOOV_UPDATE_PERIOD   GST_CLOCK_TIME_NONE
419 #define DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK 550
420 #define DEFAULT_RESERVED_PREFILL FALSE
421 #define DEFAULT_INTERLEAVE_BYTES 0
422 #define DEFAULT_INTERLEAVE_TIME 250*GST_MSECOND
423 #define DEFAULT_MAX_RAW_AUDIO_DRIFT 40 * GST_MSECOND
424 #define DEFAULT_START_GAP_THRESHOLD 0
425 
426 static void gst_qt_mux_finalize (GObject * object);
427 
428 static GstStateChangeReturn gst_qt_mux_change_state (GstElement * element,
429     GstStateChange transition);
430 
431 /* property functions */
432 static void gst_qt_mux_set_property (GObject * object,
433     guint prop_id, const GValue * value, GParamSpec * pspec);
434 static void gst_qt_mux_get_property (GObject * object,
435     guint prop_id, GValue * value, GParamSpec * pspec);
436 
437 /* pad functions */
438 static GstPad *gst_qt_mux_request_new_pad (GstElement * element,
439     GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
440 static void gst_qt_mux_release_pad (GstElement * element, GstPad * pad);
441 
442 /* event */
443 static gboolean gst_qt_mux_sink_event (GstCollectPads * pads,
444     GstCollectData * data, GstEvent * event, gpointer user_data);
445 
446 static GstFlowReturn gst_qt_mux_collected (GstCollectPads * pads,
447     gpointer user_data);
448 static GstFlowReturn gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
449     GstBuffer * buf);
450 
451 static GstFlowReturn
452 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux);
453 
454 static void gst_qt_mux_update_global_statistics (GstQTMux * qtmux);
455 static void gst_qt_mux_update_edit_lists (GstQTMux * qtmux);
456 
457 static GstElementClass *parent_class = NULL;
458 
459 static void
gst_qt_mux_base_init(gpointer g_class)460 gst_qt_mux_base_init (gpointer g_class)
461 {
462   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
463   GstQTMuxClass *klass = (GstQTMuxClass *) g_class;
464   GstQTMuxClassParams *params;
465   GstPadTemplate *videosinktempl, *audiosinktempl, *subtitlesinktempl,
466       *captionsinktempl;
467   GstPadTemplate *srctempl;
468   gchar *longname, *description;
469 
470   params =
471       (GstQTMuxClassParams *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (g_class),
472       GST_QT_MUX_PARAMS_QDATA);
473   g_assert (params != NULL);
474 
475   /* construct the element details struct */
476   longname = g_strdup_printf ("%s Muxer", params->prop->long_name);
477   description = g_strdup_printf ("Multiplex audio and video into a %s file",
478       params->prop->long_name);
479   gst_element_class_set_static_metadata (element_class, longname,
480       "Codec/Muxer", description,
481       "Thiago Sousa Santos <thiagoss@embedded.ufcg.edu.br>");
482   g_free (longname);
483   g_free (description);
484 
485   /* pad templates */
486   srctempl = gst_pad_template_new ("src", GST_PAD_SRC,
487       GST_PAD_ALWAYS, params->src_caps);
488   gst_element_class_add_pad_template (element_class, srctempl);
489 
490   if (params->audio_sink_caps) {
491     audiosinktempl = gst_pad_template_new_with_gtype ("audio_%u",
492         GST_PAD_SINK, GST_PAD_REQUEST, params->audio_sink_caps,
493         GST_TYPE_QT_MUX_PAD);
494     gst_element_class_add_pad_template (element_class, audiosinktempl);
495   }
496 
497   if (params->video_sink_caps) {
498     videosinktempl = gst_pad_template_new_with_gtype ("video_%u",
499         GST_PAD_SINK, GST_PAD_REQUEST, params->video_sink_caps,
500         GST_TYPE_QT_MUX_PAD);
501     gst_element_class_add_pad_template (element_class, videosinktempl);
502   }
503 
504   if (params->subtitle_sink_caps) {
505     subtitlesinktempl = gst_pad_template_new_with_gtype ("subtitle_%u",
506         GST_PAD_SINK, GST_PAD_REQUEST, params->subtitle_sink_caps,
507         GST_TYPE_QT_MUX_PAD);
508     gst_element_class_add_pad_template (element_class, subtitlesinktempl);
509   }
510 
511   if (params->caption_sink_caps) {
512     captionsinktempl = gst_pad_template_new_with_gtype ("caption_%u",
513         GST_PAD_SINK, GST_PAD_REQUEST, params->caption_sink_caps,
514         GST_TYPE_QT_MUX_PAD);
515     gst_element_class_add_pad_template (element_class, captionsinktempl);
516   }
517 
518   klass->format = params->prop->format;
519 }
520 
521 static void
gst_qt_mux_class_init(GstQTMuxClass * klass)522 gst_qt_mux_class_init (GstQTMuxClass * klass)
523 {
524   GObjectClass *gobject_class;
525   GstElementClass *gstelement_class;
526   GParamFlags streamable_flags;
527   const gchar *streamable_desc;
528   gboolean streamable;
529 #define STREAMABLE_DESC "If set to true, the output should be as if it is to "\
530   "be streamed and hence no indexes written or duration written."
531 
532   gobject_class = (GObjectClass *) klass;
533   gstelement_class = (GstElementClass *) klass;
534 
535   parent_class = g_type_class_peek_parent (klass);
536 
537   gobject_class->finalize = gst_qt_mux_finalize;
538   gobject_class->get_property = gst_qt_mux_get_property;
539   gobject_class->set_property = gst_qt_mux_set_property;
540 
541   streamable_flags = G_PARAM_READWRITE | G_PARAM_CONSTRUCT;
542   if (klass->format == GST_QT_MUX_FORMAT_ISML) {
543     streamable_desc = STREAMABLE_DESC;
544     streamable = DEFAULT_STREAMABLE;
545   } else {
546     streamable_desc =
547         STREAMABLE_DESC " (DEPRECATED, only valid for fragmented MP4)";
548     streamable_flags |= G_PARAM_DEPRECATED;
549     streamable = FALSE;
550   }
551 
552   g_object_class_install_property (gobject_class, PROP_MOVIE_TIMESCALE,
553       g_param_spec_uint ("movie-timescale", "Movie timescale",
554           "Timescale to use in the movie (units per second, 0 == default)",
555           0, G_MAXUINT32, DEFAULT_MOVIE_TIMESCALE,
556           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
557   g_object_class_install_property (gobject_class, PROP_TRAK_TIMESCALE,
558       g_param_spec_uint ("trak-timescale", "Track timescale",
559           "Timescale to use for the tracks (units per second, 0 is automatic)",
560           0, G_MAXUINT32, DEFAULT_TRAK_TIMESCALE,
561           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
562   g_object_class_install_property (gobject_class, PROP_DO_CTTS,
563       g_param_spec_boolean ("presentation-time",
564           "Include presentation-time info",
565           "Calculate and include presentation/composition time "
566           "(in addition to decoding time)", DEFAULT_DO_CTTS,
567           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
568 #ifndef GST_REMOVE_DEPRECATED
569   g_object_class_install_property (gobject_class, PROP_DTS_METHOD,
570       g_param_spec_enum ("dts-method", "dts-method",
571           "Method to determine DTS time (DEPRECATED)",
572           GST_TYPE_QT_MUX_DTS_METHOD, DEFAULT_DTS_METHOD,
573           G_PARAM_DEPRECATED | G_PARAM_READWRITE | G_PARAM_CONSTRUCT |
574           G_PARAM_STATIC_STRINGS));
575 #endif
576   g_object_class_install_property (gobject_class, PROP_FAST_START,
577       g_param_spec_boolean ("faststart", "Format file to faststart",
578           "If the file should be formatted for faststart (headers first)",
579           DEFAULT_FAST_START, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
580   g_object_class_install_property (gobject_class, PROP_FAST_START_TEMP_FILE,
581       g_param_spec_string ("faststart-file", "File to use for storing buffers",
582           "File that will be used temporarily to store data from the stream "
583           "when creating a faststart file. If null a filepath will be "
584           "created automatically", DEFAULT_FAST_START_TEMP_FILE,
585           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
586   g_object_class_install_property (gobject_class, PROP_MOOV_RECOV_FILE,
587       g_param_spec_string ("moov-recovery-file",
588           "File to store data for posterior moov atom recovery",
589           "File to be used to store "
590           "data for moov atom making movie file recovery possible in case "
591           "of a crash during muxing. Null for disabled. (Experimental)",
592           DEFAULT_MOOV_RECOV_FILE,
593           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
594   g_object_class_install_property (gobject_class, PROP_FRAGMENT_DURATION,
595       g_param_spec_uint ("fragment-duration", "Fragment duration",
596           "Fragment durations in ms (produce a fragmented file if > 0)",
597           0, G_MAXUINT32, klass->format == GST_QT_MUX_FORMAT_ISML ?
598           2000 : DEFAULT_FRAGMENT_DURATION,
599           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
600   g_object_class_install_property (gobject_class, PROP_STREAMABLE,
601       g_param_spec_boolean ("streamable", "Streamable", streamable_desc,
602           streamable, streamable_flags | G_PARAM_STATIC_STRINGS));
603   g_object_class_install_property (gobject_class, PROP_RESERVED_MAX_DURATION,
604       g_param_spec_uint64 ("reserved-max-duration",
605           "Reserved maximum file duration (ns)",
606           "When set to a value > 0, reserves space for index tables at the "
607           "beginning of the file.",
608           0, G_MAXUINT64, DEFAULT_RESERVED_MAX_DURATION,
609           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
610   g_object_class_install_property (gobject_class,
611       PROP_RESERVED_DURATION_REMAINING,
612       g_param_spec_uint64 ("reserved-duration-remaining",
613           "Report the approximate amount of remaining recording space (ns)",
614           "Reports the approximate amount of remaining moov header space "
615           "reserved using reserved-max-duration", 0, G_MAXUINT64, 0,
616           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
617   g_object_class_install_property (gobject_class,
618       PROP_RESERVED_MOOV_UPDATE_PERIOD,
619       g_param_spec_uint64 ("reserved-moov-update-period",
620           "Interval at which to update index tables (ns)",
621           "When used with reserved-max-duration, periodically updates the "
622           "index tables with information muxed so far.", 0, G_MAXUINT64,
623           DEFAULT_RESERVED_MOOV_UPDATE_PERIOD,
624           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
625   g_object_class_install_property (gobject_class, PROP_RESERVED_BYTES_PER_SEC,
626       g_param_spec_uint ("reserved-bytes-per-sec",
627           "Reserved MOOV bytes per second, per track",
628           "Multiplier for converting reserved-max-duration into bytes of header to reserve, per second, per track",
629           0, 10000, DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK,
630           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
631   g_object_class_install_property (gobject_class, PROP_RESERVED_PREFILL,
632       g_param_spec_boolean ("reserved-prefill",
633           "Reserved Prefill Samples Table",
634           "Prefill samples table of reserved duration",
635           DEFAULT_RESERVED_PREFILL,
636           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
637   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_BYTES,
638       g_param_spec_uint64 ("interleave-bytes", "Interleave (bytes)",
639           "Interleave between streams in bytes",
640           0, G_MAXUINT64, DEFAULT_INTERLEAVE_BYTES,
641           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
642   g_object_class_install_property (gobject_class, PROP_INTERLEAVE_TIME,
643       g_param_spec_uint64 ("interleave-time", "Interleave (time)",
644           "Interleave between streams in nanoseconds",
645           0, G_MAXUINT64, DEFAULT_INTERLEAVE_TIME,
646           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
647   g_object_class_install_property (gobject_class, PROP_MAX_RAW_AUDIO_DRIFT,
648       g_param_spec_uint64 ("max-raw-audio-drift", "Max Raw Audio Drift",
649           "Maximum allowed drift of raw audio samples vs. timestamps in nanoseconds",
650           0, G_MAXUINT64, DEFAULT_MAX_RAW_AUDIO_DRIFT,
651           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
652   g_object_class_install_property (gobject_class, PROP_START_GAP_THRESHOLD,
653       g_param_spec_uint64 ("start-gap-threshold", "Start Gap Threshold",
654           "Threshold for creating an edit list for gaps at the start in nanoseconds",
655           0, G_MAXUINT64, DEFAULT_START_GAP_THRESHOLD,
656           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
657 
658   gstelement_class->request_new_pad =
659       GST_DEBUG_FUNCPTR (gst_qt_mux_request_new_pad);
660   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_qt_mux_change_state);
661   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_qt_mux_release_pad);
662 }
663 
664 static void
gst_qt_mux_pad_reset(GstQTPad * qtpad)665 gst_qt_mux_pad_reset (GstQTPad * qtpad)
666 {
667   qtpad->fourcc = 0;
668   qtpad->is_out_of_order = FALSE;
669   qtpad->sample_size = 0;
670   qtpad->sync = FALSE;
671   qtpad->last_dts = 0;
672   qtpad->sample_offset = 0;
673   qtpad->dts_adjustment = GST_CLOCK_TIME_NONE;
674   qtpad->first_ts = GST_CLOCK_TIME_NONE;
675   qtpad->first_dts = GST_CLOCK_TIME_NONE;
676   qtpad->prepare_buf_func = NULL;
677   qtpad->create_empty_buffer = NULL;
678   qtpad->avg_bitrate = 0;
679   qtpad->max_bitrate = 0;
680   qtpad->total_duration = 0;
681   qtpad->total_bytes = 0;
682   qtpad->sparse = FALSE;
683 
684   gst_buffer_replace (&qtpad->last_buf, NULL);
685 
686   if (qtpad->tags) {
687     gst_tag_list_unref (qtpad->tags);
688     qtpad->tags = NULL;
689   }
690 
691   /* reference owned elsewhere */
692   qtpad->trak = NULL;
693   qtpad->tc_trak = NULL;
694 
695   if (qtpad->traf) {
696     atom_traf_free (qtpad->traf);
697     qtpad->traf = NULL;
698   }
699   atom_array_clear (&qtpad->fragment_buffers);
700   if (qtpad->samples)
701     g_array_unref (qtpad->samples);
702   qtpad->samples = NULL;
703 
704   /* reference owned elsewhere */
705   qtpad->tfra = NULL;
706 
707   qtpad->first_pts = GST_CLOCK_TIME_NONE;
708   qtpad->tc_pos = -1;
709   if (qtpad->first_tc)
710     gst_video_time_code_free (qtpad->first_tc);
711   qtpad->first_tc = NULL;
712 
713   if (qtpad->raw_audio_adapter)
714     gst_object_unref (qtpad->raw_audio_adapter);
715   qtpad->raw_audio_adapter = NULL;
716 }
717 
718 /*
719  * Takes GstQTMux back to its initial state
720  */
721 static void
gst_qt_mux_reset(GstQTMux * qtmux,gboolean alloc)722 gst_qt_mux_reset (GstQTMux * qtmux, gboolean alloc)
723 {
724   GSList *walk;
725 
726   qtmux->state = GST_QT_MUX_STATE_NONE;
727   qtmux->header_size = 0;
728   qtmux->mdat_size = 0;
729   qtmux->moov_pos = 0;
730   qtmux->mdat_pos = 0;
731   qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
732   qtmux->fragment_sequence = 0;
733 
734   if (qtmux->ftyp) {
735     atom_ftyp_free (qtmux->ftyp);
736     qtmux->ftyp = NULL;
737   }
738   if (qtmux->moov) {
739     atom_moov_free (qtmux->moov);
740     qtmux->moov = NULL;
741   }
742   if (qtmux->mfra) {
743     atom_mfra_free (qtmux->mfra);
744     qtmux->mfra = NULL;
745   }
746   if (qtmux->fast_start_file) {
747     fclose (qtmux->fast_start_file);
748     g_remove (qtmux->fast_start_file_path);
749     qtmux->fast_start_file = NULL;
750   }
751   if (qtmux->moov_recov_file) {
752     fclose (qtmux->moov_recov_file);
753     qtmux->moov_recov_file = NULL;
754   }
755   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
756     AtomInfo *ainfo = (AtomInfo *) walk->data;
757     ainfo->free_func (ainfo->atom);
758     g_free (ainfo);
759   }
760   g_slist_free (qtmux->extra_atoms);
761   qtmux->extra_atoms = NULL;
762 
763   GST_OBJECT_LOCK (qtmux);
764   gst_tag_setter_reset_tags (GST_TAG_SETTER (qtmux));
765   GST_OBJECT_UNLOCK (qtmux);
766 
767   /* reset pad data */
768   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
769     GstQTPad *qtpad = (GstQTPad *) walk->data;
770     gst_qt_mux_pad_reset (qtpad);
771 
772     /* hm, moov_free above yanked the traks away from us,
773      * so do not free, but do clear */
774     qtpad->trak = NULL;
775   }
776 
777   if (alloc) {
778     qtmux->moov = atom_moov_new (qtmux->context);
779     /* ensure all is as nice and fresh as request_new_pad would provide it */
780     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
781       GstQTPad *qtpad = (GstQTPad *) walk->data;
782 
783       qtpad->trak = atom_trak_new (qtmux->context);
784       atom_moov_add_trak (qtmux->moov, qtpad->trak);
785     }
786   }
787 
788   qtmux->current_pad = NULL;
789   qtmux->current_chunk_size = 0;
790   qtmux->current_chunk_duration = 0;
791   qtmux->current_chunk_offset = -1;
792 
793   qtmux->reserved_moov_size = 0;
794   qtmux->last_moov_update = GST_CLOCK_TIME_NONE;
795   qtmux->muxed_since_last_update = 0;
796   qtmux->reserved_duration_remaining = GST_CLOCK_TIME_NONE;
797 }
798 
799 static void
gst_qt_mux_init(GstQTMux * qtmux,GstQTMuxClass * qtmux_klass)800 gst_qt_mux_init (GstQTMux * qtmux, GstQTMuxClass * qtmux_klass)
801 {
802   GstElementClass *klass = GST_ELEMENT_CLASS (qtmux_klass);
803   GstPadTemplate *templ;
804 
805   templ = gst_element_class_get_pad_template (klass, "src");
806   qtmux->srcpad = gst_pad_new_from_template (templ, "src");
807   gst_pad_use_fixed_caps (qtmux->srcpad);
808   gst_element_add_pad (GST_ELEMENT (qtmux), qtmux->srcpad);
809 
810   qtmux->sinkpads = NULL;
811   qtmux->collect = gst_collect_pads_new ();
812   gst_collect_pads_set_event_function (qtmux->collect,
813       GST_DEBUG_FUNCPTR (gst_qt_mux_sink_event), qtmux);
814   gst_collect_pads_set_clip_function (qtmux->collect,
815       GST_DEBUG_FUNCPTR (gst_collect_pads_clip_running_time), qtmux);
816   gst_collect_pads_set_function (qtmux->collect,
817       GST_DEBUG_FUNCPTR (gst_qt_mux_collected), qtmux);
818 
819   /* properties set to default upon construction */
820 
821   qtmux->reserved_max_duration = DEFAULT_RESERVED_MAX_DURATION;
822   qtmux->reserved_moov_update_period = DEFAULT_RESERVED_MOOV_UPDATE_PERIOD;
823   qtmux->reserved_bytes_per_sec_per_trak =
824       DEFAULT_RESERVED_BYTES_PER_SEC_PER_TRAK;
825   qtmux->interleave_bytes = DEFAULT_INTERLEAVE_BYTES;
826   qtmux->interleave_time = DEFAULT_INTERLEAVE_TIME;
827   qtmux->max_raw_audio_drift = DEFAULT_MAX_RAW_AUDIO_DRIFT;
828   qtmux->start_gap_threshold = DEFAULT_START_GAP_THRESHOLD;
829 
830   /* always need this */
831   qtmux->context =
832       atoms_context_new (gst_qt_mux_map_format_to_flavor (qtmux_klass->format));
833 
834   /* internals to initial state */
835   gst_qt_mux_reset (qtmux, TRUE);
836 }
837 
838 
839 static void
gst_qt_mux_finalize(GObject * object)840 gst_qt_mux_finalize (GObject * object)
841 {
842   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
843 
844   gst_qt_mux_reset (qtmux, FALSE);
845 
846   g_free (qtmux->fast_start_file_path);
847   g_free (qtmux->moov_recov_file_path);
848 
849   atoms_context_free (qtmux->context);
850   gst_object_unref (qtmux->collect);
851 
852   g_slist_free (qtmux->sinkpads);
853 
854   G_OBJECT_CLASS (parent_class)->finalize (object);
855 }
856 
857 static GstBuffer *
gst_qt_mux_prepare_jpc_buffer(GstQTPad * qtpad,GstBuffer * buf,GstQTMux * qtmux)858 gst_qt_mux_prepare_jpc_buffer (GstQTPad * qtpad, GstBuffer * buf,
859     GstQTMux * qtmux)
860 {
861   GstBuffer *newbuf;
862   GstMapInfo map;
863   gsize size;
864 
865   GST_LOG_OBJECT (qtmux, "Preparing jpc buffer");
866 
867   if (buf == NULL)
868     return NULL;
869 
870   size = gst_buffer_get_size (buf);
871   newbuf = gst_buffer_new_and_alloc (size + 8);
872   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_ALL, 8, size);
873 
874   gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
875   GST_WRITE_UINT32_BE (map.data, map.size);
876   GST_WRITE_UINT32_LE (map.data + 4, FOURCC_jp2c);
877 
878   gst_buffer_unmap (buf, &map);
879   gst_buffer_unref (buf);
880 
881   return newbuf;
882 }
883 
884 static gsize
extract_608_field_from_s334_1a(const guint8 * ccdata,gsize ccdata_size,guint field,guint8 ** res)885 extract_608_field_from_s334_1a (const guint8 * ccdata, gsize ccdata_size,
886     guint field, guint8 ** res)
887 {
888   guint8 *storage;
889   gsize storage_size = 128;
890   gsize i, res_size = 0;
891 
892   storage = g_malloc0 (storage_size);
893 
894   /* Iterate over the ccdata and put the corresponding tuples for the given field
895    * in the storage */
896   for (i = 0; i < ccdata_size; i += 3) {
897     if ((field == 1 && (ccdata[i * 3] & 0x80)) ||
898         (field == 2 && !(ccdata[i * 3] & 0x80))) {
899       GST_DEBUG ("Storing matching cc for field %d : 0x%02x 0x%02x", field,
900           ccdata[i * 3 + 1], ccdata[i * 3 + 2]);
901       if (res_size >= storage_size) {
902         storage_size += 128;
903         storage = g_realloc (storage, storage_size);
904       }
905       storage[res_size] = ccdata[i * 3 + 1];
906       storage[res_size + 1] = ccdata[i * 3 + 2];
907       res_size += 2;
908     }
909   }
910 
911   if (res_size == 0) {
912     g_free (storage);
913     *res = NULL;
914     return 0;
915   }
916 
917   *res = storage;
918   return res_size;
919 }
920 
921 
922 static GstBuffer *
gst_qt_mux_prepare_caption_buffer(GstQTPad * qtpad,GstBuffer * buf,GstQTMux * qtmux)923 gst_qt_mux_prepare_caption_buffer (GstQTPad * qtpad, GstBuffer * buf,
924     GstQTMux * qtmux)
925 {
926   GstBuffer *newbuf = NULL;
927   GstMapInfo map, inmap;
928   gsize size;
929   gboolean in_prefill;
930 
931   if (buf == NULL)
932     return NULL;
933 
934   in_prefill = (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL);
935 
936   size = gst_buffer_get_size (buf);
937   gst_buffer_map (buf, &inmap, GST_MAP_READ);
938 
939   GST_LOG_OBJECT (qtmux,
940       "Preparing caption buffer %" GST_FOURCC_FORMAT " size:%" G_GSIZE_FORMAT,
941       GST_FOURCC_ARGS (qtpad->fourcc), size);
942 
943   switch (qtpad->fourcc) {
944     case FOURCC_c608:
945     {
946       guint8 *cdat, *cdt2;
947       gsize cdat_size, cdt2_size, total_size = 0;
948       gsize write_offs = 0;
949 
950       cdat_size =
951           extract_608_field_from_s334_1a (inmap.data, inmap.size, 1, &cdat);
952       cdt2_size =
953           extract_608_field_from_s334_1a (inmap.data, inmap.size, 2, &cdt2);
954 
955       if (cdat_size)
956         total_size += cdat_size + 8;
957       if (cdt2_size)
958         total_size += cdt2_size + 8;
959       if (total_size == 0) {
960         GST_DEBUG_OBJECT (qtmux, "No 608 data ?");
961         /* FIXME : We might want to *always* store something, even if
962          * it's "empty" CC (i.e. 0x80 0x80) */
963         break;
964       }
965 
966       newbuf = gst_buffer_new_and_alloc (in_prefill ? 20 : total_size);
967       /* Let's copy over all metadata and not the memory */
968       gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
969 
970       gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
971       if (cdat_size || in_prefill) {
972         GST_WRITE_UINT32_BE (map.data, in_prefill ? 10 : cdat_size + 8);
973         GST_WRITE_UINT32_LE (map.data + 4, FOURCC_cdat);
974         if (cdat_size)
975           memcpy (map.data + 8, cdat, in_prefill ? 2 : cdat_size);
976         else {
977           /* Write 'empty' CC */
978           map.data[8] = 0x80;
979           map.data[9] = 0x80;
980         }
981         write_offs = in_prefill ? 10 : cdat_size + 8;
982         if (cdat_size)
983           g_free (cdat);
984       }
985 
986       if (cdt2_size || in_prefill) {
987         GST_WRITE_UINT32_BE (map.data + write_offs,
988             in_prefill ? 10 : cdt2_size + 8);
989         GST_WRITE_UINT32_LE (map.data + write_offs + 4, FOURCC_cdt2);
990         if (cdt2_size)
991           memcpy (map.data + write_offs + 8, cdt2, in_prefill ? 2 : cdt2_size);
992         else {
993           /* Write 'empty' CC */
994           map.data[write_offs + 8] = 0x80;
995           map.data[write_offs + 9] = 0x80;
996         }
997         if (cdt2_size)
998           g_free (cdt2);
999       }
1000       gst_buffer_unmap (newbuf, &map);
1001       break;
1002     }
1003       break;
1004     case FOURCC_c708:
1005     {
1006       /* Take the whole CDP */
1007       if (in_prefill && size > 256) {
1008         GST_ERROR_OBJECT (qtmux, "Input C708 CDP too big for prefill mode !");
1009         break;
1010       }
1011       newbuf = gst_buffer_new_and_alloc (in_prefill ? 256 + 8 : size + 8);
1012 
1013       /* Let's copy over all metadata and not the memory */
1014       gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1015 
1016       gst_buffer_map (newbuf, &map, GST_MAP_WRITE);
1017 
1018       GST_WRITE_UINT32_BE (map.data, size + 8);
1019       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_ccdp);
1020       memcpy (map.data + 8, inmap.data, inmap.size);
1021 
1022       gst_buffer_unmap (newbuf, &map);
1023       break;
1024     }
1025     default:
1026       /* theoretically this should never happen, but let's keep this here in case */
1027       GST_WARNING_OBJECT (qtmux, "Unknown caption format");
1028       break;
1029   }
1030 
1031   gst_buffer_unmap (buf, &inmap);
1032   gst_buffer_unref (buf);
1033 
1034   return newbuf;
1035 }
1036 
1037 static GstBuffer *
gst_qt_mux_prepare_tx3g_buffer(GstQTPad * qtpad,GstBuffer * buf,GstQTMux * qtmux)1038 gst_qt_mux_prepare_tx3g_buffer (GstQTPad * qtpad, GstBuffer * buf,
1039     GstQTMux * qtmux)
1040 {
1041   GstBuffer *newbuf;
1042   GstMapInfo frommap;
1043   GstMapInfo tomap;
1044   gsize size;
1045   const guint8 *dataend;
1046 
1047   GST_LOG_OBJECT (qtmux, "Preparing tx3g buffer %" GST_PTR_FORMAT, buf);
1048 
1049   if (buf == NULL)
1050     return NULL;
1051 
1052   gst_buffer_map (buf, &frommap, GST_MAP_READ);
1053 
1054   dataend = memchr (frommap.data, 0, frommap.size);
1055   size = dataend ? dataend - frommap.data : frommap.size;
1056   newbuf = gst_buffer_new_and_alloc (size + 2);
1057 
1058   gst_buffer_map (newbuf, &tomap, GST_MAP_WRITE);
1059 
1060   GST_WRITE_UINT16_BE (tomap.data, size);
1061   memcpy (tomap.data + 2, frommap.data, size);
1062 
1063   gst_buffer_unmap (newbuf, &tomap);
1064   gst_buffer_unmap (buf, &frommap);
1065 
1066   gst_buffer_copy_into (newbuf, buf, GST_BUFFER_COPY_METADATA, 0, size);
1067 
1068   /* gst_buffer_copy_into is trying to be too clever and
1069    * won't copy duration when size is different */
1070   GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf);
1071 
1072   gst_buffer_unref (buf);
1073 
1074   return newbuf;
1075 }
1076 
1077 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)1078 gst_qt_mux_pad_add_ac3_extension (GstQTMux * qtmux, GstQTPad * qtpad,
1079     guint8 fscod, guint8 frmsizcod, guint8 bsid, guint8 bsmod, guint8 acmod,
1080     guint8 lfe_on)
1081 {
1082   AtomInfo *ext;
1083 
1084   g_return_if_fail (qtpad->trak_ste);
1085 
1086   ext = build_ac3_extension (fscod, bsid, bsmod, acmod, lfe_on, frmsizcod >> 1);        /* bitrate_code is inside frmsizcod */
1087 
1088   sample_table_entry_add_ext_atom (qtpad->trak_ste, ext);
1089 }
1090 
1091 static GstBuffer *
gst_qt_mux_prepare_parse_ac3_frame(GstQTPad * qtpad,GstBuffer * buf,GstQTMux * qtmux)1092 gst_qt_mux_prepare_parse_ac3_frame (GstQTPad * qtpad, GstBuffer * buf,
1093     GstQTMux * qtmux)
1094 {
1095   GstMapInfo map;
1096   GstByteReader reader;
1097   guint off;
1098 
1099   if (!gst_buffer_map (buf, &map, GST_MAP_READ)) {
1100     GST_WARNING_OBJECT (qtpad->collect.pad, "Failed to map buffer");
1101     return buf;
1102   }
1103 
1104   if (G_UNLIKELY (map.size < 8))
1105     goto done;
1106 
1107   gst_byte_reader_init (&reader, map.data, map.size);
1108   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
1109       0, map.size);
1110 
1111   if (off != -1) {
1112     GstBitReader bits;
1113     guint8 fscod, frmsizcod, bsid, bsmod, acmod, lfe_on;
1114 
1115     GST_DEBUG_OBJECT (qtpad->collect.pad, "Found ac3 sync point at offset: %u",
1116         off);
1117 
1118     gst_bit_reader_init (&bits, map.data, map.size);
1119 
1120     /* off + sync + crc */
1121     gst_bit_reader_skip_unchecked (&bits, off * 8 + 16 + 16);
1122 
1123     fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
1124     frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
1125     bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
1126     bsmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1127     acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
1128 
1129     if ((acmod & 0x1) && (acmod != 0x1))        /* 3 front channels */
1130       gst_bit_reader_skip_unchecked (&bits, 2);
1131     if ((acmod & 0x4))          /* if a surround channel exists */
1132       gst_bit_reader_skip_unchecked (&bits, 2);
1133     if (acmod == 0x2)           /* if in 2/0 mode */
1134       gst_bit_reader_skip_unchecked (&bits, 2);
1135 
1136     lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
1137 
1138     gst_qt_mux_pad_add_ac3_extension (qtmux, qtpad, fscod, frmsizcod, bsid,
1139         bsmod, acmod, lfe_on);
1140 
1141     /* AC-3 spec says that those values should be constant for the
1142      * whole stream when muxed in mp4. We trust the input follows it */
1143     GST_DEBUG_OBJECT (qtpad->collect.pad, "Data parsed, removing "
1144         "prepare buffer function");
1145     qtpad->prepare_buf_func = NULL;
1146   }
1147 
1148 done:
1149   gst_buffer_unmap (buf, &map);
1150   return buf;
1151 }
1152 
1153 static GstBuffer *
gst_qt_mux_create_empty_tx3g_buffer(GstQTPad * qtpad,gint64 duration)1154 gst_qt_mux_create_empty_tx3g_buffer (GstQTPad * qtpad, gint64 duration)
1155 {
1156   guint8 *data;
1157 
1158   data = g_malloc (2);
1159   GST_WRITE_UINT16_BE (data, 0);
1160 
1161   return gst_buffer_new_wrapped (data, 2);
1162 }
1163 
1164 static void
gst_qt_mux_add_mp4_tag(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1165 gst_qt_mux_add_mp4_tag (GstQTMux * qtmux, const GstTagList * list,
1166     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1167 {
1168   switch (gst_tag_get_type (tag)) {
1169       /* strings */
1170     case G_TYPE_STRING:
1171     {
1172       gchar *str = NULL;
1173 
1174       if (!gst_tag_list_get_string (list, tag, &str) || !str)
1175         break;
1176       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1177           GST_FOURCC_ARGS (fourcc), str);
1178       atom_udta_add_str_tag (udta, fourcc, str);
1179       g_free (str);
1180       break;
1181     }
1182       /* double */
1183     case G_TYPE_DOUBLE:
1184     {
1185       gdouble value;
1186 
1187       if (!gst_tag_list_get_double (list, tag, &value))
1188         break;
1189       GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1190           GST_FOURCC_ARGS (fourcc), (gint) value);
1191       atom_udta_add_uint_tag (udta, fourcc, 21, (gint) value);
1192       break;
1193     }
1194     case G_TYPE_UINT:
1195     {
1196       guint value = 0;
1197       if (tag2) {
1198         /* paired unsigned integers */
1199         guint count = 0;
1200         gboolean got_tag;
1201 
1202         got_tag = gst_tag_list_get_uint (list, tag, &value);
1203         got_tag = gst_tag_list_get_uint (list, tag2, &count) || got_tag;
1204         if (!got_tag)
1205           break;
1206         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u/%u",
1207             GST_FOURCC_ARGS (fourcc), value, count);
1208         atom_udta_add_uint_tag (udta, fourcc, 0,
1209             value << 16 | (count & 0xFFFF));
1210       } else {
1211         /* unpaired unsigned integers */
1212         if (!gst_tag_list_get_uint (list, tag, &value))
1213           break;
1214         GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %u",
1215             GST_FOURCC_ARGS (fourcc), value);
1216         atom_udta_add_uint_tag (udta, fourcc, 1, value);
1217       }
1218       break;
1219     }
1220     default:
1221       g_assert_not_reached ();
1222       break;
1223   }
1224 }
1225 
1226 static void
gst_qt_mux_add_mp4_date(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1227 gst_qt_mux_add_mp4_date (GstQTMux * qtmux, const GstTagList * list,
1228     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1229 {
1230   GDate *date = NULL;
1231   GDateYear year;
1232   GDateMonth month;
1233   GDateDay day;
1234   gchar *str;
1235 
1236   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1237 
1238   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1239     return;
1240 
1241   year = g_date_get_year (date);
1242   month = g_date_get_month (date);
1243   day = g_date_get_day (date);
1244 
1245   g_date_free (date);
1246 
1247   if (year == G_DATE_BAD_YEAR && month == G_DATE_BAD_MONTH &&
1248       day == G_DATE_BAD_DAY) {
1249     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1250     return;
1251   }
1252 
1253   str = g_strdup_printf ("%u-%u-%u", year, month, day);
1254   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1255       GST_FOURCC_ARGS (fourcc), str);
1256   atom_udta_add_str_tag (udta, fourcc, str);
1257   g_free (str);
1258 }
1259 
1260 static void
gst_qt_mux_add_mp4_cover(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1261 gst_qt_mux_add_mp4_cover (GstQTMux * qtmux, const GstTagList * list,
1262     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1263 {
1264   GValue value = { 0, };
1265   GstBuffer *buf;
1266   GstSample *sample;
1267   GstCaps *caps;
1268   GstStructure *structure;
1269   gint flags = 0;
1270   GstMapInfo map;
1271 
1272   g_return_if_fail (gst_tag_get_type (tag) == GST_TYPE_SAMPLE);
1273 
1274   if (!gst_tag_list_copy_value (&value, list, tag))
1275     return;
1276 
1277   sample = gst_value_get_sample (&value);
1278 
1279   if (!sample)
1280     goto done;
1281 
1282   buf = gst_sample_get_buffer (sample);
1283   if (!buf)
1284     goto done;
1285 
1286   caps = gst_sample_get_caps (sample);
1287   if (!caps) {
1288     GST_WARNING_OBJECT (qtmux, "preview image without caps");
1289     goto done;
1290   }
1291 
1292   GST_DEBUG_OBJECT (qtmux, "preview image caps %" GST_PTR_FORMAT, caps);
1293 
1294   structure = gst_caps_get_structure (caps, 0);
1295   if (gst_structure_has_name (structure, "image/jpeg"))
1296     flags = 13;
1297   else if (gst_structure_has_name (structure, "image/png"))
1298     flags = 14;
1299 
1300   if (!flags) {
1301     GST_WARNING_OBJECT (qtmux, "preview image format not supported");
1302     goto done;
1303   }
1304 
1305   gst_buffer_map (buf, &map, GST_MAP_READ);
1306   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT
1307       " -> image size %" G_GSIZE_FORMAT "", GST_FOURCC_ARGS (fourcc), map.size);
1308   atom_udta_add_tag (udta, fourcc, flags, map.data, map.size);
1309   gst_buffer_unmap (buf, &map);
1310 done:
1311   g_value_unset (&value);
1312 }
1313 
1314 static void
gst_qt_mux_add_3gp_str(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1315 gst_qt_mux_add_3gp_str (GstQTMux * qtmux, const GstTagList * list,
1316     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1317 {
1318   gchar *str = NULL;
1319   guint number;
1320 
1321   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_STRING);
1322   g_return_if_fail (!tag2 || gst_tag_get_type (tag2) == G_TYPE_UINT);
1323 
1324   if (!gst_tag_list_get_string (list, tag, &str) || !str)
1325     return;
1326 
1327   if (tag2)
1328     if (!gst_tag_list_get_uint (list, tag2, &number))
1329       tag2 = NULL;
1330 
1331   if (!tag2) {
1332     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1333         GST_FOURCC_ARGS (fourcc), str);
1334     atom_udta_add_3gp_str_tag (udta, fourcc, str);
1335   } else {
1336     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s/%d",
1337         GST_FOURCC_ARGS (fourcc), str, number);
1338     atom_udta_add_3gp_str_int_tag (udta, fourcc, str, number);
1339   }
1340 
1341   g_free (str);
1342 }
1343 
1344 static void
gst_qt_mux_add_3gp_date(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1345 gst_qt_mux_add_3gp_date (GstQTMux * qtmux, const GstTagList * list,
1346     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1347 {
1348   GDate *date = NULL;
1349   GDateYear year;
1350 
1351   g_return_if_fail (gst_tag_get_type (tag) == G_TYPE_DATE);
1352 
1353   if (!gst_tag_list_get_date (list, tag, &date) || !date)
1354     return;
1355 
1356   year = g_date_get_year (date);
1357   g_date_free (date);
1358 
1359   if (year == G_DATE_BAD_YEAR) {
1360     GST_WARNING_OBJECT (qtmux, "invalid date in tag");
1361     return;
1362   }
1363 
1364   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %d",
1365       GST_FOURCC_ARGS (fourcc), year);
1366   atom_udta_add_3gp_uint_tag (udta, fourcc, year);
1367 }
1368 
1369 static void
gst_qt_mux_add_3gp_location(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1370 gst_qt_mux_add_3gp_location (GstQTMux * qtmux, const GstTagList * list,
1371     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1372 {
1373   gdouble latitude = -360, longitude = -360, altitude = 0;
1374   gchar *location = NULL;
1375   guint8 *data, *ddata;
1376   gint size = 0, len = 0;
1377   gboolean ret = FALSE;
1378 
1379   g_return_if_fail (strcmp (tag, GST_TAG_GEO_LOCATION_NAME) == 0);
1380 
1381   ret = gst_tag_list_get_string (list, tag, &location);
1382   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LONGITUDE,
1383       &longitude);
1384   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_LATITUDE,
1385       &latitude);
1386   ret |= gst_tag_list_get_double (list, GST_TAG_GEO_LOCATION_ELEVATION,
1387       &altitude);
1388 
1389   if (!ret)
1390     return;
1391 
1392   if (location)
1393     len = strlen (location);
1394   size += len + 1 + 2;
1395 
1396   /* role + (long, lat, alt) + body + notes */
1397   size += 1 + 3 * 4 + 1 + 1;
1398 
1399   data = ddata = g_malloc (size);
1400 
1401   /* language tag */
1402   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1403   /* location */
1404   if (location)
1405     memcpy (data + 2, location, len);
1406   GST_WRITE_UINT8 (data + 2 + len, 0);
1407   data += len + 1 + 2;
1408   /* role */
1409   GST_WRITE_UINT8 (data, 0);
1410   /* long, lat, alt */
1411 #define QT_WRITE_SFP32(data, fp) GST_WRITE_UINT32_BE(data, (guint32) ((gint) (fp * 65536.0)))
1412   QT_WRITE_SFP32 (data + 1, longitude);
1413   QT_WRITE_SFP32 (data + 5, latitude);
1414   QT_WRITE_SFP32 (data + 9, altitude);
1415   /* neither astronomical body nor notes */
1416   GST_WRITE_UINT16_BE (data + 13, 0);
1417 
1418   GST_DEBUG_OBJECT (qtmux, "Adding tag 'loci'");
1419   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1420   g_free (ddata);
1421 }
1422 
1423 static void
gst_qt_mux_add_3gp_keywords(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1424 gst_qt_mux_add_3gp_keywords (GstQTMux * qtmux, const GstTagList * list,
1425     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1426 {
1427   gchar *keywords = NULL;
1428   guint8 *data, *ddata;
1429   gint size = 0, i;
1430   gchar **kwds;
1431 
1432   g_return_if_fail (strcmp (tag, GST_TAG_KEYWORDS) == 0);
1433 
1434   if (!gst_tag_list_get_string (list, tag, &keywords) || !keywords)
1435     return;
1436 
1437   kwds = g_strsplit (keywords, ",", 0);
1438   g_free (keywords);
1439 
1440   size = 0;
1441   for (i = 0; kwds[i]; i++) {
1442     /* size byte + null-terminator */
1443     size += strlen (kwds[i]) + 1 + 1;
1444   }
1445 
1446   /* language tag + count + keywords */
1447   size += 2 + 1;
1448 
1449   data = ddata = g_malloc (size);
1450 
1451   /* language tag */
1452   GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
1453   /* count */
1454   GST_WRITE_UINT8 (data + 2, i);
1455   data += 3;
1456   /* keywords */
1457   for (i = 0; kwds[i]; ++i) {
1458     gint len = strlen (kwds[i]);
1459 
1460     GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1461         GST_FOURCC_ARGS (fourcc), kwds[i]);
1462     /* size */
1463     GST_WRITE_UINT8 (data, len + 1);
1464     memcpy (data + 1, kwds[i], len + 1);
1465     data += len + 2;
1466   }
1467 
1468   g_strfreev (kwds);
1469 
1470   atom_udta_add_3gp_tag (udta, fourcc, ddata, size);
1471   g_free (ddata);
1472 }
1473 
1474 static gboolean
gst_qt_mux_parse_classification_string(GstQTMux * qtmux,const gchar * input,guint32 * p_fourcc,guint16 * p_table,gchar ** p_content)1475 gst_qt_mux_parse_classification_string (GstQTMux * qtmux, const gchar * input,
1476     guint32 * p_fourcc, guint16 * p_table, gchar ** p_content)
1477 {
1478   guint32 fourcc;
1479   gint table;
1480   gint size;
1481   const gchar *data;
1482 
1483   data = input;
1484   size = strlen (input);
1485 
1486   if (size < 4 + 3 + 1 + 1 + 1) {
1487     /* at least the minimum xxxx://y/z */
1488     GST_WARNING_OBJECT (qtmux, "Classification tag input (%s) too short, "
1489         "ignoring", input);
1490     return FALSE;
1491   }
1492 
1493   /* read the fourcc */
1494   memcpy (&fourcc, data, 4);
1495   size -= 4;
1496   data += 4;
1497 
1498   if (strncmp (data, "://", 3) != 0) {
1499     goto mismatch;
1500   }
1501   data += 3;
1502   size -= 3;
1503 
1504   /* read the table number */
1505   if (sscanf (data, "%d", &table) != 1) {
1506     goto mismatch;
1507   }
1508   if (table < 0) {
1509     GST_WARNING_OBJECT (qtmux, "Invalid table number in classification tag (%d)"
1510         ", table numbers should be positive, ignoring tag", table);
1511     return FALSE;
1512   }
1513 
1514   /* find the next / */
1515   while (size > 0 && data[0] != '/') {
1516     data += 1;
1517     size -= 1;
1518   }
1519   if (size == 0) {
1520     goto mismatch;
1521   }
1522   g_assert (data[0] == '/');
1523 
1524   /* skip the '/' */
1525   data += 1;
1526   size -= 1;
1527   if (size == 0) {
1528     goto mismatch;
1529   }
1530 
1531   /* read up the rest of the string */
1532   *p_content = g_strdup (data);
1533   *p_table = (guint16) table;
1534   *p_fourcc = fourcc;
1535   return TRUE;
1536 
1537 mismatch:
1538   {
1539     GST_WARNING_OBJECT (qtmux, "Ignoring classification tag as "
1540         "input (%s) didn't match the expected entitycode://table/content",
1541         input);
1542     return FALSE;
1543   }
1544 }
1545 
1546 static void
gst_qt_mux_add_3gp_classification(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta,const char * tag,const char * tag2,guint32 fourcc)1547 gst_qt_mux_add_3gp_classification (GstQTMux * qtmux, const GstTagList * list,
1548     AtomUDTA * udta, const char *tag, const char *tag2, guint32 fourcc)
1549 {
1550   gchar *clsf_data = NULL;
1551   gint size = 0;
1552   guint32 entity = 0;
1553   guint16 table = 0;
1554   gchar *content = NULL;
1555   guint8 *data;
1556 
1557   g_return_if_fail (strcmp (tag, GST_TAG_3GP_CLASSIFICATION) == 0);
1558 
1559   if (!gst_tag_list_get_string (list, tag, &clsf_data) || !clsf_data)
1560     return;
1561 
1562   GST_DEBUG_OBJECT (qtmux, "Adding tag %" GST_FOURCC_FORMAT " -> %s",
1563       GST_FOURCC_ARGS (fourcc), clsf_data);
1564 
1565   /* parse the string, format is:
1566    * entityfourcc://table/content
1567    */
1568   gst_qt_mux_parse_classification_string (qtmux, clsf_data, &entity, &table,
1569       &content);
1570   g_free (clsf_data);
1571   /* +1 for the \0 */
1572   size = strlen (content) + 1;
1573 
1574   /* now we have everything, build the atom
1575    * atom description is at 3GPP TS 26.244 V8.2.0 (2009-09) */
1576   data = g_malloc (4 + 2 + 2 + size);
1577   GST_WRITE_UINT32_LE (data, entity);
1578   GST_WRITE_UINT16_BE (data + 4, (guint16) table);
1579   GST_WRITE_UINT16_BE (data + 6, 0);
1580   memcpy (data + 8, content, size);
1581   g_free (content);
1582 
1583   atom_udta_add_3gp_tag (udta, fourcc, data, 4 + 2 + 2 + size);
1584   g_free (data);
1585 }
1586 
1587 typedef void (*GstQTMuxAddUdtaTagFunc) (GstQTMux * mux,
1588     const GstTagList * list, AtomUDTA * udta, const char *tag,
1589     const char *tag2, guint32 fourcc);
1590 
1591 /*
1592  * Struct to record mappings from gstreamer tags to fourcc codes
1593  */
1594 typedef struct _GstTagToFourcc
1595 {
1596   guint32 fourcc;
1597   const gchar *gsttag;
1598   const gchar *gsttag2;
1599   const GstQTMuxAddUdtaTagFunc func;
1600 } GstTagToFourcc;
1601 
1602 /* tag list tags to fourcc matching */
1603 static const GstTagToFourcc tag_matches_mp4[] = {
1604   {FOURCC__alb, GST_TAG_ALBUM, NULL, gst_qt_mux_add_mp4_tag},
1605   {FOURCC_soal, GST_TAG_ALBUM_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1606   {FOURCC__ART, GST_TAG_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1607   {FOURCC_soar, GST_TAG_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1608   {FOURCC_aART, GST_TAG_ALBUM_ARTIST, NULL, gst_qt_mux_add_mp4_tag},
1609   {FOURCC_soaa, GST_TAG_ALBUM_ARTIST_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1610   {FOURCC__swr, GST_TAG_APPLICATION_NAME, NULL, gst_qt_mux_add_mp4_tag},
1611   {FOURCC__cmt, GST_TAG_COMMENT, NULL, gst_qt_mux_add_mp4_tag},
1612   {FOURCC__wrt, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_mp4_tag},
1613   {FOURCC_soco, GST_TAG_COMPOSER_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1614   {FOURCC_tvsh, GST_TAG_SHOW_NAME, NULL, gst_qt_mux_add_mp4_tag},
1615   {FOURCC_sosn, GST_TAG_SHOW_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1616   {FOURCC_tvsn, GST_TAG_SHOW_SEASON_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1617   {FOURCC_tves, GST_TAG_SHOW_EPISODE_NUMBER, NULL, gst_qt_mux_add_mp4_tag},
1618   {FOURCC__gen, GST_TAG_GENRE, NULL, gst_qt_mux_add_mp4_tag},
1619   {FOURCC__nam, GST_TAG_TITLE, NULL, gst_qt_mux_add_mp4_tag},
1620   {FOURCC_sonm, GST_TAG_TITLE_SORTNAME, NULL, gst_qt_mux_add_mp4_tag},
1621   {FOURCC_perf, GST_TAG_PERFORMER, NULL, gst_qt_mux_add_mp4_tag},
1622   {FOURCC__grp, GST_TAG_GROUPING, NULL, gst_qt_mux_add_mp4_tag},
1623   {FOURCC__des, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_mp4_tag},
1624   {FOURCC__lyr, GST_TAG_LYRICS, NULL, gst_qt_mux_add_mp4_tag},
1625   {FOURCC__too, GST_TAG_ENCODER, NULL, gst_qt_mux_add_mp4_tag},
1626   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_mp4_tag},
1627   {FOURCC_keyw, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_mp4_tag},
1628   {FOURCC__day, GST_TAG_DATE, NULL, gst_qt_mux_add_mp4_date},
1629   {FOURCC_tmpo, GST_TAG_BEATS_PER_MINUTE, NULL, gst_qt_mux_add_mp4_tag},
1630   {FOURCC_trkn, GST_TAG_TRACK_NUMBER, GST_TAG_TRACK_COUNT,
1631       gst_qt_mux_add_mp4_tag},
1632   {FOURCC_disk, GST_TAG_ALBUM_VOLUME_NUMBER, GST_TAG_ALBUM_VOLUME_COUNT,
1633       gst_qt_mux_add_mp4_tag},
1634   {FOURCC_covr, GST_TAG_PREVIEW_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1635   {FOURCC_covr, GST_TAG_IMAGE, NULL, gst_qt_mux_add_mp4_cover},
1636   {0, NULL,}
1637 };
1638 
1639 static const GstTagToFourcc tag_matches_3gp[] = {
1640   {FOURCC_titl, GST_TAG_TITLE, NULL, gst_qt_mux_add_3gp_str},
1641   {FOURCC_dscp, GST_TAG_DESCRIPTION, NULL, gst_qt_mux_add_3gp_str},
1642   {FOURCC_cprt, GST_TAG_COPYRIGHT, NULL, gst_qt_mux_add_3gp_str},
1643   {FOURCC_perf, GST_TAG_ARTIST, NULL, gst_qt_mux_add_3gp_str},
1644   {FOURCC_auth, GST_TAG_COMPOSER, NULL, gst_qt_mux_add_3gp_str},
1645   {FOURCC_gnre, GST_TAG_GENRE, NULL, gst_qt_mux_add_3gp_str},
1646   {FOURCC_kywd, GST_TAG_KEYWORDS, NULL, gst_qt_mux_add_3gp_keywords},
1647   {FOURCC_yrrc, GST_TAG_DATE, NULL, gst_qt_mux_add_3gp_date},
1648   {FOURCC_albm, GST_TAG_ALBUM, GST_TAG_TRACK_NUMBER, gst_qt_mux_add_3gp_str},
1649   {FOURCC_loci, GST_TAG_GEO_LOCATION_NAME, NULL, gst_qt_mux_add_3gp_location},
1650   {FOURCC_clsf, GST_TAG_3GP_CLASSIFICATION, NULL,
1651       gst_qt_mux_add_3gp_classification},
1652   {0, NULL,}
1653 };
1654 
1655 /* qtdemux produces these for atoms it cannot parse */
1656 #define GST_QT_DEMUX_PRIVATE_TAG "private-qt-tag"
1657 
1658 static void
gst_qt_mux_add_xmp_tags(GstQTMux * qtmux,const GstTagList * list)1659 gst_qt_mux_add_xmp_tags (GstQTMux * qtmux, const GstTagList * list)
1660 {
1661   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1662   GstBuffer *xmp = NULL;
1663 
1664   /* adobe specs only have 'quicktime' and 'mp4',
1665    * but I guess we can extrapolate to gpp.
1666    * Keep mj2 out for now as we don't add any tags for it yet.
1667    * If you have further info about xmp on these formats, please share */
1668   if (qtmux_klass->format == GST_QT_MUX_FORMAT_MJ2)
1669     return;
1670 
1671   GST_DEBUG_OBJECT (qtmux, "Adding xmp tags");
1672 
1673   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
1674     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1675         list, TRUE);
1676     if (xmp)
1677       atom_udta_add_xmp_tags (&qtmux->moov->udta, xmp);
1678   } else {
1679     AtomInfo *ainfo;
1680     /* for isom/mp4, it is a top level uuid atom */
1681     xmp = gst_tag_xmp_writer_tag_list_to_xmp_buffer (GST_TAG_XMP_WRITER (qtmux),
1682         list, TRUE);
1683     if (xmp) {
1684       ainfo = build_uuid_xmp_atom (xmp);
1685       if (ainfo) {
1686         qtmux->extra_atoms = g_slist_prepend (qtmux->extra_atoms, ainfo);
1687       }
1688     }
1689   }
1690   if (xmp)
1691     gst_buffer_unref (xmp);
1692 }
1693 
1694 static void
gst_qt_mux_add_metadata_tags(GstQTMux * qtmux,const GstTagList * list,AtomUDTA * udta)1695 gst_qt_mux_add_metadata_tags (GstQTMux * qtmux, const GstTagList * list,
1696     AtomUDTA * udta)
1697 {
1698   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
1699   guint32 fourcc;
1700   gint i;
1701   const gchar *tag, *tag2;
1702   const GstTagToFourcc *tag_matches;
1703 
1704   switch (qtmux_klass->format) {
1705     case GST_QT_MUX_FORMAT_3GP:
1706       tag_matches = tag_matches_3gp;
1707       break;
1708     case GST_QT_MUX_FORMAT_MJ2:
1709       tag_matches = NULL;
1710       break;
1711     default:
1712       /* sort of iTunes style for mp4 and QT (?) */
1713       tag_matches = tag_matches_mp4;
1714       break;
1715   }
1716 
1717   if (!tag_matches)
1718     return;
1719 
1720   /* Clear existing tags so we don't add them over and over */
1721   atom_udta_clear_tags (udta);
1722 
1723   for (i = 0; tag_matches[i].fourcc; i++) {
1724     fourcc = tag_matches[i].fourcc;
1725     tag = tag_matches[i].gsttag;
1726     tag2 = tag_matches[i].gsttag2;
1727 
1728     g_assert (tag_matches[i].func);
1729     tag_matches[i].func (qtmux, list, udta, tag, tag2, fourcc);
1730   }
1731 
1732   /* add unparsed blobs if present */
1733   if (gst_tag_exists (GST_QT_DEMUX_PRIVATE_TAG)) {
1734     guint num_tags;
1735 
1736     num_tags = gst_tag_list_get_tag_size (list, GST_QT_DEMUX_PRIVATE_TAG);
1737     for (i = 0; i < num_tags; ++i) {
1738       GstSample *sample = NULL;
1739       GstBuffer *buf;
1740       const GstStructure *s;
1741 
1742       if (!gst_tag_list_get_sample_index (list, GST_QT_DEMUX_PRIVATE_TAG, i,
1743               &sample))
1744         continue;
1745       buf = gst_sample_get_buffer (sample);
1746 
1747       if (buf && (s = gst_sample_get_info (sample))) {
1748         const gchar *style = NULL;
1749         GstMapInfo map;
1750 
1751         gst_buffer_map (buf, &map, GST_MAP_READ);
1752         GST_DEBUG_OBJECT (qtmux,
1753             "Found private tag %d/%d; size %" G_GSIZE_FORMAT ", info %"
1754             GST_PTR_FORMAT, i, num_tags, map.size, s);
1755         if (s && (style = gst_structure_get_string (s, "style"))) {
1756           /* try to prevent some style tag ending up into another variant
1757            * (todo: make into a list if more cases) */
1758           if ((strcmp (style, "itunes") == 0 &&
1759                   qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) ||
1760               (strcmp (style, "iso") == 0 &&
1761                   qtmux_klass->format == GST_QT_MUX_FORMAT_3GP)) {
1762             GST_DEBUG_OBJECT (qtmux, "Adding private tag");
1763             atom_udta_add_blob_tag (udta, map.data, map.size);
1764           }
1765         }
1766         gst_buffer_unmap (buf, &map);
1767       }
1768       gst_sample_unref (sample);
1769     }
1770   }
1771 
1772   return;
1773 }
1774 
1775 /*
1776  * Gets the tagsetter iface taglist and puts the known tags
1777  * into the output stream
1778  */
1779 static void
gst_qt_mux_setup_metadata(GstQTMux * qtmux)1780 gst_qt_mux_setup_metadata (GstQTMux * qtmux)
1781 {
1782   const GstTagList *tags = NULL;
1783   GSList *walk;
1784 
1785   GST_OBJECT_LOCK (qtmux);
1786   if (qtmux->tags_changed) {
1787     tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (qtmux));
1788     qtmux->tags_changed = FALSE;
1789   }
1790   GST_OBJECT_UNLOCK (qtmux);
1791 
1792   GST_LOG_OBJECT (qtmux, "tags: %" GST_PTR_FORMAT, tags);
1793 
1794   if (tags && !gst_tag_list_is_empty (tags)) {
1795     GstTagList *copy = gst_tag_list_copy (tags);
1796 
1797     GST_DEBUG_OBJECT (qtmux, "Removing bogus tags");
1798     gst_tag_list_remove_tag (copy, GST_TAG_VIDEO_CODEC);
1799     gst_tag_list_remove_tag (copy, GST_TAG_AUDIO_CODEC);
1800     gst_tag_list_remove_tag (copy, GST_TAG_CONTAINER_FORMAT);
1801 
1802     GST_DEBUG_OBJECT (qtmux, "Formatting tags");
1803     gst_qt_mux_add_metadata_tags (qtmux, copy, &qtmux->moov->udta);
1804     gst_qt_mux_add_xmp_tags (qtmux, copy);
1805     gst_tag_list_unref (copy);
1806   } else {
1807     GST_DEBUG_OBJECT (qtmux, "No new tags received");
1808   }
1809 
1810   for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
1811     GstCollectData *cdata = (GstCollectData *) walk->data;
1812     GstQTPad *qpad = (GstQTPad *) cdata;
1813     GstPad *pad = qpad->collect.pad;
1814 
1815     if (qpad->tags_changed && qpad->tags) {
1816       GST_DEBUG_OBJECT (pad, "Adding tags");
1817       gst_tag_list_remove_tag (qpad->tags, GST_TAG_CONTAINER_FORMAT);
1818       gst_qt_mux_add_metadata_tags (qtmux, qpad->tags, &qpad->trak->udta);
1819       qpad->tags_changed = FALSE;
1820       GST_DEBUG_OBJECT (pad, "Tags added");
1821     } else {
1822       GST_DEBUG_OBJECT (pad, "No new tags received");
1823     }
1824   }
1825 }
1826 
1827 static inline GstBuffer *
_gst_buffer_new_take_data(guint8 * data,guint size)1828 _gst_buffer_new_take_data (guint8 * data, guint size)
1829 {
1830   GstBuffer *buf;
1831 
1832   buf = gst_buffer_new ();
1833   gst_buffer_append_memory (buf,
1834       gst_memory_new_wrapped (0, data, size, 0, size, data, g_free));
1835 
1836   return buf;
1837 }
1838 
1839 static GstFlowReturn
gst_qt_mux_send_buffer(GstQTMux * qtmux,GstBuffer * buf,guint64 * offset,gboolean mind_fast)1840 gst_qt_mux_send_buffer (GstQTMux * qtmux, GstBuffer * buf, guint64 * offset,
1841     gboolean mind_fast)
1842 {
1843   GstFlowReturn res;
1844   gsize size;
1845 
1846   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
1847 
1848   size = gst_buffer_get_size (buf);
1849   GST_LOG_OBJECT (qtmux, "sending buffer size %" G_GSIZE_FORMAT, size);
1850 
1851   if (mind_fast && qtmux->fast_start_file) {
1852     GstMapInfo map;
1853     gint ret;
1854 
1855     GST_LOG_OBJECT (qtmux, "to temporary file");
1856     gst_buffer_map (buf, &map, GST_MAP_READ);
1857     ret = fwrite (map.data, sizeof (guint8), map.size, qtmux->fast_start_file);
1858     gst_buffer_unmap (buf, &map);
1859     gst_buffer_unref (buf);
1860     if (ret != size)
1861       goto write_error;
1862     else
1863       res = GST_FLOW_OK;
1864   } else {
1865     GST_LOG_OBJECT (qtmux, "downstream");
1866     res = gst_pad_push (qtmux->srcpad, buf);
1867   }
1868 
1869   if (G_LIKELY (offset))
1870     *offset += size;
1871 
1872   return res;
1873 
1874   /* ERRORS */
1875 write_error:
1876   {
1877     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1878         ("Failed to write to temporary file"), GST_ERROR_SYSTEM);
1879     return GST_FLOW_ERROR;
1880   }
1881 }
1882 
1883 static gboolean
gst_qt_mux_seek_to_beginning(FILE * f)1884 gst_qt_mux_seek_to_beginning (FILE * f)
1885 {
1886 #ifdef HAVE_FSEEKO
1887   if (fseeko (f, (off_t) 0, SEEK_SET) != 0)
1888     return FALSE;
1889 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1890   if (lseek (fileno (f), (off_t) 0, SEEK_SET) == (off_t) - 1)
1891     return FALSE;
1892 #else
1893   if (fseek (f, (long) 0, SEEK_SET) != 0)
1894     return FALSE;
1895 #endif
1896   return TRUE;
1897 }
1898 
1899 static GstFlowReturn
gst_qt_mux_send_buffered_data(GstQTMux * qtmux,guint64 * offset)1900 gst_qt_mux_send_buffered_data (GstQTMux * qtmux, guint64 * offset)
1901 {
1902   GstFlowReturn ret = GST_FLOW_OK;
1903   GstBuffer *buf = NULL;
1904 
1905   if (fflush (qtmux->fast_start_file))
1906     goto flush_failed;
1907 
1908   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1909     goto seek_failed;
1910 
1911   /* hm, this could all take a really really long time,
1912    * but there may not be another way to get moov atom first
1913    * (somehow optimize copy?) */
1914   GST_DEBUG_OBJECT (qtmux, "Sending buffered data");
1915   while (ret == GST_FLOW_OK) {
1916     const int bufsize = 4096;
1917     GstMapInfo map;
1918     gsize size;
1919 
1920     buf = gst_buffer_new_and_alloc (bufsize);
1921     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1922     size = fread (map.data, sizeof (guint8), bufsize, qtmux->fast_start_file);
1923     if (size == 0) {
1924       gst_buffer_unmap (buf, &map);
1925       break;
1926     }
1927     GST_LOG_OBJECT (qtmux, "Pushing buffered buffer of size %d", (gint) size);
1928     gst_buffer_unmap (buf, &map);
1929     if (size != bufsize)
1930       gst_buffer_set_size (buf, size);
1931     ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
1932     buf = NULL;
1933   }
1934   if (buf)
1935     gst_buffer_unref (buf);
1936 
1937   if (ftruncate (fileno (qtmux->fast_start_file), 0))
1938     goto seek_failed;
1939   if (!gst_qt_mux_seek_to_beginning (qtmux->fast_start_file))
1940     goto seek_failed;
1941 
1942   return ret;
1943 
1944   /* ERRORS */
1945 flush_failed:
1946   {
1947     GST_ELEMENT_ERROR (qtmux, RESOURCE, WRITE,
1948         ("Failed to flush temporary file"), GST_ERROR_SYSTEM);
1949     ret = GST_FLOW_ERROR;
1950     goto fail;
1951   }
1952 seek_failed:
1953   {
1954     GST_ELEMENT_ERROR (qtmux, RESOURCE, SEEK,
1955         ("Failed to seek temporary file"), GST_ERROR_SYSTEM);
1956     ret = GST_FLOW_ERROR;
1957     goto fail;
1958   }
1959 fail:
1960   {
1961     /* clear descriptor so we don't remove temp file later on,
1962      * might be possible to recover */
1963     fclose (qtmux->fast_start_file);
1964     qtmux->fast_start_file = NULL;
1965     return ret;
1966   }
1967 }
1968 
1969 /*
1970  * Sends the initial mdat atom fields (size fields and fourcc type),
1971  * the subsequent buffers are considered part of it's data.
1972  * As we can't predict the amount of data that we are going to place in mdat
1973  * we need to record the position of the size field in the stream so we can
1974  * seek back to it later and update when the streams have finished.
1975  */
1976 static GstFlowReturn
gst_qt_mux_send_mdat_header(GstQTMux * qtmux,guint64 * off,guint64 size,gboolean extended,gboolean fsync_after)1977 gst_qt_mux_send_mdat_header (GstQTMux * qtmux, guint64 * off, guint64 size,
1978     gboolean extended, gboolean fsync_after)
1979 {
1980   GstBuffer *buf;
1981   GstMapInfo map;
1982 
1983   GST_DEBUG_OBJECT (qtmux, "Sending mdat's atom header, "
1984       "size %" G_GUINT64_FORMAT, size);
1985 
1986   /* if the qtmux state is EOS, really write the mdat, otherwise
1987    * allow size == 0 for a placeholder atom */
1988   if (qtmux->state == GST_QT_MUX_STATE_EOS || size > 0)
1989     size += 8;
1990 
1991   if (extended) {
1992     gboolean large_file = (size > MDAT_LARGE_FILE_LIMIT);
1993     /* Always write 16-bytes, but put a free atom first
1994      * if the size is < 4GB. */
1995     buf = gst_buffer_new_and_alloc (16);
1996     gst_buffer_map (buf, &map, GST_MAP_WRITE);
1997 
1998     if (large_file) {
1999       /* Write extended mdat header and large_size field */
2000       GST_WRITE_UINT32_BE (map.data, 1);
2001       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2002       GST_WRITE_UINT64_BE (map.data + 8, size + 8);
2003     } else {
2004       /* Write an empty free atom, then standard 32-bit mdat */
2005       GST_WRITE_UINT32_BE (map.data, 8);
2006       GST_WRITE_UINT32_LE (map.data + 4, FOURCC_free);
2007       GST_WRITE_UINT32_BE (map.data + 8, size);
2008       GST_WRITE_UINT32_LE (map.data + 12, FOURCC_mdat);
2009     }
2010     gst_buffer_unmap (buf, &map);
2011   } else {
2012     buf = gst_buffer_new_and_alloc (8);
2013     gst_buffer_map (buf, &map, GST_MAP_WRITE);
2014 
2015     /* Vanilla 32-bit mdat */
2016     GST_WRITE_UINT32_BE (map.data, size);
2017     GST_WRITE_UINT32_LE (map.data + 4, FOURCC_mdat);
2018     gst_buffer_unmap (buf, &map);
2019   }
2020 
2021   GST_LOG_OBJECT (qtmux, "Pushing mdat header");
2022   if (fsync_after)
2023     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2024 
2025   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2026 
2027 }
2028 
2029 /*
2030  * We get the position of the mdat size field, seek back to it
2031  * and overwrite with the real value
2032  */
2033 static GstFlowReturn
gst_qt_mux_update_mdat_size(GstQTMux * qtmux,guint64 mdat_pos,guint64 mdat_size,guint64 * offset,gboolean fsync_after)2034 gst_qt_mux_update_mdat_size (GstQTMux * qtmux, guint64 mdat_pos,
2035     guint64 mdat_size, guint64 * offset, gboolean fsync_after)
2036 {
2037   GstSegment segment;
2038 
2039   /* We must have recorded the mdat position for this to work */
2040   g_assert (mdat_pos != 0);
2041 
2042   /* seek and rewrite the header */
2043   gst_segment_init (&segment, GST_FORMAT_BYTES);
2044   segment.start = mdat_pos;
2045   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2046 
2047   return gst_qt_mux_send_mdat_header (qtmux, offset, mdat_size, TRUE,
2048       fsync_after);
2049 }
2050 
2051 static GstFlowReturn
gst_qt_mux_send_ftyp(GstQTMux * qtmux,guint64 * off)2052 gst_qt_mux_send_ftyp (GstQTMux * qtmux, guint64 * off)
2053 {
2054   GstBuffer *buf;
2055   guint64 size = 0, offset = 0;
2056   guint8 *data = NULL;
2057 
2058   GST_DEBUG_OBJECT (qtmux, "Sending ftyp atom");
2059 
2060   if (!atom_ftyp_copy_data (qtmux->ftyp, &data, &size, &offset))
2061     goto serialize_error;
2062 
2063   buf = _gst_buffer_new_take_data (data, offset);
2064 
2065   GST_LOG_OBJECT (qtmux, "Pushing ftyp");
2066   return gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2067 
2068   /* ERRORS */
2069 serialize_error:
2070   {
2071     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2072         ("Failed to serialize ftyp"));
2073     return GST_FLOW_ERROR;
2074   }
2075 }
2076 
2077 static void
gst_qt_mux_prepare_ftyp(GstQTMux * qtmux,AtomFTYP ** p_ftyp,GstBuffer ** p_prefix)2078 gst_qt_mux_prepare_ftyp (GstQTMux * qtmux, AtomFTYP ** p_ftyp,
2079     GstBuffer ** p_prefix)
2080 {
2081   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2082   guint32 major, version;
2083   GList *comp;
2084   GstBuffer *prefix = NULL;
2085   AtomFTYP *ftyp = NULL;
2086 
2087   GST_DEBUG_OBJECT (qtmux, "Preparing ftyp and possible prefix atom");
2088 
2089   /* init and send context and ftyp based on current property state */
2090   gst_qt_mux_map_format_to_header (qtmux_klass->format, &prefix, &major,
2091       &version, &comp, qtmux->moov, qtmux->longest_chunk,
2092       qtmux->fast_start_file != NULL);
2093   ftyp = atom_ftyp_new (qtmux->context, major, version, comp);
2094   if (comp)
2095     g_list_free (comp);
2096   if (prefix) {
2097     if (p_prefix)
2098       *p_prefix = prefix;
2099     else
2100       gst_buffer_unref (prefix);
2101   }
2102   *p_ftyp = ftyp;
2103 }
2104 
2105 static GstFlowReturn
gst_qt_mux_prepare_and_send_ftyp(GstQTMux * qtmux)2106 gst_qt_mux_prepare_and_send_ftyp (GstQTMux * qtmux)
2107 {
2108   GstFlowReturn ret = GST_FLOW_OK;
2109   GstBuffer *prefix = NULL;
2110 
2111   GST_DEBUG_OBJECT (qtmux, "Preparing to send ftyp atom");
2112 
2113   /* init and send context and ftyp based on current property state */
2114   if (qtmux->ftyp) {
2115     atom_ftyp_free (qtmux->ftyp);
2116     qtmux->ftyp = NULL;
2117   }
2118   gst_qt_mux_prepare_ftyp (qtmux, &qtmux->ftyp, &prefix);
2119   if (prefix) {
2120     ret = gst_qt_mux_send_buffer (qtmux, prefix, &qtmux->header_size, FALSE);
2121     if (ret != GST_FLOW_OK)
2122       return ret;
2123   }
2124   return gst_qt_mux_send_ftyp (qtmux, &qtmux->header_size);
2125 }
2126 
2127 static void
gst_qt_mux_set_header_on_caps(GstQTMux * mux,GstBuffer * buf)2128 gst_qt_mux_set_header_on_caps (GstQTMux * mux, GstBuffer * buf)
2129 {
2130   GstStructure *structure;
2131   GValue array = { 0 };
2132   GValue value = { 0 };
2133   GstCaps *caps, *tcaps;
2134 
2135   tcaps = gst_pad_get_current_caps (mux->srcpad);
2136   caps = gst_caps_copy (tcaps);
2137   gst_caps_unref (tcaps);
2138 
2139   structure = gst_caps_get_structure (caps, 0);
2140 
2141   g_value_init (&array, GST_TYPE_ARRAY);
2142 
2143   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2144   g_value_init (&value, GST_TYPE_BUFFER);
2145   gst_value_take_buffer (&value, gst_buffer_ref (buf));
2146   gst_value_array_append_value (&array, &value);
2147   g_value_unset (&value);
2148 
2149   gst_structure_set_value (structure, "streamheader", &array);
2150   g_value_unset (&array);
2151   gst_pad_set_caps (mux->srcpad, caps);
2152   gst_caps_unref (caps);
2153 }
2154 
2155 /*
2156  * Write out a free space atom. The offset is adjusted by the full
2157  * size, but a smaller buffer is sent
2158  */
2159 static GstFlowReturn
gst_qt_mux_send_free_atom(GstQTMux * qtmux,guint64 * off,guint32 size,gboolean fsync_after)2160 gst_qt_mux_send_free_atom (GstQTMux * qtmux, guint64 * off, guint32 size,
2161     gboolean fsync_after)
2162 {
2163   Atom *node_header;
2164   GstBuffer *buf;
2165   guint8 *data = NULL;
2166   guint64 offset = 0, bsize = 0;
2167   GstFlowReturn ret;
2168 
2169   GST_DEBUG_OBJECT (qtmux, "Sending free atom header of size %u", size);
2170 
2171   /* We can't make a free space atom smaller than the header */
2172   if (size < 8)
2173     goto too_small;
2174 
2175   node_header = g_malloc0 (sizeof (Atom));
2176   node_header->type = FOURCC_free;
2177   node_header->size = size;
2178 
2179   bsize = offset = 0;
2180   if (atom_copy_data (node_header, &data, &bsize, &offset) == 0)
2181     goto serialize_error;
2182 
2183   buf = _gst_buffer_new_take_data (data, offset);
2184   g_free (node_header);
2185 
2186   if (fsync_after)
2187     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2188 
2189   GST_LOG_OBJECT (qtmux, "Pushing free atom");
2190   ret = gst_qt_mux_send_buffer (qtmux, buf, off, FALSE);
2191 
2192   if (off) {
2193     GstSegment segment;
2194 
2195     *off += size - 8;
2196 
2197     /* Make sure downstream position ends up at the end of this free box */
2198     gst_segment_init (&segment, GST_FORMAT_BYTES);
2199     segment.start = *off;
2200     gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
2201   }
2202 
2203   return ret;
2204 
2205   /* ERRORS */
2206 too_small:
2207   {
2208     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2209         ("Not enough free reserved space"));
2210     return GST_FLOW_ERROR;
2211   }
2212 serialize_error:
2213   {
2214     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
2215         ("Failed to serialize mdat"));
2216     g_free (node_header);
2217     return GST_FLOW_ERROR;
2218   }
2219 }
2220 
2221 static void
gst_qt_mux_configure_moov(GstQTMux * qtmux)2222 gst_qt_mux_configure_moov (GstQTMux * qtmux)
2223 {
2224   gboolean fragmented = FALSE;
2225   guint32 timescale;
2226 
2227   GST_OBJECT_LOCK (qtmux);
2228   timescale = qtmux->timescale;
2229   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED ||
2230       qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE)
2231     fragmented = TRUE;
2232   GST_OBJECT_UNLOCK (qtmux);
2233 
2234   /* inform lower layers of our property wishes, and determine duration.
2235    * Let moov take care of this using its list of traks;
2236    * so that released pads are also included */
2237   GST_DEBUG_OBJECT (qtmux, "Updating timescale to %" G_GUINT32_FORMAT,
2238       timescale);
2239   atom_moov_update_timescale (qtmux->moov, timescale);
2240   atom_moov_set_fragmented (qtmux->moov, fragmented);
2241 
2242   atom_moov_update_duration (qtmux->moov);
2243 }
2244 
2245 static GstFlowReturn
gst_qt_mux_send_moov(GstQTMux * qtmux,guint64 * _offset,guint64 padded_moov_size,gboolean mind_fast,gboolean fsync_after)2246 gst_qt_mux_send_moov (GstQTMux * qtmux, guint64 * _offset,
2247     guint64 padded_moov_size, gboolean mind_fast, gboolean fsync_after)
2248 {
2249   guint64 offset = 0, size = 0;
2250   guint8 *data;
2251   GstBuffer *buf;
2252   GstFlowReturn ret = GST_FLOW_OK;
2253   GSList *walk;
2254   guint64 current_time = atoms_get_current_qt_time ();
2255 
2256   /* update modification times */
2257   qtmux->moov->mvhd.time_info.modification_time = current_time;
2258   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2259     GstCollectData *cdata = (GstCollectData *) walk->data;
2260     GstQTPad *qtpad = (GstQTPad *) cdata;
2261 
2262     qtpad->trak->mdia.mdhd.time_info.modification_time = current_time;
2263     qtpad->trak->tkhd.modification_time = current_time;
2264   }
2265 
2266   /* serialize moov */
2267   offset = size = 0;
2268   data = NULL;
2269   GST_LOG_OBJECT (qtmux, "Copying movie header into buffer");
2270   if (!atom_moov_copy_data (qtmux->moov, &data, &size, &offset))
2271     goto serialize_error;
2272   qtmux->last_moov_size = offset;
2273 
2274   /* Check we have enough reserved space for this and a Free atom */
2275   if (padded_moov_size > 0 && offset + 8 > padded_moov_size)
2276     goto too_small_reserved;
2277   buf = _gst_buffer_new_take_data (data, offset);
2278   GST_DEBUG_OBJECT (qtmux, "Pushing moov atoms");
2279 
2280   /* If at EOS, this is the final moov, put in the streamheader
2281    * (apparently used by a flumotion util) */
2282   if (qtmux->state == GST_QT_MUX_STATE_EOS)
2283     gst_qt_mux_set_header_on_caps (qtmux, buf);
2284 
2285   if (fsync_after)
2286     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_SYNC_AFTER);
2287   ret = gst_qt_mux_send_buffer (qtmux, buf, _offset, mind_fast);
2288 
2289   /* Write out a free atom if needed */
2290   if (ret == GST_FLOW_OK && offset < padded_moov_size) {
2291     GST_LOG_OBJECT (qtmux, "Writing out free atom of size %u",
2292         (guint32) (padded_moov_size - offset));
2293     ret =
2294         gst_qt_mux_send_free_atom (qtmux, _offset, padded_moov_size - offset,
2295         fsync_after);
2296   }
2297 
2298   return ret;
2299 too_small_reserved:
2300   {
2301     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2302         ("Not enough free reserved header space"),
2303         ("Needed %" G_GUINT64_FORMAT " bytes, reserved %" G_GUINT64_FORMAT,
2304             offset, padded_moov_size));
2305     return GST_FLOW_ERROR;
2306   }
2307 serialize_error:
2308   {
2309     g_free (data);
2310     return GST_FLOW_ERROR;
2311   }
2312 }
2313 
2314 /* either calculates size of extra atoms or pushes them */
2315 static GstFlowReturn
gst_qt_mux_send_extra_atoms(GstQTMux * qtmux,gboolean send,guint64 * offset,gboolean mind_fast)2316 gst_qt_mux_send_extra_atoms (GstQTMux * qtmux, gboolean send, guint64 * offset,
2317     gboolean mind_fast)
2318 {
2319   GSList *walk;
2320   guint64 loffset = 0, size = 0;
2321   guint8 *data;
2322   GstFlowReturn ret = GST_FLOW_OK;
2323 
2324   for (walk = qtmux->extra_atoms; walk; walk = g_slist_next (walk)) {
2325     AtomInfo *ainfo = (AtomInfo *) walk->data;
2326 
2327     loffset = size = 0;
2328     data = NULL;
2329     if (!ainfo->copy_data_func (ainfo->atom,
2330             send ? &data : NULL, &size, &loffset))
2331       goto serialize_error;
2332 
2333     if (send) {
2334       GstBuffer *buf;
2335 
2336       GST_DEBUG_OBJECT (qtmux,
2337           "Pushing extra top-level atom %" GST_FOURCC_FORMAT,
2338           GST_FOURCC_ARGS (ainfo->atom->type));
2339       buf = _gst_buffer_new_take_data (data, loffset);
2340       ret = gst_qt_mux_send_buffer (qtmux, buf, offset, FALSE);
2341       if (ret != GST_FLOW_OK)
2342         break;
2343     } else {
2344       if (offset)
2345         *offset += loffset;
2346     }
2347   }
2348 
2349   return ret;
2350 
2351 serialize_error:
2352   {
2353     g_free (data);
2354     return GST_FLOW_ERROR;
2355   }
2356 }
2357 
2358 static gboolean
gst_qt_mux_downstream_is_seekable(GstQTMux * qtmux)2359 gst_qt_mux_downstream_is_seekable (GstQTMux * qtmux)
2360 {
2361   gboolean seekable = FALSE;
2362   GstQuery *query = gst_query_new_seeking (GST_FORMAT_BYTES);
2363 
2364   if (gst_pad_peer_query (qtmux->srcpad, query)) {
2365     gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
2366     GST_INFO_OBJECT (qtmux, "downstream is %sseekable", seekable ? "" : "not ");
2367   } else {
2368     /* have to assume seeking is not supported if query not handled downstream */
2369     GST_WARNING_OBJECT (qtmux, "downstream did not handle seeking query");
2370     seekable = FALSE;
2371   }
2372   gst_query_unref (query);
2373 
2374   return seekable;
2375 }
2376 
2377 static void
gst_qt_mux_prepare_moov_recovery(GstQTMux * qtmux)2378 gst_qt_mux_prepare_moov_recovery (GstQTMux * qtmux)
2379 {
2380   GSList *walk;
2381   gboolean fail = FALSE;
2382   AtomFTYP *ftyp = NULL;
2383   GstBuffer *prefix = NULL;
2384 
2385   GST_DEBUG_OBJECT (qtmux, "Opening moov recovery file: %s",
2386       qtmux->moov_recov_file_path);
2387 
2388   qtmux->moov_recov_file = g_fopen (qtmux->moov_recov_file_path, "wb+");
2389   if (qtmux->moov_recov_file == NULL) {
2390     GST_WARNING_OBJECT (qtmux, "Failed to open moov recovery file in %s",
2391         qtmux->moov_recov_file_path);
2392     return;
2393   }
2394 
2395   gst_qt_mux_prepare_ftyp (qtmux, &ftyp, &prefix);
2396 
2397   if (!atoms_recov_write_headers (qtmux->moov_recov_file, ftyp, prefix,
2398           qtmux->moov, qtmux->timescale, g_slist_length (qtmux->sinkpads))) {
2399     GST_WARNING_OBJECT (qtmux, "Failed to write moov recovery file " "headers");
2400     goto fail;
2401   }
2402 
2403   atom_ftyp_free (ftyp);
2404   if (prefix)
2405     gst_buffer_unref (prefix);
2406 
2407   for (walk = qtmux->sinkpads; walk && !fail; walk = g_slist_next (walk)) {
2408     GstCollectData *cdata = (GstCollectData *) walk->data;
2409     GstQTPad *qpad = (GstQTPad *) cdata;
2410     /* write info for each stream */
2411     fail = atoms_recov_write_trak_info (qtmux->moov_recov_file, qpad->trak);
2412     if (fail) {
2413       GST_WARNING_OBJECT (qtmux, "Failed to write trak info to recovery "
2414           "file");
2415       break;
2416     }
2417   }
2418 
2419   return;
2420 
2421 fail:
2422   /* cleanup */
2423   fclose (qtmux->moov_recov_file);
2424   qtmux->moov_recov_file = NULL;
2425 }
2426 
2427 static guint64
prefill_get_block_index(GstQTMux * qtmux,GstQTPad * qpad)2428 prefill_get_block_index (GstQTMux * qtmux, GstQTPad * qpad)
2429 {
2430   switch (qpad->fourcc) {
2431     case FOURCC_apch:
2432     case FOURCC_apcn:
2433     case FOURCC_apcs:
2434     case FOURCC_apco:
2435     case FOURCC_ap4h:
2436     case FOURCC_ap4x:
2437     case FOURCC_c608:
2438     case FOURCC_c708:
2439       return qpad->sample_offset;
2440     case FOURCC_sowt:
2441     case FOURCC_twos:
2442       return gst_util_uint64_scale_ceil (qpad->sample_offset,
2443           qpad->expected_sample_duration_n,
2444           qpad->expected_sample_duration_d *
2445           atom_trak_get_timescale (qpad->trak));
2446     default:
2447       return -1;
2448   }
2449 }
2450 
2451 static guint
prefill_get_sample_size(GstQTMux * qtmux,GstQTPad * qpad)2452 prefill_get_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2453 {
2454   switch (qpad->fourcc) {
2455     case FOURCC_apch:
2456       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2457         return 300000;
2458       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2459         return 350000;
2460       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2461         return 525000;
2462       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2463         return 1050000;
2464       } else {
2465         return 4150000;
2466       }
2467       break;
2468     case FOURCC_apcn:
2469       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2470         return 200000;
2471       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2472         return 250000;
2473       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2474         return 350000;
2475       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2476         return 700000;
2477       } else {
2478         return 2800000;
2479       }
2480       break;
2481     case FOURCC_apcs:
2482       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2483         return 150000;
2484       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2485         return 200000;
2486       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2487         return 250000;
2488       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2489         return 500000;
2490       } else {
2491         return 2800000;
2492       }
2493       break;
2494     case FOURCC_apco:
2495       if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 480) {
2496         return 80000;
2497       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 576) {
2498         return 100000;
2499       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 720) {
2500         return 150000;
2501       } else if (((SampleTableEntryMP4V *) qpad->trak_ste)->height <= 1080) {
2502         return 250000;
2503       } else {
2504         return 900000;
2505       }
2506       break;
2507     case FOURCC_c608:
2508       /* We always write both cdat and cdt2 atom in prefill mode */
2509       return 20;
2510     case FOURCC_c708:
2511       /* We're cheating a bit by always allocating 256 bytes plus 8 bytes for the atom header
2512        * even if we use less  */
2513       return 256 + 8;
2514     case FOURCC_sowt:
2515     case FOURCC_twos:{
2516       guint64 block_idx;
2517       guint64 next_sample_offset;
2518 
2519       block_idx = prefill_get_block_index (qtmux, qpad);
2520       next_sample_offset =
2521           gst_util_uint64_scale (block_idx + 1,
2522           qpad->expected_sample_duration_d *
2523           atom_trak_get_timescale (qpad->trak),
2524           qpad->expected_sample_duration_n);
2525 
2526       return (next_sample_offset - qpad->sample_offset) * qpad->sample_size;
2527     }
2528     case FOURCC_ap4h:
2529     case FOURCC_ap4x:
2530     default:
2531       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2532       return -1;
2533   }
2534 
2535   return -1;
2536 }
2537 
2538 static GstClockTime
prefill_get_next_timestamp(GstQTMux * qtmux,GstQTPad * qpad)2539 prefill_get_next_timestamp (GstQTMux * qtmux, GstQTPad * qpad)
2540 {
2541   switch (qpad->fourcc) {
2542     case FOURCC_apch:
2543     case FOURCC_apcn:
2544     case FOURCC_apcs:
2545     case FOURCC_apco:
2546     case FOURCC_ap4h:
2547     case FOURCC_ap4x:
2548     case FOURCC_c608:
2549     case FOURCC_c708:
2550       return gst_util_uint64_scale (qpad->sample_offset + 1,
2551           qpad->expected_sample_duration_d * GST_SECOND,
2552           qpad->expected_sample_duration_n);
2553     case FOURCC_sowt:
2554     case FOURCC_twos:{
2555       guint64 block_idx;
2556       guint64 next_sample_offset;
2557 
2558       block_idx = prefill_get_block_index (qtmux, qpad);
2559       next_sample_offset =
2560           gst_util_uint64_scale (block_idx + 1,
2561           qpad->expected_sample_duration_d *
2562           atom_trak_get_timescale (qpad->trak),
2563           qpad->expected_sample_duration_n);
2564 
2565       return gst_util_uint64_scale (next_sample_offset, GST_SECOND,
2566           atom_trak_get_timescale (qpad->trak));
2567     }
2568     default:
2569       GST_ERROR_OBJECT (qtmux, "unsupported codec for pre-filling");
2570       return -1;
2571   }
2572 
2573   return -1;
2574 }
2575 
2576 static GstBuffer *
prefill_raw_audio_prepare_buf_func(GstQTPad * qtpad,GstBuffer * buf,GstQTMux * qtmux)2577 prefill_raw_audio_prepare_buf_func (GstQTPad * qtpad, GstBuffer * buf,
2578     GstQTMux * qtmux)
2579 {
2580   guint64 block_idx;
2581   guint64 nsamples;
2582   GstClockTime input_timestamp;
2583   guint64 input_timestamp_distance;
2584 
2585   if (buf)
2586     gst_adapter_push (qtpad->raw_audio_adapter, buf);
2587 
2588   block_idx = gst_util_uint64_scale_ceil (qtpad->raw_audio_adapter_offset,
2589       qtpad->expected_sample_duration_n,
2590       qtpad->expected_sample_duration_d *
2591       atom_trak_get_timescale (qtpad->trak));
2592   nsamples =
2593       gst_util_uint64_scale (block_idx + 1,
2594       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2595       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2596 
2597   if ((!GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2598               GST_COLLECT_PADS_STATE_EOS)
2599           && gst_adapter_available (qtpad->raw_audio_adapter) <
2600           nsamples * qtpad->sample_size)
2601       || gst_adapter_available (qtpad->raw_audio_adapter) == 0) {
2602     return NULL;
2603   }
2604 
2605   input_timestamp =
2606       gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2607       &input_timestamp_distance);
2608   if (input_timestamp != GST_CLOCK_TIME_NONE)
2609     input_timestamp +=
2610         gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2611         qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2612 
2613   buf =
2614       gst_adapter_take_buffer (qtpad->raw_audio_adapter,
2615       !GST_COLLECT_PADS_STATE_IS_SET (&qtpad->collect,
2616           GST_COLLECT_PADS_STATE_EOS) ? nsamples *
2617       qtpad->sample_size : gst_adapter_available (qtpad->raw_audio_adapter));
2618   GST_BUFFER_PTS (buf) = input_timestamp;
2619   GST_BUFFER_DTS (buf) = GST_CLOCK_TIME_NONE;
2620   GST_BUFFER_DURATION (buf) = GST_CLOCK_TIME_NONE;
2621 
2622   qtpad->raw_audio_adapter_offset += nsamples;
2623 
2624   /* Check if we have yet another block of raw audio in the adapter */
2625   nsamples =
2626       gst_util_uint64_scale (block_idx + 2,
2627       qtpad->expected_sample_duration_d * atom_trak_get_timescale (qtpad->trak),
2628       qtpad->expected_sample_duration_n) - qtpad->raw_audio_adapter_offset;
2629   if (gst_adapter_available (qtpad->raw_audio_adapter) >=
2630       nsamples * qtpad->sample_size) {
2631     input_timestamp =
2632         gst_adapter_prev_pts (qtpad->raw_audio_adapter,
2633         &input_timestamp_distance);
2634     if (input_timestamp != GST_CLOCK_TIME_NONE)
2635       input_timestamp +=
2636           gst_util_uint64_scale (input_timestamp_distance, GST_SECOND,
2637           qtpad->sample_size * atom_trak_get_timescale (qtpad->trak));
2638     qtpad->raw_audio_adapter_pts = input_timestamp;
2639   } else {
2640     qtpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2641   }
2642 
2643   return buf;
2644 }
2645 
2646 static void
find_video_sample_duration(GstQTMux * qtmux,guint * dur_n,guint * dur_d)2647 find_video_sample_duration (GstQTMux * qtmux, guint * dur_n, guint * dur_d)
2648 {
2649   GSList *walk;
2650 
2651   /* Find the (first) video track and assume that we have to output
2652    * in that size */
2653   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2654     GstCollectData *cdata = (GstCollectData *) walk->data;
2655     GstQTPad *tmp_qpad = (GstQTPad *) cdata;
2656 
2657     if (tmp_qpad->trak->is_video) {
2658       *dur_n = tmp_qpad->expected_sample_duration_n;
2659       *dur_d = tmp_qpad->expected_sample_duration_d;
2660       break;
2661     }
2662   }
2663 
2664   if (walk == NULL) {
2665     GST_INFO_OBJECT (qtmux,
2666         "Found no video framerate, using 40ms audio buffers");
2667     *dur_n = 25;
2668     *dur_d = 1;
2669   }
2670 }
2671 
2672 /* Called when all pads are prerolled to adjust and  */
2673 static gboolean
prefill_update_sample_size(GstQTMux * qtmux,GstQTPad * qpad)2674 prefill_update_sample_size (GstQTMux * qtmux, GstQTPad * qpad)
2675 {
2676   switch (qpad->fourcc) {
2677     case FOURCC_apch:
2678     case FOURCC_apcn:
2679     case FOURCC_apcs:
2680     case FOURCC_apco:
2681     case FOURCC_ap4h:
2682     case FOURCC_ap4x:
2683     {
2684       guint sample_size = prefill_get_sample_size (qtmux, qpad);
2685       atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2686       return TRUE;
2687     }
2688     case FOURCC_c608:
2689     case FOURCC_c708:
2690     {
2691       guint sample_size = prefill_get_sample_size (qtmux, qpad);
2692       /* We need a "valid" duration */
2693       find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2694           &qpad->expected_sample_duration_d);
2695       atom_trak_set_constant_size_samples (qpad->trak, sample_size);
2696       return TRUE;
2697     }
2698     case FOURCC_sowt:
2699     case FOURCC_twos:{
2700       find_video_sample_duration (qtmux, &qpad->expected_sample_duration_n,
2701           &qpad->expected_sample_duration_d);
2702       /* Set a prepare_buf_func that ensures this */
2703       qpad->prepare_buf_func = prefill_raw_audio_prepare_buf_func;
2704       qpad->raw_audio_adapter = gst_adapter_new ();
2705       qpad->raw_audio_adapter_offset = 0;
2706       qpad->raw_audio_adapter_pts = GST_CLOCK_TIME_NONE;
2707 
2708       return TRUE;
2709     }
2710     default:
2711       return TRUE;
2712   }
2713 }
2714 
2715 /* Only called at startup when doing the "fake" iteration of all tracks in order
2716  * to prefill the sample tables in the header.  */
2717 static GstQTPad *
find_best_pad_prefill_start(GstQTMux * qtmux)2718 find_best_pad_prefill_start (GstQTMux * qtmux)
2719 {
2720   GSList *walk;
2721   GstQTPad *best_pad = NULL;
2722 
2723   /* If interleave limits have been specified and the current pad is within
2724    * those interleave limits, pick that one, otherwise let's try to figure out
2725    * the next best one. */
2726   if (qtmux->current_pad &&
2727       (qtmux->interleave_bytes != 0 || qtmux->interleave_time != 0) &&
2728       (qtmux->interleave_bytes == 0
2729           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
2730       && (qtmux->interleave_time == 0
2731           || qtmux->current_chunk_duration <= qtmux->interleave_time)
2732       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
2733       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
2734 
2735     if (qtmux->current_pad->total_duration < qtmux->reserved_max_duration) {
2736       best_pad = qtmux->current_pad;
2737     }
2738   } else if (qtmux->collect->data->next) {
2739     /* Attempt to try another pad if we have one. Otherwise use the only pad
2740      * present */
2741     best_pad = qtmux->current_pad = NULL;
2742   }
2743 
2744   /* The next best pad is the one which has the lowest timestamp and hasn't
2745    * exceeded the reserved max duration */
2746   if (!best_pad) {
2747     GstClockTime best_time = GST_CLOCK_TIME_NONE;
2748 
2749     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2750       GstCollectData *cdata = (GstCollectData *) walk->data;
2751       GstQTPad *qtpad = (GstQTPad *) cdata;
2752       GstClockTime timestamp;
2753 
2754       if (qtpad->total_duration >= qtmux->reserved_max_duration)
2755         continue;
2756 
2757       timestamp = qtpad->total_duration;
2758 
2759       if (best_pad == NULL ||
2760           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
2761         best_pad = qtpad;
2762         best_time = timestamp;
2763       }
2764     }
2765   }
2766 
2767   return best_pad;
2768 }
2769 
2770 /* Called when starting the file in prefill_mode to figure out all the entries
2771  * of the header based on the input stream and reserved maximum duration.
2772  *
2773  * The _actual_ header (i.e. with the proper duration and trimmed sample tables)
2774  * will be updated and written on EOS. */
2775 static gboolean
gst_qt_mux_prefill_samples(GstQTMux * qtmux)2776 gst_qt_mux_prefill_samples (GstQTMux * qtmux)
2777 {
2778   GstQTPad *qpad;
2779   GSList *walk;
2780   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2781 
2782   /* Update expected sample sizes/durations as needed, this is for raw
2783    * audio where samples are actual audio samples. */
2784   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2785     GstCollectData *cdata = (GstCollectData *) walk->data;
2786     GstQTPad *qpad = (GstQTPad *) cdata;
2787 
2788     if (!prefill_update_sample_size (qtmux, qpad))
2789       return FALSE;
2790   }
2791 
2792   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT) {
2793     /* For the first sample check/update timecode as needed. We do that before
2794      * all actual samples as the code in gst_qt_mux_add_buffer() does it with
2795      * initial buffer directly, not with last_buf */
2796     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
2797       GstCollectData *cdata = (GstCollectData *) walk->data;
2798       GstQTPad *qpad = (GstQTPad *) cdata;
2799       GstBuffer *buffer =
2800           gst_collect_pads_peek (qtmux->collect, (GstCollectData *) qpad);
2801       GstVideoTimeCodeMeta *tc_meta;
2802 
2803       if (buffer && (tc_meta = gst_buffer_get_video_time_code_meta (buffer))
2804           && qpad->trak->is_video) {
2805         GstVideoTimeCode *tc = &tc_meta->tc;
2806 
2807         qpad->tc_trak = atom_trak_new (qtmux->context);
2808         atom_moov_add_trak (qtmux->moov, qpad->tc_trak);
2809 
2810         qpad->trak->tref = atom_tref_new (FOURCC_tmcd);
2811         atom_tref_add_entry (qpad->trak->tref, qpad->tc_trak->tkhd.track_ID);
2812 
2813         atom_trak_set_timecode_type (qpad->tc_trak, qtmux->context,
2814             qpad->trak->mdia.mdhd.time_info.timescale, tc);
2815 
2816         atom_trak_add_samples (qpad->tc_trak, 1, 1, 4,
2817             qtmux->mdat_size, FALSE, 0);
2818 
2819         qpad->tc_pos = qtmux->mdat_size;
2820         qpad->first_tc = gst_video_time_code_copy (tc);
2821         qpad->first_pts = GST_BUFFER_PTS (buffer);
2822 
2823         qtmux->current_chunk_offset = -1;
2824         qtmux->current_chunk_size = 0;
2825         qtmux->current_chunk_duration = 0;
2826         qtmux->mdat_size += 4;
2827       }
2828       if (buffer)
2829         gst_buffer_unref (buffer);
2830     }
2831   }
2832 
2833   while ((qpad = find_best_pad_prefill_start (qtmux))) {
2834     GstClockTime timestamp, next_timestamp, duration;
2835     guint nsamples, sample_size;
2836     guint64 chunk_offset;
2837     gint64 scaled_duration;
2838     gint64 pts_offset = 0;
2839     gboolean sync = FALSE;
2840     TrakBufferEntryInfo sample_entry;
2841 
2842     sample_size = prefill_get_sample_size (qtmux, qpad);
2843 
2844     if (sample_size == -1) {
2845       return FALSE;
2846     }
2847 
2848     if (!qpad->samples)
2849       qpad->samples = g_array_new (FALSE, FALSE, sizeof (TrakBufferEntryInfo));
2850 
2851     timestamp = qpad->total_duration;
2852     next_timestamp = prefill_get_next_timestamp (qtmux, qpad);
2853     duration = next_timestamp - timestamp;
2854 
2855     if (qpad->first_ts == GST_CLOCK_TIME_NONE)
2856       qpad->first_ts = timestamp;
2857     if (qpad->first_dts == GST_CLOCK_TIME_NONE)
2858       qpad->first_dts = timestamp;
2859 
2860     if (qtmux->current_pad != qpad || qtmux->current_chunk_offset == -1) {
2861       qtmux->current_pad = qpad;
2862       if (qtmux->current_chunk_offset == -1)
2863         qtmux->current_chunk_offset = qtmux->mdat_size;
2864       else
2865         qtmux->current_chunk_offset += qtmux->current_chunk_size;
2866       qtmux->current_chunk_size = 0;
2867       qtmux->current_chunk_duration = 0;
2868     }
2869     if (qpad->sample_size)
2870       nsamples = sample_size / qpad->sample_size;
2871     else
2872       nsamples = 1;
2873     qpad->last_dts = timestamp;
2874     scaled_duration = gst_util_uint64_scale_round (timestamp + duration,
2875         atom_trak_get_timescale (qpad->trak),
2876         GST_SECOND) - gst_util_uint64_scale_round (timestamp,
2877         atom_trak_get_timescale (qpad->trak), GST_SECOND);
2878 
2879     qtmux->current_chunk_size += sample_size;
2880     qtmux->current_chunk_duration += duration;
2881     qpad->total_bytes += sample_size;
2882 
2883     chunk_offset = qtmux->current_chunk_offset;
2884 
2885     /* I-frame only, no frame reordering */
2886     sync = FALSE;
2887     pts_offset = 0;
2888 
2889     if (qtmux->current_chunk_duration > qtmux->longest_chunk
2890         || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk)) {
2891       qtmux->longest_chunk = qtmux->current_chunk_duration;
2892     }
2893 
2894     sample_entry.track_id = qpad->trak->tkhd.track_ID;
2895     sample_entry.nsamples = nsamples;
2896     sample_entry.delta = scaled_duration / nsamples;
2897     sample_entry.size = sample_size / nsamples;
2898     sample_entry.chunk_offset = chunk_offset;
2899     sample_entry.pts_offset = pts_offset;
2900     sample_entry.sync = sync;
2901     sample_entry.do_pts = TRUE;
2902     g_array_append_val (qpad->samples, sample_entry);
2903     atom_trak_add_samples (qpad->trak, nsamples, scaled_duration / nsamples,
2904         sample_size / nsamples, chunk_offset, sync, pts_offset);
2905 
2906     qpad->total_duration = next_timestamp;
2907     qtmux->mdat_size += sample_size;
2908     qpad->sample_offset += nsamples;
2909   }
2910 
2911   return TRUE;
2912 }
2913 
2914 static GstFlowReturn
gst_qt_mux_start_file(GstQTMux * qtmux)2915 gst_qt_mux_start_file (GstQTMux * qtmux)
2916 {
2917   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
2918   GstFlowReturn ret = GST_FLOW_OK;
2919   GstCaps *caps;
2920   GstSegment segment;
2921   gchar s_id[32];
2922   GstClockTime reserved_max_duration;
2923   guint reserved_bytes_per_sec_per_trak;
2924   GSList *walk;
2925 
2926   GST_DEBUG_OBJECT (qtmux, "starting file");
2927 
2928   GST_OBJECT_LOCK (qtmux);
2929   reserved_max_duration = qtmux->reserved_max_duration;
2930   reserved_bytes_per_sec_per_trak = qtmux->reserved_bytes_per_sec_per_trak;
2931   GST_OBJECT_UNLOCK (qtmux);
2932 
2933   /* stream-start (FIXME: create id based on input ids) */
2934   g_snprintf (s_id, sizeof (s_id), "qtmux-%08x", g_random_int ());
2935   gst_pad_push_event (qtmux->srcpad, gst_event_new_stream_start (s_id));
2936 
2937   caps = gst_caps_copy (gst_pad_get_pad_template_caps (qtmux->srcpad));
2938   /* qtmux has structure with and without variant, remove all but the first */
2939   while (gst_caps_get_size (caps) > 1)
2940     gst_caps_remove_structure (caps, 1);
2941   gst_pad_set_caps (qtmux->srcpad, caps);
2942   gst_caps_unref (caps);
2943 
2944   /* Default is 'normal' mode */
2945   qtmux->mux_mode = GST_QT_MUX_MODE_MOOV_AT_END;
2946 
2947   /* Require a sensible fragment duration when muxing
2948    * using the ISML muxer */
2949   if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML &&
2950       qtmux->fragment_duration == 0)
2951     goto invalid_isml;
2952 
2953   if (qtmux->fragment_duration > 0) {
2954     if (qtmux->streamable)
2955       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE;
2956     else
2957       qtmux->mux_mode = GST_QT_MUX_MODE_FRAGMENTED;
2958   } else if (qtmux->fast_start) {
2959     qtmux->mux_mode = GST_QT_MUX_MODE_FAST_START;
2960   } else if (reserved_max_duration != GST_CLOCK_TIME_NONE) {
2961     if (qtmux->reserved_prefill)
2962       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL;
2963     else
2964       qtmux->mux_mode = GST_QT_MUX_MODE_ROBUST_RECORDING;
2965   }
2966 
2967   switch (qtmux->mux_mode) {
2968     case GST_QT_MUX_MODE_MOOV_AT_END:
2969     case GST_QT_MUX_MODE_ROBUST_RECORDING:
2970       /* We have to be able to seek to rewrite the mdat header, or any
2971        * moov atom we write will not be visible in the file, because an
2972        * MDAT with 0 as the size covers the rest of the file. A file
2973        * with no moov is not playable, so error out now. */
2974       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2975         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
2976             ("Downstream is not seekable - will not be able to create a playable file"),
2977             (NULL));
2978         return GST_FLOW_ERROR;
2979       }
2980       if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
2981         GST_WARNING_OBJECT (qtmux,
2982             "Robust muxing requires reserved-moov-update-period to be set");
2983       }
2984       break;
2985     case GST_QT_MUX_MODE_FAST_START:
2986     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
2987       break;                    /* Don't need seekability, ignore */
2988     case GST_QT_MUX_MODE_FRAGMENTED:
2989       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2990         GST_WARNING_OBJECT (qtmux, "downstream is not seekable, but "
2991             "streamable=false. Will ignore that and create streamable output "
2992             "instead");
2993         qtmux->streamable = TRUE;
2994         g_object_notify (G_OBJECT (qtmux), "streamable");
2995       }
2996       break;
2997     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
2998       if (!gst_qt_mux_downstream_is_seekable (qtmux)) {
2999         GST_WARNING_OBJECT (qtmux,
3000             "downstream is not seekable, will not be able "
3001             "to trim samples table at the end if less than reserved-duration is "
3002             "recorded");
3003       }
3004       break;
3005   }
3006 
3007   /* let downstream know we think in BYTES and expect to do seeking later on */
3008   gst_segment_init (&segment, GST_FORMAT_BYTES);
3009   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3010 
3011   GST_OBJECT_LOCK (qtmux);
3012 
3013   if (qtmux->timescale == 0) {
3014     guint32 suggested_timescale = 0;
3015     GSList *walk;
3016 
3017     /* Calculate a reasonable timescale for the moov:
3018      * If there is video, it is the biggest video track timescale or an even
3019      * multiple of it if it's smaller than 1800.
3020      * Otherwise it is 1800 */
3021     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3022       GstCollectData *cdata = (GstCollectData *) walk->data;
3023       GstQTPad *qpad = (GstQTPad *) cdata;
3024 
3025       if (!qpad->trak)
3026         continue;
3027 
3028       /* not video */
3029       if (!qpad->trak->mdia.minf.vmhd)
3030         continue;
3031 
3032       suggested_timescale =
3033           MAX (qpad->trak->mdia.mdhd.time_info.timescale, suggested_timescale);
3034     }
3035 
3036     if (suggested_timescale == 0)
3037       suggested_timescale = 1800;
3038 
3039     while (suggested_timescale < 1800)
3040       suggested_timescale *= 2;
3041 
3042     qtmux->timescale = suggested_timescale;
3043   }
3044 
3045   /* Set width/height/timescale of any closed caption tracks to that of the
3046    * first video track */
3047   {
3048     guint video_width = 0, video_height = 0;
3049     guint32 video_timescale = 0;
3050     GSList *walk;
3051 
3052     for (walk = qtmux->sinkpads; walk; walk = g_slist_next (walk)) {
3053       GstCollectData *cdata = (GstCollectData *) walk->data;
3054       GstQTPad *qpad = (GstQTPad *) cdata;
3055 
3056       if (!qpad->trak)
3057         continue;
3058 
3059       /* Not closed caption */
3060       if (qpad->trak->mdia.hdlr.handler_type != FOURCC_clcp)
3061         continue;
3062 
3063       if (video_width == 0 || video_height == 0 || video_timescale == 0) {
3064         GSList *walk2;
3065 
3066         for (walk2 = qtmux->sinkpads; walk2; walk2 = g_slist_next (walk2)) {
3067           GstCollectData *cdata2 = (GstCollectData *) walk2->data;
3068           GstQTPad *qpad2 = (GstQTPad *) cdata2;
3069 
3070           if (!qpad2->trak)
3071             continue;
3072 
3073           /* not video */
3074           if (!qpad2->trak->mdia.minf.vmhd)
3075             continue;
3076 
3077           video_width = qpad2->trak->tkhd.width;
3078           video_height = qpad2->trak->tkhd.height;
3079           video_timescale = qpad2->trak->mdia.mdhd.time_info.timescale;
3080         }
3081       }
3082 
3083       qpad->trak->tkhd.width = video_width << 16;
3084       qpad->trak->tkhd.height = video_height << 16;
3085       qpad->trak->mdia.mdhd.time_info.timescale = video_timescale;
3086     }
3087   }
3088 
3089   /* initialize our moov recovery file */
3090   if (qtmux->moov_recov_file_path) {
3091     gst_qt_mux_prepare_moov_recovery (qtmux);
3092   }
3093 
3094   /* Make sure the first time we update the moov, we'll
3095    * include any tagsetter tags */
3096   qtmux->tags_changed = TRUE;
3097 
3098   GST_OBJECT_UNLOCK (qtmux);
3099 
3100   /*
3101    * send mdat header if already needed, and mark position for later update.
3102    * We don't send ftyp now if we are on fast start mode, because we can
3103    * better fine tune using the information we gather to create the whole moov
3104    * atom.
3105    */
3106   switch (qtmux->mux_mode) {
3107     case GST_QT_MUX_MODE_MOOV_AT_END:
3108       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3109       if (ret != GST_FLOW_OK)
3110         break;
3111 
3112       /* Store this as the mdat offset for later updating
3113        * when we write the moov */
3114       qtmux->mdat_pos = qtmux->header_size;
3115       /* extended atom in case we go over 4GB while writing and need
3116        * the full 64-bit atom */
3117       ret =
3118           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3119           FALSE);
3120       break;
3121     case GST_QT_MUX_MODE_ROBUST_RECORDING:
3122       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3123       if (ret != GST_FLOW_OK)
3124         break;
3125 
3126       /* Pad ftyp out to an 8-byte boundary before starting the moov
3127        * ping pong region. It should be well less than 1 disk sector,
3128        * unless there's a bajillion compatible types listed,
3129        * but let's be sure the free atom doesn't cross a sector
3130        * boundary anyway */
3131       if (qtmux->header_size % 8) {
3132         /* Extra 8 bytes for the padding free atom header */
3133         guint padding = (guint) (16 - (qtmux->header_size % 8));
3134         GST_LOG_OBJECT (qtmux, "Rounding ftyp by %u bytes", padding);
3135         ret =
3136             gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, padding,
3137             FALSE);
3138         if (ret != GST_FLOW_OK)
3139           return ret;
3140       }
3141 
3142       /* Store this as the moov offset for later updating.
3143        * We record mdat position below */
3144       qtmux->moov_pos = qtmux->header_size;
3145 
3146       /* Set up the initial 'ping' state of the ping-pong buffers */
3147       qtmux->reserved_moov_first_active = TRUE;
3148 
3149       gst_qt_mux_configure_moov (qtmux);
3150       gst_qt_mux_setup_metadata (qtmux);
3151       /* Empty free atom to begin, starting on an 8-byte boundary */
3152       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size, 8, FALSE);
3153       if (ret != GST_FLOW_OK)
3154         return ret;
3155       /* Moov header, not padded yet */
3156       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3157       if (ret != GST_FLOW_OK)
3158         return ret;
3159       /* The moov we just sent contains the 'base' size of the moov, before
3160        * we put in any time-dependent per-trak data. Use that to make
3161        * a good estimate of how much extra to reserve */
3162       /* Calculate how much space to reserve for our MOOV atom.
3163        * We actually reserve twice that, for ping-pong buffers */
3164       qtmux->base_moov_size = qtmux->last_moov_size;
3165       GST_LOG_OBJECT (qtmux, "Base moov size is %u before any indexes",
3166           qtmux->base_moov_size);
3167       qtmux->reserved_moov_size = qtmux->base_moov_size +
3168           gst_util_uint64_scale (reserved_max_duration,
3169           reserved_bytes_per_sec_per_trak *
3170           atom_moov_get_trak_count (qtmux->moov), GST_SECOND);
3171 
3172       /* Need space for at least 4 atom headers. More really, but
3173        * this as an absolute minimum */
3174       if (qtmux->reserved_moov_size < 4 * 8)
3175         goto reserved_moov_too_small;
3176 
3177       GST_DEBUG_OBJECT (qtmux, "reserving header area of size %u",
3178           2 * qtmux->reserved_moov_size + 16);
3179 
3180       GST_OBJECT_LOCK (qtmux);
3181       qtmux->reserved_duration_remaining =
3182           gst_util_uint64_scale (qtmux->reserved_moov_size -
3183           qtmux->base_moov_size, GST_SECOND,
3184           reserved_bytes_per_sec_per_trak *
3185           atom_moov_get_trak_count (qtmux->moov));
3186       GST_OBJECT_UNLOCK (qtmux);
3187 
3188       /* Now that we know how much reserved space is targetted,
3189        * output a free atom to fill the extra reserved */
3190       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3191           qtmux->reserved_moov_size - qtmux->base_moov_size, FALSE);
3192       if (ret != GST_FLOW_OK)
3193         return ret;
3194 
3195       /* Then a free atom containing 'pong' buffer, with an
3196        * extra 8 bytes to account for the free atom header itself */
3197       ret = gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3198           qtmux->reserved_moov_size + 8, FALSE);
3199       if (ret != GST_FLOW_OK)
3200         return ret;
3201 
3202       /* extra atoms go after the free/moov(s), before the mdat */
3203       ret =
3204           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3205       if (ret != GST_FLOW_OK)
3206         return ret;
3207 
3208       qtmux->mdat_pos = qtmux->header_size;
3209       /* extended atom in case we go over 4GB while writing and need
3210        * the full 64-bit atom */
3211       ret =
3212           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, 0, TRUE,
3213           FALSE);
3214       break;
3215     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:
3216       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3217       if (ret != GST_FLOW_OK)
3218         break;
3219 
3220       /* Store this as the moov offset for later updating.
3221        * We record mdat position below */
3222       qtmux->moov_pos = qtmux->header_size;
3223 
3224       if (!gst_qt_mux_prefill_samples (qtmux)) {
3225         GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3226             ("Unsupported codecs or configuration for prefill mode"), (NULL));
3227 
3228         return GST_FLOW_ERROR;
3229       }
3230 
3231       gst_qt_mux_update_global_statistics (qtmux);
3232       gst_qt_mux_configure_moov (qtmux);
3233       gst_qt_mux_update_edit_lists (qtmux);
3234       gst_qt_mux_setup_metadata (qtmux);
3235 
3236       /* Moov header with pre-filled samples */
3237       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3238       if (ret != GST_FLOW_OK)
3239         return ret;
3240 
3241       /* last_moov_size now contains the full size of the moov, moov_pos the
3242        * position. This allows us to rewrite it in the very end as needed */
3243       qtmux->reserved_moov_size =
3244           qtmux->last_moov_size + 12 * g_slist_length (qtmux->sinkpads) + 8;
3245 
3246       /* Send an additional free atom at the end so we definitely have space
3247        * to rewrite the moov header at the end and remove the samples that
3248        * were not actually written */
3249       ret =
3250           gst_qt_mux_send_free_atom (qtmux, &qtmux->header_size,
3251           12 * g_slist_length (qtmux->sinkpads) + 8, FALSE);
3252       if (ret != GST_FLOW_OK)
3253         return ret;
3254 
3255       /* extra atoms go after the free/moov(s), before the mdat */
3256       ret =
3257           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3258       if (ret != GST_FLOW_OK)
3259         return ret;
3260 
3261       qtmux->mdat_pos = qtmux->header_size;
3262 
3263       /* And now send the mdat header */
3264       ret =
3265           gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size,
3266           qtmux->mdat_size, TRUE, FALSE);
3267 
3268       /* chunks position is set relative to the first byte of the
3269        * MDAT atom payload. Set the overall offset into the file */
3270       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3271 
3272       {
3273         GstSegment segment;
3274 
3275         gst_segment_init (&segment, GST_FORMAT_BYTES);
3276         segment.start = qtmux->moov_pos;
3277         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3278 
3279         ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3280         if (ret != GST_FLOW_OK)
3281           return ret;
3282 
3283         segment.start = qtmux->header_size;
3284         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3285       }
3286 
3287       qtmux->current_chunk_size = 0;
3288       qtmux->current_chunk_duration = 0;
3289       qtmux->current_chunk_offset = -1;
3290       qtmux->mdat_size = 0;
3291       qtmux->current_pad = NULL;
3292       qtmux->longest_chunk = GST_CLOCK_TIME_NONE;
3293 
3294       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3295         GstCollectData *cdata = (GstCollectData *) walk->data;
3296         GstQTPad *qtpad = (GstQTPad *) cdata;
3297 
3298         qtpad->total_bytes = 0;
3299         qtpad->total_duration = 0;
3300         qtpad->first_dts = qtpad->first_ts = GST_CLOCK_TIME_NONE;
3301         qtpad->last_dts = GST_CLOCK_TIME_NONE;
3302         qtpad->sample_offset = 0;
3303       }
3304 
3305       break;
3306     case GST_QT_MUX_MODE_FAST_START:
3307       GST_OBJECT_LOCK (qtmux);
3308       qtmux->fast_start_file = g_fopen (qtmux->fast_start_file_path, "wb+");
3309       if (!qtmux->fast_start_file)
3310         goto open_failed;
3311       GST_OBJECT_UNLOCK (qtmux);
3312       /* send a dummy buffer for preroll */
3313       ret = gst_qt_mux_send_buffer (qtmux, gst_buffer_new (), NULL, FALSE);
3314       break;
3315     case GST_QT_MUX_MODE_FRAGMENTED:
3316     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
3317       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3318       if (ret != GST_FLOW_OK)
3319         break;
3320       /* store the moov pos so we can update the duration later
3321        * in non-streamable mode */
3322       qtmux->moov_pos = qtmux->header_size;
3323 
3324       GST_DEBUG_OBJECT (qtmux, "fragment duration %d ms, writing headers",
3325           qtmux->fragment_duration);
3326       /* also used as snapshot marker to indicate fragmented file */
3327       qtmux->fragment_sequence = 1;
3328       /* prepare moov and/or tags */
3329       gst_qt_mux_configure_moov (qtmux);
3330       gst_qt_mux_setup_metadata (qtmux);
3331       ret = gst_qt_mux_send_moov (qtmux, &qtmux->header_size, 0, FALSE, FALSE);
3332       if (ret != GST_FLOW_OK)
3333         return ret;
3334       /* extra atoms */
3335       ret =
3336           gst_qt_mux_send_extra_atoms (qtmux, TRUE, &qtmux->header_size, FALSE);
3337       if (ret != GST_FLOW_OK)
3338         break;
3339       /* prepare index if not streamable */
3340       if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED)
3341         qtmux->mfra = atom_mfra_new (qtmux->context);
3342       break;
3343   }
3344 
3345   return ret;
3346   /* ERRORS */
3347 invalid_isml:
3348   {
3349     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3350         ("Cannot create an ISML file with 0 fragment duration"), (NULL));
3351     return GST_FLOW_ERROR;
3352   }
3353 reserved_moov_too_small:
3354   {
3355     GST_ELEMENT_ERROR (qtmux, STREAM, MUX,
3356         ("Not enough reserved space for creating headers"), (NULL));
3357     return GST_FLOW_ERROR;
3358   }
3359 open_failed:
3360   {
3361     GST_ELEMENT_ERROR (qtmux, RESOURCE, OPEN_READ_WRITE,
3362         (("Could not open temporary file \"%s\""),
3363             qtmux->fast_start_file_path), GST_ERROR_SYSTEM);
3364     GST_OBJECT_UNLOCK (qtmux);
3365     return GST_FLOW_ERROR;
3366   }
3367 }
3368 
3369 static GstFlowReturn
gst_qt_mux_send_last_buffers(GstQTMux * qtmux)3370 gst_qt_mux_send_last_buffers (GstQTMux * qtmux)
3371 {
3372   GstFlowReturn ret = GST_FLOW_OK;
3373   GSList *walk;
3374 
3375   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3376     GstCollectData *cdata = (GstCollectData *) walk->data;
3377     GstQTPad *qtpad = (GstQTPad *) cdata;
3378 
3379     /* avoid add_buffer complaining if not negotiated
3380      * in which case no buffers either, so skipping */
3381     if (!qtpad->fourcc) {
3382       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3383           GST_PAD_NAME (qtpad->collect.pad));
3384       continue;
3385     }
3386 
3387     /* send last buffer; also flushes possibly queued buffers/ts */
3388     GST_DEBUG_OBJECT (qtmux, "Sending the last buffer for pad %s",
3389         GST_PAD_NAME (qtpad->collect.pad));
3390     ret = gst_qt_mux_add_buffer (qtmux, qtpad, NULL);
3391     if (ret != GST_FLOW_OK) {
3392       GST_WARNING_OBJECT (qtmux, "Failed to send last buffer for %s, "
3393           "flow return: %s", GST_PAD_NAME (qtpad->collect.pad),
3394           gst_flow_get_name (ret));
3395     }
3396   }
3397 
3398   return ret;
3399 }
3400 
3401 static void
gst_qt_mux_update_global_statistics(GstQTMux * qtmux)3402 gst_qt_mux_update_global_statistics (GstQTMux * qtmux)
3403 {
3404   GSList *walk;
3405 
3406   /* for setting some subtitles fields */
3407   guint max_width = 0;
3408   guint max_height = 0;
3409 
3410   qtmux->first_ts = qtmux->last_dts = GST_CLOCK_TIME_NONE;
3411 
3412   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3413     GstCollectData *cdata = (GstCollectData *) walk->data;
3414     GstQTPad *qtpad = (GstQTPad *) cdata;
3415 
3416     if (!qtpad->fourcc) {
3417       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3418           GST_PAD_NAME (qtpad->collect.pad));
3419       continue;
3420     }
3421 
3422     /* having flushed above, can check for buffers now */
3423     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3424       GstClockTime first_pts_in = qtpad->first_ts;
3425       /* it should be, since we got first_ts by adding adjustment
3426        * to a positive incoming PTS */
3427       if (qtpad->dts_adjustment <= first_pts_in)
3428         first_pts_in -= qtpad->dts_adjustment;
3429       /* determine max stream duration */
3430       if (!GST_CLOCK_TIME_IS_VALID (qtmux->last_dts)
3431           || qtpad->last_dts > qtmux->last_dts) {
3432         qtmux->last_dts = qtpad->last_dts;
3433       }
3434       if (!GST_CLOCK_TIME_IS_VALID (qtmux->first_ts)
3435           || first_pts_in < qtmux->first_ts) {
3436         /* we need the original incoming PTS here, as this first_ts
3437          * is used in update_edit_lists to construct the edit list that arrange
3438          * for sync'ed streams.  The first_ts is most likely obtained from
3439          * some (audio) stream with 0 dts_adjustment and initial 0 PTS,
3440          * so it makes no difference, though it matters in other cases */
3441         qtmux->first_ts = first_pts_in;
3442       }
3443     }
3444 
3445     /* subtitles need to know the video width/height,
3446      * it is stored shifted 16 bits to the left according to the
3447      * spec */
3448     max_width = MAX (max_width, (qtpad->trak->tkhd.width >> 16));
3449     max_height = MAX (max_height, (qtpad->trak->tkhd.height >> 16));
3450 
3451     /* update average bitrate of streams if needed */
3452     {
3453       guint32 avgbitrate = 0;
3454       guint32 maxbitrate = qtpad->max_bitrate;
3455 
3456       if (qtpad->avg_bitrate)
3457         avgbitrate = qtpad->avg_bitrate;
3458       else if (qtpad->total_duration > 0)
3459         avgbitrate = (guint32) gst_util_uint64_scale_round (qtpad->total_bytes,
3460             8 * GST_SECOND, qtpad->total_duration);
3461 
3462       atom_trak_update_bitrates (qtpad->trak, avgbitrate, maxbitrate);
3463     }
3464   }
3465 
3466   /* need to update values on subtitle traks now that we know the
3467    * max width and height */
3468   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3469     GstCollectData *cdata = (GstCollectData *) walk->data;
3470     GstQTPad *qtpad = (GstQTPad *) cdata;
3471 
3472     if (!qtpad->fourcc) {
3473       GST_DEBUG_OBJECT (qtmux, "Pad %s has never had buffers",
3474           GST_PAD_NAME (qtpad->collect.pad));
3475       continue;
3476     }
3477 
3478     if (qtpad->fourcc == FOURCC_tx3g) {
3479       atom_trak_tx3g_update_dimension (qtpad->trak, max_width, max_height);
3480     }
3481   }
3482 }
3483 
3484 /* Called after gst_qt_mux_update_global_statistics() updates the
3485  * first_ts tracking, to create/set edit lists for delayed streams */
3486 static void
gst_qt_mux_update_edit_lists(GstQTMux * qtmux)3487 gst_qt_mux_update_edit_lists (GstQTMux * qtmux)
3488 {
3489   GSList *walk;
3490 
3491   GST_DEBUG_OBJECT (qtmux, "Media first ts selected: %" GST_TIME_FORMAT,
3492       GST_TIME_ARGS (qtmux->first_ts));
3493   /* add/update EDTSs for late streams. configure_moov will have
3494    * set the trak durations above by summing the sample tables,
3495    * here we extend that if needing to insert an empty segment */
3496   for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3497     GstCollectData *cdata = (GstCollectData *) walk->data;
3498     GstQTPad *qtpad = (GstQTPad *) cdata;
3499 
3500     atom_trak_edts_clear (qtpad->trak);
3501 
3502     if (GST_CLOCK_TIME_IS_VALID (qtpad->first_ts)) {
3503       guint32 lateness = 0;
3504       guint32 duration = qtpad->trak->tkhd.duration;
3505       gboolean has_gap;
3506 
3507       has_gap = (qtpad->first_ts > (qtmux->first_ts + qtpad->dts_adjustment));
3508 
3509       if (has_gap) {
3510         GstClockTime diff, trak_lateness;
3511 
3512         diff = qtpad->first_ts - (qtmux->first_ts + qtpad->dts_adjustment);
3513         lateness = gst_util_uint64_scale_round (diff,
3514             qtmux->timescale, GST_SECOND);
3515 
3516         /* Allow up to 1 trak timescale unit of lateness, Such a small
3517          * timestamp/duration can't be represented by the trak-specific parts
3518          * of the headers anyway, so it's irrelevantly small */
3519         trak_lateness = gst_util_uint64_scale (diff,
3520             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3521 
3522         if (trak_lateness > 0 && diff > qtmux->start_gap_threshold) {
3523           GST_DEBUG_OBJECT (qtmux,
3524               "Pad %s is a late stream by %" GST_TIME_FORMAT,
3525               GST_PAD_NAME (qtpad->collect.pad), GST_TIME_ARGS (diff));
3526 
3527           atom_trak_set_elst_entry (qtpad->trak, 0, lateness, (guint32) - 1,
3528               (guint32) (1 * 65536.0));
3529         }
3530       }
3531 
3532       /* Always write an edit list for the whole track. In general this is not
3533        * necessary except for the case of having a gap or DTS adjustment but
3534        * it allows to give the whole track's duration in the usually more
3535        * accurate media timescale
3536        */
3537       {
3538         GstClockTime ctts = 0;
3539         guint32 media_start;
3540 
3541         if (qtpad->first_ts > qtpad->first_dts)
3542           ctts = qtpad->first_ts - qtpad->first_dts;
3543 
3544         media_start = gst_util_uint64_scale_round (ctts,
3545             atom_trak_get_timescale (qtpad->trak), GST_SECOND);
3546 
3547         /* atom_trak_set_elst_entry() has a quirk - if the edit list
3548          * is empty because there's no gap added above, this call
3549          * will not replace index 1, it will create the entry at index 0.
3550          * Luckily, that's exactly what we want here */
3551         atom_trak_set_elst_entry (qtpad->trak, 1, duration, media_start,
3552             (guint32) (1 * 65536.0));
3553       }
3554 
3555       /* need to add the empty time to the trak duration */
3556       duration += lateness;
3557       qtpad->trak->tkhd.duration = duration;
3558       if (qtpad->tc_trak) {
3559         qtpad->tc_trak->tkhd.duration = duration;
3560         qtpad->tc_trak->mdia.mdhd.time_info.duration = duration;
3561       }
3562 
3563       /* And possibly grow the moov duration */
3564       if (duration > qtmux->moov->mvhd.time_info.duration) {
3565         qtmux->moov->mvhd.time_info.duration = duration;
3566         qtmux->moov->mvex.mehd.fragment_duration = duration;
3567       }
3568     }
3569   }
3570 }
3571 
3572 static GstFlowReturn
gst_qt_mux_update_timecode(GstQTMux * qtmux,GstQTPad * qtpad)3573 gst_qt_mux_update_timecode (GstQTMux * qtmux, GstQTPad * qtpad)
3574 {
3575   GstSegment segment;
3576   GstBuffer *buf;
3577   GstMapInfo map;
3578   guint64 offset = qtpad->tc_pos;
3579   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
3580 
3581   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
3582     return GST_FLOW_OK;
3583 
3584   g_assert (qtpad->tc_pos != -1);
3585 
3586   gst_segment_init (&segment, GST_FORMAT_BYTES);
3587   segment.start = offset;
3588   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3589 
3590   buf = gst_buffer_new_and_alloc (4);
3591   gst_buffer_map (buf, &map, GST_MAP_WRITE);
3592 
3593   GST_WRITE_UINT32_BE (map.data,
3594       gst_video_time_code_frames_since_daily_jam (qtpad->first_tc));
3595   gst_buffer_unmap (buf, &map);
3596 
3597   /* Reset this value, so the timecode won't be re-rewritten */
3598   qtpad->tc_pos = -1;
3599 
3600   return gst_qt_mux_send_buffer (qtmux, buf, &offset, FALSE);
3601 }
3602 
3603 static GstFlowReturn
gst_qt_mux_stop_file(GstQTMux * qtmux)3604 gst_qt_mux_stop_file (GstQTMux * qtmux)
3605 {
3606   gboolean ret = GST_FLOW_OK;
3607   guint64 offset = 0, size = 0;
3608   gboolean large_file;
3609   GSList *walk;
3610 
3611   GST_DEBUG_OBJECT (qtmux, "Updating remaining values and sending last data");
3612 
3613   /* pushing last buffers for each pad */
3614   if ((ret = gst_qt_mux_send_last_buffers (qtmux)) != GST_FLOW_OK)
3615     return ret;
3616 
3617   if (qtmux->mux_mode == GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
3618     /* Streamable mode; no need to write duration or MFRA */
3619     GST_DEBUG_OBJECT (qtmux, "streamable file; nothing to stop");
3620     return GST_FLOW_OK;
3621   }
3622 
3623   gst_qt_mux_update_global_statistics (qtmux);
3624   for (walk = qtmux->collect->data; walk; walk = walk->next) {
3625     GstQTPad *qtpad = (GstQTPad *) walk->data;
3626 
3627     if (qtpad->tc_pos != -1) {
3628       /* File is being stopped and timecode hasn't been updated. Update it now
3629        * with whatever we have */
3630       ret = gst_qt_mux_update_timecode (qtmux, qtpad);
3631       if (ret != GST_FLOW_OK)
3632         return ret;
3633     }
3634   }
3635 
3636   switch (qtmux->mux_mode) {
3637     case GST_QT_MUX_MODE_FRAGMENTED:{
3638       GstSegment segment;
3639       guint8 *data = NULL;
3640       GstBuffer *buf;
3641 
3642       size = offset = 0;
3643       GST_DEBUG_OBJECT (qtmux, "adding mfra");
3644       if (!atom_mfra_copy_data (qtmux->mfra, &data, &size, &offset))
3645         goto serialize_error;
3646       buf = _gst_buffer_new_take_data (data, offset);
3647       ret = gst_qt_mux_send_buffer (qtmux, buf, NULL, FALSE);
3648       if (ret != GST_FLOW_OK)
3649         return ret;
3650 
3651       /* only mvex duration is updated,
3652        * mvhd should be consistent with empty moov
3653        * (but TODO maybe some clients do not handle that well ?) */
3654       qtmux->moov->mvex.mehd.fragment_duration =
3655           gst_util_uint64_scale_round (qtmux->last_dts, qtmux->timescale,
3656           GST_SECOND);
3657       GST_DEBUG_OBJECT (qtmux,
3658           "rewriting moov with mvex duration %" GST_TIME_FORMAT,
3659           GST_TIME_ARGS (qtmux->last_dts));
3660       /* seek and rewrite the header */
3661       gst_segment_init (&segment, GST_FORMAT_BYTES);
3662       segment.start = qtmux->moov_pos;
3663       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3664       /* no need to seek back */
3665       return gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3666     }
3667     case GST_QT_MUX_MODE_ROBUST_RECORDING:{
3668       ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
3669       if (G_UNLIKELY (ret != GST_FLOW_OK))
3670         return ret;
3671       /* Finalise by writing the final size into the mdat. Up until now
3672        * it's been 0, which means 'rest of the file'
3673        * No need to seek back after this, we won't write any more */
3674       return gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3675           qtmux->mdat_size, NULL, TRUE);
3676     }
3677     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
3678       GSList *walk;
3679       guint32 next_track_id = qtmux->moov->mvhd.next_track_id;
3680 
3681       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3682         GstCollectData *cdata = (GstCollectData *) walk->data;
3683         GstQTPad *qpad = (GstQTPad *) cdata;
3684         guint64 block_idx;
3685         AtomSTBL *stbl = &qpad->trak->mdia.minf.stbl;
3686 
3687         /* Get the block index of the last sample we wrote, not of the next
3688          * sample we would write */
3689         block_idx = prefill_get_block_index (qtmux, qpad);
3690 
3691         /* stts */
3692         if (block_idx > 0) {
3693           STTSEntry *entry;
3694           guint64 nsamples = 0;
3695           gint i, n;
3696 
3697           n = atom_array_get_len (&stbl->stts.entries);
3698           for (i = 0; i < n; i++) {
3699             entry = &atom_array_index (&stbl->stts.entries, i);
3700             if (nsamples + entry->sample_count >= qpad->sample_offset) {
3701               entry->sample_count = qpad->sample_offset - nsamples;
3702               stbl->stts.entries.len = i + 1;
3703               break;
3704             }
3705             nsamples += entry->sample_count;
3706           }
3707           g_assert (i < n);
3708         } else {
3709           stbl->stts.entries.len = 0;
3710         }
3711 
3712         /* stsz */
3713         {
3714           g_assert (stbl->stsz.entries.len == 0);
3715           stbl->stsz.table_size = qpad->sample_offset;
3716         }
3717 
3718         /* stco/stsc */
3719         {
3720           gint i, n;
3721           guint64 nsamples = 0;
3722           gint chunk_index = 0;
3723           const TrakBufferEntryInfo *sample_entry;
3724 
3725           if (block_idx > 0) {
3726             sample_entry =
3727                 &g_array_index (qpad->samples, TrakBufferEntryInfo,
3728                 block_idx - 1);
3729 
3730             n = stbl->stco64.entries.len;
3731             for (i = 0; i < n; i++) {
3732               guint64 *entry = &atom_array_index (&stbl->stco64.entries, i);
3733 
3734               if (*entry == sample_entry->chunk_offset) {
3735                 stbl->stco64.entries.len = i + 1;
3736                 chunk_index = i + 1;
3737                 break;
3738               }
3739             }
3740             g_assert (i < n);
3741             g_assert (chunk_index > 0);
3742 
3743             n = stbl->stsc.entries.len;
3744             for (i = 0; i < n; i++) {
3745               STSCEntry *entry = &atom_array_index (&stbl->stsc.entries, i);
3746 
3747               if (entry->first_chunk >= chunk_index)
3748                 break;
3749 
3750               if (i > 0) {
3751                 nsamples +=
3752                     (entry->first_chunk - atom_array_index (&stbl->stsc.entries,
3753                         i -
3754                         1).first_chunk) * atom_array_index (&stbl->stsc.entries,
3755                     i - 1).samples_per_chunk;
3756               }
3757             }
3758             g_assert (i <= n);
3759 
3760             if (i > 0) {
3761               STSCEntry *prev_entry =
3762                   &atom_array_index (&stbl->stsc.entries, i - 1);
3763               nsamples +=
3764                   (chunk_index -
3765                   prev_entry->first_chunk) * prev_entry->samples_per_chunk;
3766               if (qpad->sample_offset - nsamples > 0) {
3767                 stbl->stsc.entries.len = i;
3768                 atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3769                     qpad->sample_offset - nsamples);
3770               } else {
3771                 stbl->stsc.entries.len = i;
3772                 stbl->stco64.entries.len--;
3773               }
3774             } else {
3775               /* Everything in a single chunk */
3776               stbl->stsc.entries.len = 0;
3777               atom_stsc_add_new_entry (&stbl->stsc, chunk_index,
3778                   qpad->sample_offset);
3779             }
3780           } else {
3781             stbl->stco64.entries.len = 0;
3782             stbl->stsc.entries.len = 0;
3783           }
3784         }
3785 
3786         {
3787           GList *walk2;
3788 
3789           for (walk2 = qtmux->moov->mvex.trexs; walk2; walk2 = walk2->next) {
3790             AtomTREX *trex = walk2->data;
3791 
3792             if (trex->track_ID == qpad->trak->tkhd.track_ID) {
3793               trex->track_ID = next_track_id;
3794               break;
3795             }
3796           }
3797 
3798           qpad->trak->tkhd.track_ID = next_track_id++;
3799         }
3800       }
3801       qtmux->moov->mvhd.next_track_id = next_track_id;
3802 
3803       gst_qt_mux_update_global_statistics (qtmux);
3804       gst_qt_mux_configure_moov (qtmux);
3805 
3806       gst_qt_mux_update_edit_lists (qtmux);
3807 
3808       /* Check if any gap edit lists were added. We don't have any space
3809        * reserved for this in the moov and the pre-finalized moov would have
3810        * broken A/V synchronization. Error out here now
3811        */
3812       for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
3813         GstCollectData *cdata = (GstCollectData *) walk->data;
3814         GstQTPad *qpad = (GstQTPad *) cdata;
3815 
3816         if (qpad->trak->edts
3817             && g_slist_length (qpad->trak->edts->elst.entries) > 1) {
3818           GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3819               ("Can't support gaps in prefill mode"));
3820 
3821           return GST_FLOW_ERROR;
3822         }
3823       }
3824 
3825       gst_qt_mux_setup_metadata (qtmux);
3826       atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
3827 
3828       {
3829         GstSegment segment;
3830 
3831         gst_segment_init (&segment, GST_FORMAT_BYTES);
3832         segment.start = qtmux->moov_pos;
3833         gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
3834 
3835         ret =
3836             gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
3837             FALSE);
3838         if (ret != GST_FLOW_OK)
3839           return ret;
3840 
3841         if (qtmux->reserved_moov_size > qtmux->last_moov_size) {
3842           ret =
3843               gst_qt_mux_send_free_atom (qtmux, NULL,
3844               qtmux->reserved_moov_size - qtmux->last_moov_size, TRUE);
3845         }
3846 
3847         if (ret != GST_FLOW_OK)
3848           return ret;
3849       }
3850 
3851       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3852           qtmux->mdat_size, NULL, FALSE);
3853       return ret;
3854     }
3855     default:
3856       break;
3857   }
3858 
3859   /* Moov-at-end or fast-start mode from here down */
3860   gst_qt_mux_configure_moov (qtmux);
3861 
3862   gst_qt_mux_update_edit_lists (qtmux);
3863 
3864   /* tags into file metadata */
3865   gst_qt_mux_setup_metadata (qtmux);
3866 
3867   large_file = (qtmux->mdat_size > MDAT_LARGE_FILE_LIMIT);
3868 
3869   switch (qtmux->mux_mode) {
3870     case GST_QT_MUX_MODE_FAST_START:{
3871       /* if faststart, update the offset of the atoms in the movie with the offset
3872        * that the movie headers before mdat will cause.
3873        * Also, send the ftyp */
3874       offset = size = 0;
3875 
3876       ret = gst_qt_mux_prepare_and_send_ftyp (qtmux);
3877       if (ret != GST_FLOW_OK) {
3878         goto ftyp_error;
3879       }
3880       /* copy into NULL to obtain size */
3881       if (!atom_moov_copy_data (qtmux->moov, NULL, &size, &offset))
3882         goto serialize_error;
3883       GST_DEBUG_OBJECT (qtmux, "calculated moov atom size %" G_GUINT64_FORMAT,
3884           offset);
3885       offset += qtmux->header_size + (large_file ? 16 : 8);
3886 
3887       /* sum up with the extra atoms size */
3888       ret = gst_qt_mux_send_extra_atoms (qtmux, FALSE, &offset, FALSE);
3889       if (ret != GST_FLOW_OK)
3890         return ret;
3891       break;
3892     }
3893     default:
3894       offset = qtmux->header_size;
3895       break;
3896   }
3897 
3898   /* Now that we know the size of moov + extra atoms, we can adjust
3899    * the chunk offsets stored into the moov */
3900   atom_moov_chunks_set_offset (qtmux->moov, offset);
3901 
3902   /* write out moov and extra atoms */
3903   /* note: as of this point, we no longer care about tracking written data size,
3904    * since there is no more use for it anyway */
3905   ret = gst_qt_mux_send_moov (qtmux, NULL, 0, FALSE, FALSE);
3906   if (ret != GST_FLOW_OK)
3907     return ret;
3908 
3909   /* extra atoms */
3910   ret = gst_qt_mux_send_extra_atoms (qtmux, TRUE, NULL, FALSE);
3911   if (ret != GST_FLOW_OK)
3912     return ret;
3913 
3914   switch (qtmux->mux_mode) {
3915     case GST_QT_MUX_MODE_MOOV_AT_END:
3916     {
3917       /* mdat needs update iff not using faststart */
3918       GST_DEBUG_OBJECT (qtmux, "updating mdat size");
3919       ret = gst_qt_mux_update_mdat_size (qtmux, qtmux->mdat_pos,
3920           qtmux->mdat_size, NULL, FALSE);
3921       /* note; no seeking back to the end of file is done,
3922        * since we no longer write anything anyway */
3923       break;
3924     }
3925     case GST_QT_MUX_MODE_FAST_START:
3926     {
3927       /* send mdat atom and move buffered data into it */
3928       /* mdat_size = accumulated (buffered data) */
3929       ret = gst_qt_mux_send_mdat_header (qtmux, NULL, qtmux->mdat_size,
3930           large_file, FALSE);
3931       if (ret != GST_FLOW_OK)
3932         return ret;
3933       ret = gst_qt_mux_send_buffered_data (qtmux, NULL);
3934       if (ret != GST_FLOW_OK)
3935         return ret;
3936       break;
3937     }
3938     default:
3939       g_assert_not_reached ();
3940   }
3941 
3942   return ret;
3943 
3944   /* ERRORS */
3945 serialize_error:
3946   {
3947     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
3948         ("Failed to serialize moov"));
3949     return GST_FLOW_ERROR;
3950   }
3951 ftyp_error:
3952   {
3953     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Failed to send ftyp"));
3954     return GST_FLOW_ERROR;
3955   }
3956 }
3957 
3958 static GstFlowReturn
gst_qt_mux_pad_fragment_add_buffer(GstQTMux * qtmux,GstQTPad * pad,GstBuffer * buf,gboolean force,guint32 nsamples,gint64 dts,guint32 delta,guint32 size,gboolean sync,gint64 pts_offset)3959 gst_qt_mux_pad_fragment_add_buffer (GstQTMux * qtmux, GstQTPad * pad,
3960     GstBuffer * buf, gboolean force, guint32 nsamples, gint64 dts,
3961     guint32 delta, guint32 size, gboolean sync, gint64 pts_offset)
3962 {
3963   GstFlowReturn ret = GST_FLOW_OK;
3964 
3965   /* setup if needed */
3966   if (G_UNLIKELY (!pad->traf || force))
3967     goto init;
3968 
3969 flush:
3970   /* flush pad fragment if threshold reached,
3971    * or at new keyframe if we should be minding those in the first place */
3972   if (G_UNLIKELY (force || (sync && pad->sync) ||
3973           pad->fragment_duration < (gint64) delta)) {
3974     AtomMOOF *moof;
3975     guint64 size = 0, offset = 0;
3976     guint8 *data = NULL;
3977     GstBuffer *buffer;
3978     guint i, total_size;
3979 
3980     /* now we know where moof ends up, update offset in tfra */
3981     if (pad->tfra)
3982       atom_tfra_update_offset (pad->tfra, qtmux->header_size);
3983 
3984     moof = atom_moof_new (qtmux->context, qtmux->fragment_sequence);
3985     /* takes ownership */
3986     atom_moof_add_traf (moof, pad->traf);
3987     pad->traf = NULL;
3988     atom_moof_copy_data (moof, &data, &size, &offset);
3989     buffer = _gst_buffer_new_take_data (data, offset);
3990     GST_LOG_OBJECT (qtmux, "writing moof size %" G_GSIZE_FORMAT,
3991         gst_buffer_get_size (buffer));
3992     ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->header_size, FALSE);
3993 
3994     /* and actual data */
3995     total_size = 0;
3996     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
3997       total_size +=
3998           gst_buffer_get_size (atom_array_index (&pad->fragment_buffers, i));
3999     }
4000 
4001     GST_LOG_OBJECT (qtmux, "writing %d buffers, total_size %d",
4002         atom_array_get_len (&pad->fragment_buffers), total_size);
4003     if (ret == GST_FLOW_OK)
4004       ret = gst_qt_mux_send_mdat_header (qtmux, &qtmux->header_size, total_size,
4005           FALSE, FALSE);
4006     for (i = 0; i < atom_array_get_len (&pad->fragment_buffers); i++) {
4007       if (G_LIKELY (ret == GST_FLOW_OK))
4008         ret = gst_qt_mux_send_buffer (qtmux,
4009             atom_array_index (&pad->fragment_buffers, i), &qtmux->header_size,
4010             FALSE);
4011       else
4012         gst_buffer_unref (atom_array_index (&pad->fragment_buffers, i));
4013     }
4014 
4015     atom_array_clear (&pad->fragment_buffers);
4016     atom_moof_free (moof);
4017     qtmux->fragment_sequence++;
4018     force = FALSE;
4019   }
4020 
4021 init:
4022   if (G_UNLIKELY (!pad->traf)) {
4023     GST_LOG_OBJECT (qtmux, "setting up new fragment");
4024     pad->traf = atom_traf_new (qtmux->context, atom_trak_get_id (pad->trak));
4025     atom_array_init (&pad->fragment_buffers, 512);
4026     pad->fragment_duration = gst_util_uint64_scale (qtmux->fragment_duration,
4027         atom_trak_get_timescale (pad->trak), 1000);
4028 
4029     if (G_UNLIKELY (qtmux->mfra && !pad->tfra)) {
4030       pad->tfra = atom_tfra_new (qtmux->context, atom_trak_get_id (pad->trak));
4031       atom_mfra_add_tfra (qtmux->mfra, pad->tfra);
4032     }
4033     atom_traf_set_base_decode_time (pad->traf, dts);
4034   }
4035 
4036   /* add buffer and metadata */
4037   atom_traf_add_samples (pad->traf, delta, size, sync, pts_offset,
4038       pad->sync && sync);
4039   atom_array_append (&pad->fragment_buffers, buf, 256);
4040   pad->fragment_duration -= delta;
4041 
4042   if (pad->tfra) {
4043     guint32 sn = atom_traf_get_sample_num (pad->traf);
4044 
4045     if ((sync && pad->sync) || (sn == 1 && !pad->sync))
4046       atom_tfra_add_entry (pad->tfra, dts, sn);
4047   }
4048 
4049   if (G_UNLIKELY (force))
4050     goto flush;
4051 
4052   return ret;
4053 }
4054 
4055 /* Here's the clever bit of robust recording: Updating the moov
4056  * header is done using a ping-pong scheme inside 2 blocks of size
4057  * 'reserved_moov_size' at the start of the file, in such a way that the
4058  * file on-disk is always valid if interrupted.
4059  * Inside the reserved space, we have 2 pairs of free + moov atoms
4060  * (in that order), free-A + moov-A @ offset 0 and free-B + moov-B at
4061  * at offset "reserved_moov_size".
4062  *
4063  * 1. Free-A has 0 size payload, moov-A immediately after is
4064  *    active/current, and is padded with an internal Free atom to
4065  *    end at reserved_space/2. Free-B is at reserved_space/2, sized
4066  *    to cover the remaining free space (including moov-B).
4067  * 2. We write moov-B (which is invisible inside free-B), and pad it to
4068  *    end at the end of free space. Then, we update free-A to size
4069  *    reserved_space/2 + sizeof(free-B), which hides moov-A and the
4070  *    free-B header, and makes moov-B active.
4071  * 3. Rewrite moov-A inside free-A, with padding out to free-B.
4072  *    Change the size of free-A to make moov-A active again.
4073  * 4. Rinse and repeat.
4074  *
4075  */
4076 static GstFlowReturn
gst_qt_mux_robust_recording_rewrite_moov(GstQTMux * qtmux)4077 gst_qt_mux_robust_recording_rewrite_moov (GstQTMux * qtmux)
4078 {
4079   GstSegment segment;
4080   GstFlowReturn ret;
4081   guint64 freeA_offset;
4082   guint32 new_freeA_size;
4083   guint64 new_moov_offset;
4084 
4085   /* Update moov info, then seek and rewrite the MOOV atom */
4086   gst_qt_mux_update_global_statistics (qtmux);
4087   gst_qt_mux_configure_moov (qtmux);
4088 
4089   gst_qt_mux_update_edit_lists (qtmux);
4090 
4091   /* tags into file metadata */
4092   gst_qt_mux_setup_metadata (qtmux);
4093 
4094   /* chunks position is set relative to the first byte of the
4095    * MDAT atom payload. Set the overall offset into the file */
4096   atom_moov_chunks_set_offset (qtmux->moov, qtmux->header_size);
4097 
4098   /* Calculate which moov to rewrite. qtmux->moov_pos points to
4099    * the start of the free-A header */
4100   freeA_offset = qtmux->moov_pos;
4101   if (qtmux->reserved_moov_first_active) {
4102     GST_DEBUG_OBJECT (qtmux, "Updating pong moov header");
4103     /* After this, freeA will include itself, moovA, plus the freeB
4104      * header */
4105     new_freeA_size = qtmux->reserved_moov_size + 16;
4106   } else {
4107     GST_DEBUG_OBJECT (qtmux, "Updating ping moov header");
4108     new_freeA_size = 8;
4109   }
4110   /* the moov we update is after free-A, calculate its offset */
4111   new_moov_offset = freeA_offset + new_freeA_size;
4112 
4113   /* Swap ping-pong cadence marker */
4114   qtmux->reserved_moov_first_active = !qtmux->reserved_moov_first_active;
4115 
4116   /* seek and rewrite the MOOV atom */
4117   gst_segment_init (&segment, GST_FORMAT_BYTES);
4118   segment.start = new_moov_offset;
4119   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4120 
4121   ret =
4122       gst_qt_mux_send_moov (qtmux, NULL, qtmux->reserved_moov_size, FALSE,
4123       TRUE);
4124   if (ret != GST_FLOW_OK)
4125     return ret;
4126 
4127   /* Update the estimated recording space remaining, based on amount used so
4128    * far and duration muxed so far */
4129   if (qtmux->last_moov_size > qtmux->base_moov_size && qtmux->last_dts > 0) {
4130     GstClockTime remain;
4131     GstClockTime time_muxed = qtmux->last_dts;
4132 
4133     remain =
4134         gst_util_uint64_scale (qtmux->reserved_moov_size -
4135         qtmux->last_moov_size, time_muxed,
4136         qtmux->last_moov_size - qtmux->base_moov_size);
4137     /* Always under-estimate slightly, so users
4138      * have time to stop muxing before we run out */
4139     if (remain < GST_SECOND / 2)
4140       remain = 0;
4141     else
4142       remain -= GST_SECOND / 2;
4143 
4144     GST_INFO_OBJECT (qtmux,
4145         "Reserved %u header bytes. Used %u in %" GST_TIME_FORMAT
4146         ". Remaining now %u or approx %" G_GUINT64_FORMAT " ns\n",
4147         qtmux->reserved_moov_size, qtmux->last_moov_size,
4148         GST_TIME_ARGS (qtmux->last_dts),
4149         qtmux->reserved_moov_size - qtmux->last_moov_size, remain);
4150 
4151     GST_OBJECT_LOCK (qtmux);
4152     qtmux->reserved_duration_remaining = remain;
4153     qtmux->muxed_since_last_update = 0;
4154     GST_DEBUG_OBJECT (qtmux, "reserved remaining duration now %"
4155         G_GUINT64_FORMAT, qtmux->reserved_duration_remaining);
4156     GST_OBJECT_UNLOCK (qtmux);
4157   }
4158 
4159 
4160   /* Now update the moov-A size. Don't pass offset, since we don't need
4161    * send_free_atom() to seek for us - all our callers seek back to
4162    * where they need after this, or they don't need it */
4163   gst_segment_init (&segment, GST_FORMAT_BYTES);
4164   segment.start = freeA_offset;
4165   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4166 
4167   ret = gst_qt_mux_send_free_atom (qtmux, NULL, new_freeA_size, TRUE);
4168 
4169   return ret;
4170 }
4171 
4172 static GstFlowReturn
gst_qt_mux_robust_recording_update(GstQTMux * qtmux,GstClockTime position)4173 gst_qt_mux_robust_recording_update (GstQTMux * qtmux, GstClockTime position)
4174 {
4175   GstSegment segment;
4176   GstFlowReturn flow_ret;
4177 
4178   guint64 mdat_offset = qtmux->mdat_pos + 16 + qtmux->mdat_size;
4179 
4180   GST_OBJECT_LOCK (qtmux);
4181 
4182   /* Update the offset of how much we've muxed, so the
4183    * report of remaining space keeps counting down */
4184   if (position > qtmux->last_moov_update &&
4185       position - qtmux->last_moov_update > qtmux->muxed_since_last_update) {
4186     GST_LOG_OBJECT (qtmux,
4187         "Muxed time %" G_GUINT64_FORMAT " since last moov update",
4188         qtmux->muxed_since_last_update);
4189     qtmux->muxed_since_last_update = position - qtmux->last_moov_update;
4190   }
4191 
4192   /* Next, check if we're supposed to send periodic moov updates downstream */
4193   if (qtmux->reserved_moov_update_period == GST_CLOCK_TIME_NONE) {
4194     GST_OBJECT_UNLOCK (qtmux);
4195     return GST_FLOW_OK;
4196   }
4197 
4198   /* Update if position is > the threshold or there's been no update yet */
4199   if (qtmux->last_moov_update != GST_CLOCK_TIME_NONE &&
4200       (position <= qtmux->last_moov_update ||
4201           (position - qtmux->last_moov_update) <
4202           qtmux->reserved_moov_update_period)) {
4203     GST_OBJECT_UNLOCK (qtmux);
4204     return GST_FLOW_OK;         /* No update needed yet */
4205   }
4206 
4207   qtmux->last_moov_update = position;
4208   GST_OBJECT_UNLOCK (qtmux);
4209 
4210   GST_DEBUG_OBJECT (qtmux, "Update moov atom, position %" GST_TIME_FORMAT
4211       " mdat starts @ %" G_GUINT64_FORMAT " we were a %" G_GUINT64_FORMAT,
4212       GST_TIME_ARGS (position), qtmux->mdat_pos, mdat_offset);
4213 
4214   flow_ret = gst_qt_mux_robust_recording_rewrite_moov (qtmux);
4215   if (G_UNLIKELY (flow_ret != GST_FLOW_OK))
4216     return flow_ret;
4217 
4218   /* Seek back to previous position */
4219   gst_segment_init (&segment, GST_FORMAT_BYTES);
4220   segment.start = mdat_offset;
4221   gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4222 
4223   return flow_ret;
4224 }
4225 
4226 static GstFlowReturn
gst_qt_mux_register_and_push_sample(GstQTMux * qtmux,GstQTPad * pad,GstBuffer * buffer,gboolean is_last_buffer,guint nsamples,gint64 last_dts,gint64 scaled_duration,guint sample_size,guint64 chunk_offset,gboolean sync,gboolean do_pts,gint64 pts_offset)4227 gst_qt_mux_register_and_push_sample (GstQTMux * qtmux, GstQTPad * pad,
4228     GstBuffer * buffer, gboolean is_last_buffer, guint nsamples,
4229     gint64 last_dts, gint64 scaled_duration, guint sample_size,
4230     guint64 chunk_offset, gboolean sync, gboolean do_pts, gint64 pts_offset)
4231 {
4232   GstFlowReturn ret = GST_FLOW_OK;
4233 
4234   /* note that a new chunk is started each time (not fancy but works) */
4235   if (qtmux->moov_recov_file) {
4236     if (!atoms_recov_write_trak_samples (qtmux->moov_recov_file, pad->trak,
4237             nsamples, (gint32) scaled_duration, sample_size, chunk_offset, sync,
4238             do_pts, pts_offset)) {
4239       GST_WARNING_OBJECT (qtmux, "Failed to write sample information to "
4240           "recovery file, disabling recovery");
4241       fclose (qtmux->moov_recov_file);
4242       qtmux->moov_recov_file = NULL;
4243     }
4244   }
4245 
4246   switch (qtmux->mux_mode) {
4247     case GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL:{
4248       const TrakBufferEntryInfo *sample_entry;
4249       guint64 block_idx = prefill_get_block_index (qtmux, pad);
4250 
4251       if (block_idx >= pad->samples->len) {
4252         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4253             ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4254                 block_idx, pad->samples->len));
4255         gst_buffer_unref (buffer);
4256         return GST_FLOW_ERROR;
4257       }
4258 
4259       /* Check if all values are as expected */
4260       sample_entry =
4261           &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4262 
4263       /* Allow +/- 1 difference for the scaled_duration to allow
4264        * for some rounding errors
4265        */
4266       if (sample_entry->nsamples != nsamples
4267           || ABSDIFF (sample_entry->delta, scaled_duration) > 1
4268           || sample_entry->size != sample_size
4269           || sample_entry->chunk_offset != chunk_offset
4270           || sample_entry->pts_offset != pts_offset
4271           || sample_entry->sync != sync) {
4272         GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4273             ("Unexpected values in sample %" G_GUINT64_FORMAT,
4274                 pad->sample_offset + 1));
4275         GST_ERROR_OBJECT (qtmux, "Expected: samples %u, delta %u, size %u, "
4276             "chunk offset %" G_GUINT64_FORMAT ", "
4277             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4278             sample_entry->nsamples,
4279             sample_entry->delta,
4280             sample_entry->size,
4281             sample_entry->chunk_offset,
4282             sample_entry->pts_offset, sample_entry->sync);
4283         GST_ERROR_OBJECT (qtmux, "Got: samples %u, delta %u, size %u, "
4284             "chunk offset %" G_GUINT64_FORMAT ", "
4285             "pts offset %" G_GUINT64_FORMAT ", sync %d",
4286             nsamples,
4287             (guint) scaled_duration,
4288             sample_size, chunk_offset, pts_offset, sync);
4289 
4290         gst_buffer_unref (buffer);
4291         return GST_FLOW_ERROR;
4292       }
4293 
4294       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4295       break;
4296     }
4297     case GST_QT_MUX_MODE_MOOV_AT_END:
4298     case GST_QT_MUX_MODE_FAST_START:
4299     case GST_QT_MUX_MODE_ROBUST_RECORDING:
4300       atom_trak_add_samples (pad->trak, nsamples, (gint32) scaled_duration,
4301           sample_size, chunk_offset, sync, pts_offset);
4302       ret = gst_qt_mux_send_buffer (qtmux, buffer, &qtmux->mdat_size, TRUE);
4303       /* Check if it's time to re-write the headers in robust-recording mode */
4304       if (ret == GST_FLOW_OK
4305           && qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING)
4306         ret = gst_qt_mux_robust_recording_update (qtmux, pad->total_duration);
4307       break;
4308     case GST_QT_MUX_MODE_FRAGMENTED:
4309     case GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE:
4310       /* ensure that always sync samples are marked as such */
4311       ret = gst_qt_mux_pad_fragment_add_buffer (qtmux, pad, buffer,
4312           is_last_buffer, nsamples, last_dts, (gint32) scaled_duration,
4313           sample_size, !pad->sync || sync, pts_offset);
4314       break;
4315   }
4316 
4317   return ret;
4318 }
4319 
4320 static void
gst_qt_mux_register_buffer_in_chunk(GstQTMux * qtmux,GstQTPad * pad,guint buffer_size,GstClockTime duration)4321 gst_qt_mux_register_buffer_in_chunk (GstQTMux * qtmux, GstQTPad * pad,
4322     guint buffer_size, GstClockTime duration)
4323 {
4324   /* not that much happens here,
4325    * but updating any of this very likely needs to happen all in sync,
4326    * unless there is a very good reason not to */
4327 
4328   /* for computing the avg bitrate */
4329   pad->total_bytes += buffer_size;
4330   pad->total_duration += duration;
4331   /* for keeping track of where we are in chunk;
4332    * ensures that data really is located as recorded in atoms */
4333   qtmux->current_chunk_size += buffer_size;
4334   qtmux->current_chunk_duration += duration;
4335 }
4336 
4337 static GstFlowReturn
gst_qt_mux_check_and_update_timecode(GstQTMux * qtmux,GstQTPad * pad,GstBuffer * buf,GstFlowReturn ret)4338 gst_qt_mux_check_and_update_timecode (GstQTMux * qtmux, GstQTPad * pad,
4339     GstBuffer * buf, GstFlowReturn ret)
4340 {
4341   GstVideoTimeCodeMeta *tc_meta;
4342   GstVideoTimeCode *tc;
4343   GstBuffer *tc_buf;
4344   gsize szret;
4345   guint32 frames_since_daily_jam;
4346   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
4347 
4348   if (!pad->trak->is_video)
4349     return ret;
4350 
4351   if (qtmux_klass->format != GST_QT_MUX_FORMAT_QT)
4352     return ret;
4353 
4354   if (buf == NULL || (pad->tc_trak != NULL && pad->tc_pos == -1))
4355     return ret;
4356 
4357   tc_meta = gst_buffer_get_video_time_code_meta (buf);
4358   if (!tc_meta)
4359     return ret;
4360 
4361   tc = &tc_meta->tc;
4362 
4363   /* This means we never got a timecode before */
4364   if (pad->first_tc == NULL) {
4365 #ifndef GST_DISABLE_GST_DEBUG
4366     gchar *tc_str = gst_video_time_code_to_string (tc);
4367     GST_DEBUG_OBJECT (qtmux, "Found first timecode %s", tc_str);
4368     g_free (tc_str);
4369 #endif
4370     g_assert (pad->tc_trak == NULL);
4371     pad->first_tc = gst_video_time_code_copy (tc);
4372     /* If frames are out of order, the frame we're currently getting might
4373      * not be the first one. Just write a 0 timecode for now and wait
4374      * until we receive a timecode that's lower than the current one */
4375     if (pad->is_out_of_order) {
4376       pad->first_pts = GST_BUFFER_PTS (buf);
4377       frames_since_daily_jam = 0;
4378       /* Position to rewrite */
4379       pad->tc_pos = qtmux->mdat_size;
4380     } else {
4381       frames_since_daily_jam =
4382           gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4383       frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4384     }
4385     /* Write the timecode trak now */
4386     pad->tc_trak = atom_trak_new (qtmux->context);
4387     atom_moov_add_trak (qtmux->moov, pad->tc_trak);
4388 
4389     pad->trak->tref = atom_tref_new (FOURCC_tmcd);
4390     atom_tref_add_entry (pad->trak->tref, pad->tc_trak->tkhd.track_ID);
4391 
4392     atom_trak_set_timecode_type (pad->tc_trak, qtmux->context,
4393         pad->trak->mdia.mdhd.time_info.timescale, pad->first_tc);
4394 
4395     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4396     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4397     g_assert (szret == 4);
4398 
4399     atom_trak_add_samples (pad->tc_trak, 1, 1, 4, qtmux->mdat_size, FALSE, 0);
4400     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4401 
4402     /* Need to reset the current chunk (of the previous pad) here because
4403      * some other data was written now above, and the pad has to start a
4404      * new chunk now */
4405     qtmux->current_chunk_offset = -1;
4406     qtmux->current_chunk_size = 0;
4407     qtmux->current_chunk_duration = 0;
4408   } else if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4409     frames_since_daily_jam =
4410         gst_video_time_code_frames_since_daily_jam (pad->first_tc);
4411     frames_since_daily_jam = GUINT32_TO_BE (frames_since_daily_jam);
4412 
4413     tc_buf = gst_buffer_new_allocate (NULL, 4, NULL);
4414     szret = gst_buffer_fill (tc_buf, 0, &frames_since_daily_jam, 4);
4415     g_assert (szret == 4);
4416 
4417     ret = gst_qt_mux_send_buffer (qtmux, tc_buf, &qtmux->mdat_size, TRUE);
4418     pad->tc_pos = -1;
4419 
4420     qtmux->current_chunk_offset = -1;
4421     qtmux->current_chunk_size = 0;
4422     qtmux->current_chunk_duration = 0;
4423   } else if (pad->is_out_of_order) {
4424     /* Check for a lower timecode than the one stored */
4425     g_assert (pad->tc_trak != NULL);
4426     if (GST_BUFFER_DTS (buf) <= pad->first_pts) {
4427       if (gst_video_time_code_compare (tc, pad->first_tc) == -1) {
4428         gst_video_time_code_free (pad->first_tc);
4429         pad->first_tc = gst_video_time_code_copy (tc);
4430       }
4431     } else {
4432       guint64 bk_size = qtmux->mdat_size;
4433       GstSegment segment;
4434       /* If this frame's DTS is after the first PTS received, it means
4435        * we've already received the first frame to be presented. Otherwise
4436        * the decoder would need to go back in time */
4437       gst_qt_mux_update_timecode (qtmux, pad);
4438 
4439       /* Reset writing position */
4440       gst_segment_init (&segment, GST_FORMAT_BYTES);
4441       segment.start = bk_size;
4442       gst_pad_push_event (qtmux->srcpad, gst_event_new_segment (&segment));
4443     }
4444   }
4445 
4446   return ret;
4447 }
4448 
4449 /*
4450  * Here we push the buffer and update the tables in the track atoms
4451  */
4452 static GstFlowReturn
gst_qt_mux_add_buffer(GstQTMux * qtmux,GstQTPad * pad,GstBuffer * buf)4453 gst_qt_mux_add_buffer (GstQTMux * qtmux, GstQTPad * pad, GstBuffer * buf)
4454 {
4455   GstBuffer *last_buf = NULL;
4456   GstClockTime duration;
4457   guint nsamples, sample_size;
4458   guint64 chunk_offset;
4459   gint64 last_dts, scaled_duration;
4460   gint64 pts_offset = 0;
4461   gboolean sync = FALSE;
4462   GstFlowReturn ret = GST_FLOW_OK;
4463   guint buffer_size;
4464 
4465   if (!pad->fourcc)
4466     goto not_negotiated;
4467 
4468   /* if this pad has a prepare function, call it */
4469   if (pad->prepare_buf_func != NULL) {
4470     GstBuffer *new_buf;
4471 
4472     new_buf = pad->prepare_buf_func (pad, buf, qtmux);
4473     if (buf && !new_buf)
4474       return GST_FLOW_OK;
4475     buf = new_buf;
4476   }
4477 
4478   ret = gst_qt_mux_check_and_update_timecode (qtmux, pad, buf, ret);
4479   if (ret != GST_FLOW_OK) {
4480     if (buf)
4481       gst_buffer_unref (buf);
4482     return ret;
4483   }
4484 
4485   last_buf = pad->last_buf;
4486   pad->last_buf = buf;
4487 
4488   if (last_buf == NULL) {
4489 #ifndef GST_DISABLE_GST_DEBUG
4490     if (buf == NULL) {
4491       GST_DEBUG_OBJECT (qtmux, "Pad %s has no previous buffer stored and "
4492           "received NULL buffer, doing nothing",
4493           GST_PAD_NAME (pad->collect.pad));
4494     } else {
4495       GST_LOG_OBJECT (qtmux,
4496           "Pad %s has no previous buffer stored, storing now",
4497           GST_PAD_NAME (pad->collect.pad));
4498     }
4499 #endif
4500     goto exit;
4501   }
4502 
4503   if (!GST_BUFFER_PTS_IS_VALID (last_buf))
4504     goto no_pts;
4505 
4506   /* if this is the first buffer, store the timestamp */
4507   if (G_UNLIKELY (pad->first_ts == GST_CLOCK_TIME_NONE)) {
4508     if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4509       pad->first_ts = GST_BUFFER_PTS (last_buf);
4510     } else if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4511       pad->first_ts = GST_BUFFER_DTS (last_buf);
4512     }
4513 
4514     if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4515       pad->first_dts = pad->last_dts = GST_BUFFER_DTS (last_buf);
4516     } else if (GST_BUFFER_PTS_IS_VALID (last_buf)) {
4517       pad->first_dts = pad->last_dts = GST_BUFFER_PTS (last_buf);
4518     }
4519 
4520     if (GST_CLOCK_TIME_IS_VALID (pad->first_ts)) {
4521       GST_DEBUG ("setting first_ts to %" G_GUINT64_FORMAT, pad->first_ts);
4522     } else {
4523       GST_WARNING_OBJECT (qtmux, "First buffer for pad %s has no timestamp, "
4524           "using 0 as first timestamp", GST_PAD_NAME (pad->collect.pad));
4525       pad->first_ts = pad->first_dts = 0;
4526     }
4527     GST_DEBUG_OBJECT (qtmux, "Stored first timestamp for pad %s %"
4528         GST_TIME_FORMAT, GST_PAD_NAME (pad->collect.pad),
4529         GST_TIME_ARGS (pad->first_ts));
4530   }
4531 
4532   if (buf && GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (buf)) &&
4533       GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (last_buf)) &&
4534       GST_BUFFER_DTS (buf) < GST_BUFFER_DTS (last_buf)) {
4535     GST_ERROR ("decreasing DTS value %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT,
4536         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
4537         GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)));
4538     pad->last_buf = buf = gst_buffer_make_writable (buf);
4539     GST_BUFFER_DTS (buf) = GST_BUFFER_DTS (last_buf);
4540   }
4541 
4542   buffer_size = gst_buffer_get_size (last_buf);
4543 
4544   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4545     guint required_buffer_size = prefill_get_sample_size (qtmux, pad);
4546     guint fill_size = required_buffer_size - buffer_size;
4547     GstMemory *mem;
4548     GstMapInfo map;
4549 
4550     if (required_buffer_size < buffer_size) {
4551       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4552           ("Sample size %u bigger than expected maximum %u", buffer_size,
4553               required_buffer_size));
4554       goto bail;
4555     }
4556 
4557     if (fill_size > 0) {
4558       GST_DEBUG_OBJECT (qtmux,
4559           "Padding buffer by %u bytes to reach required %u bytes", fill_size,
4560           required_buffer_size);
4561       mem = gst_allocator_alloc (NULL, fill_size, NULL);
4562       gst_memory_map (mem, &map, GST_MAP_WRITE);
4563       memset (map.data, 0, map.size);
4564       gst_memory_unmap (mem, &map);
4565       last_buf = gst_buffer_make_writable (last_buf);
4566       gst_buffer_append_memory (last_buf, mem);
4567       buffer_size = required_buffer_size;
4568     }
4569   }
4570 
4571   /* duration actually means time delta between samples, so we calculate
4572    * the duration based on the difference in DTS or PTS, falling back
4573    * to DURATION if the other two don't exist, such as with the last
4574    * sample before EOS. Or use 0 if nothing else is available */
4575   if (GST_BUFFER_DURATION_IS_VALID (last_buf))
4576     duration = GST_BUFFER_DURATION (last_buf);
4577   else
4578     duration = 0;
4579   if (!pad->sparse) {
4580     if (buf && GST_BUFFER_DTS_IS_VALID (buf)
4581         && GST_BUFFER_DTS_IS_VALID (last_buf))
4582       duration = GST_BUFFER_DTS (buf) - GST_BUFFER_DTS (last_buf);
4583     else if (buf && GST_BUFFER_PTS_IS_VALID (buf)
4584         && GST_BUFFER_PTS_IS_VALID (last_buf))
4585       duration = GST_BUFFER_PTS (buf) - GST_BUFFER_PTS (last_buf);
4586   }
4587 
4588   if (qtmux->current_pad != pad || qtmux->current_chunk_offset == -1) {
4589     GST_DEBUG_OBJECT (qtmux,
4590         "Switching to next chunk for pad %s:%s: offset %" G_GUINT64_FORMAT
4591         ", size %" G_GUINT64_FORMAT ", duration %" GST_TIME_FORMAT,
4592         GST_DEBUG_PAD_NAME (pad->collect.pad), qtmux->current_chunk_offset,
4593         qtmux->current_chunk_size,
4594         GST_TIME_ARGS (qtmux->current_chunk_duration));
4595     qtmux->current_pad = pad;
4596     if (qtmux->current_chunk_offset == -1)
4597       qtmux->current_chunk_offset = qtmux->mdat_size;
4598     else
4599       qtmux->current_chunk_offset += qtmux->current_chunk_size;
4600     qtmux->current_chunk_size = 0;
4601     qtmux->current_chunk_duration = 0;
4602   }
4603 
4604   last_dts = gst_util_uint64_scale_round (pad->last_dts,
4605       atom_trak_get_timescale (pad->trak), GST_SECOND);
4606 
4607   /* fragments only deal with 1 buffer == 1 chunk (== 1 sample) */
4608   if (pad->sample_size && !qtmux->fragment_sequence) {
4609     GstClockTime expected_timestamp;
4610 
4611     /* Constant size packets: usually raw audio (with many samples per
4612        buffer (= chunk)), but can also be fixed-packet-size codecs like ADPCM
4613      */
4614     sample_size = pad->sample_size;
4615     if (buffer_size % sample_size != 0)
4616       goto fragmented_sample;
4617 
4618     /* note: qt raw audio storage warps it implicitly into a timewise
4619      * perfect stream, discarding buffer times.
4620      * If the difference between the current PTS and the expected one
4621      * becomes too big, we error out: there was a gap and we have no way to
4622      * represent that, causing A/V sync to be off */
4623     expected_timestamp =
4624         gst_util_uint64_scale (pad->sample_offset, GST_SECOND,
4625         atom_trak_get_timescale (pad->trak)) + pad->first_ts;
4626     if (ABSDIFF (GST_BUFFER_DTS_OR_PTS (last_buf),
4627             expected_timestamp) > qtmux->max_raw_audio_drift)
4628       goto raw_audio_timestamp_drift;
4629 
4630     if (GST_BUFFER_DURATION (last_buf) != GST_CLOCK_TIME_NONE) {
4631       nsamples = gst_util_uint64_scale_round (GST_BUFFER_DURATION (last_buf),
4632           atom_trak_get_timescale (pad->trak), GST_SECOND);
4633       duration = GST_BUFFER_DURATION (last_buf);
4634     } else {
4635       nsamples = buffer_size / sample_size;
4636       duration =
4637           gst_util_uint64_scale_round (nsamples, GST_SECOND,
4638           atom_trak_get_timescale (pad->trak));
4639     }
4640 
4641     /* timescale = samplerate */
4642     scaled_duration = 1;
4643     pad->last_dts =
4644         pad->first_dts + gst_util_uint64_scale_round (pad->sample_offset +
4645         nsamples, GST_SECOND, atom_trak_get_timescale (pad->trak));
4646   } else {
4647     nsamples = 1;
4648     sample_size = buffer_size;
4649     if (!pad->sparse && ((buf && GST_BUFFER_DTS_IS_VALID (buf))
4650             || GST_BUFFER_DTS_IS_VALID (last_buf))) {
4651       gint64 scaled_dts;
4652       if (buf && GST_BUFFER_DTS_IS_VALID (buf)) {
4653         pad->last_dts = GST_BUFFER_DTS (buf);
4654       } else {
4655         pad->last_dts = GST_BUFFER_DTS (last_buf) + duration;
4656       }
4657       if ((gint64) (pad->last_dts) < 0) {
4658         scaled_dts = -gst_util_uint64_scale_round (-pad->last_dts,
4659             atom_trak_get_timescale (pad->trak), GST_SECOND);
4660       } else {
4661         scaled_dts = gst_util_uint64_scale_round (pad->last_dts,
4662             atom_trak_get_timescale (pad->trak), GST_SECOND);
4663       }
4664       scaled_duration = scaled_dts - last_dts;
4665       last_dts = scaled_dts;
4666     } else {
4667       /* first convert intended timestamp (in GstClockTime resolution) to
4668        * trak timescale, then derive delta;
4669        * this ensures sums of (scale)delta add up to converted timestamp,
4670        * which only deviates at most 1/scale from timestamp itself */
4671       scaled_duration = gst_util_uint64_scale_round (pad->last_dts + duration,
4672           atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts;
4673       pad->last_dts += duration;
4674     }
4675   }
4676 
4677   gst_qt_mux_register_buffer_in_chunk (qtmux, pad, buffer_size, duration);
4678 
4679   chunk_offset = qtmux->current_chunk_offset;
4680 
4681   GST_LOG_OBJECT (qtmux,
4682       "Pad (%s) dts updated to %" GST_TIME_FORMAT,
4683       GST_PAD_NAME (pad->collect.pad), GST_TIME_ARGS (pad->last_dts));
4684   GST_LOG_OBJECT (qtmux,
4685       "Adding %d samples to track, duration: %" G_GUINT64_FORMAT
4686       " size: %" G_GUINT32_FORMAT " chunk offset: %" G_GUINT64_FORMAT,
4687       nsamples, scaled_duration, sample_size, chunk_offset);
4688 
4689   /* might be a sync sample */
4690   if (pad->sync &&
4691       !GST_BUFFER_FLAG_IS_SET (last_buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
4692     GST_LOG_OBJECT (qtmux, "Adding new sync sample entry for track of pad %s",
4693         GST_PAD_NAME (pad->collect.pad));
4694     sync = TRUE;
4695   }
4696 
4697   if (GST_BUFFER_DTS_IS_VALID (last_buf)) {
4698     last_dts = gst_util_uint64_scale_round (GST_BUFFER_DTS (last_buf),
4699         atom_trak_get_timescale (pad->trak), GST_SECOND);
4700     pts_offset =
4701         (gint64) (gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4702             atom_trak_get_timescale (pad->trak), GST_SECOND) - last_dts);
4703   } else {
4704     pts_offset = 0;
4705     last_dts = gst_util_uint64_scale_round (GST_BUFFER_PTS (last_buf),
4706         atom_trak_get_timescale (pad->trak), GST_SECOND);
4707   }
4708   GST_DEBUG ("dts: %" GST_TIME_FORMAT " pts: %" GST_TIME_FORMAT
4709       " timebase_dts: %d pts_offset: %d",
4710       GST_TIME_ARGS (GST_BUFFER_DTS (last_buf)),
4711       GST_TIME_ARGS (GST_BUFFER_PTS (last_buf)),
4712       (int) (last_dts), (int) (pts_offset));
4713 
4714   if (GST_CLOCK_TIME_IS_VALID (duration)
4715       && (qtmux->current_chunk_duration > qtmux->longest_chunk
4716           || !GST_CLOCK_TIME_IS_VALID (qtmux->longest_chunk))) {
4717     GST_DEBUG_OBJECT (qtmux,
4718         "New longest chunk found: %" GST_TIME_FORMAT ", pad %s",
4719         GST_TIME_ARGS (qtmux->current_chunk_duration),
4720         GST_PAD_NAME (pad->collect.pad));
4721     qtmux->longest_chunk = qtmux->current_chunk_duration;
4722   }
4723 
4724   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4725     const TrakBufferEntryInfo *sample_entry;
4726     guint64 block_idx = prefill_get_block_index (qtmux, pad);
4727 
4728     if (block_idx >= pad->samples->len) {
4729       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4730           ("Unexpected sample %" G_GUINT64_FORMAT ", expected up to %u",
4731               block_idx, pad->samples->len));
4732       goto bail;
4733     }
4734 
4735     /* Check if all values are as expected */
4736     sample_entry =
4737         &g_array_index (pad->samples, TrakBufferEntryInfo, block_idx);
4738 
4739     if (chunk_offset < sample_entry->chunk_offset) {
4740       guint fill_size = sample_entry->chunk_offset - chunk_offset;
4741       GstBuffer *fill_buf;
4742 
4743       fill_buf = gst_buffer_new_allocate (NULL, fill_size, NULL);
4744       gst_buffer_memset (fill_buf, 0, 0, fill_size);
4745 
4746       ret = gst_qt_mux_send_buffer (qtmux, fill_buf, &qtmux->mdat_size, TRUE);
4747       if (ret != GST_FLOW_OK)
4748         goto bail;
4749       qtmux->current_chunk_offset = chunk_offset = sample_entry->chunk_offset;
4750       qtmux->current_chunk_size = buffer_size;
4751       qtmux->current_chunk_duration = duration;
4752     } else if (chunk_offset != sample_entry->chunk_offset) {
4753       GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4754           ("Unexpected chunk offset %" G_GUINT64_FORMAT ", expected up to %"
4755               G_GUINT64_FORMAT, chunk_offset, sample_entry->chunk_offset));
4756       goto bail;
4757     }
4758   }
4759 
4760   /* now we go and register this buffer/sample all over */
4761   ret = gst_qt_mux_register_and_push_sample (qtmux, pad, last_buf,
4762       buf == NULL, nsamples, last_dts, scaled_duration, sample_size,
4763       chunk_offset, sync, TRUE, pts_offset);
4764   pad->sample_offset += nsamples;
4765 
4766   /* if this is sparse and we have a next buffer, check if there is any gap
4767    * between them to insert an empty sample */
4768   if (pad->sparse && buf) {
4769     if (pad->create_empty_buffer) {
4770       GstBuffer *empty_buf;
4771       gint64 empty_duration =
4772           GST_BUFFER_PTS (buf) - (GST_BUFFER_PTS (last_buf) + duration);
4773       gint64 empty_duration_scaled;
4774       guint empty_size;
4775 
4776       empty_buf = pad->create_empty_buffer (pad, empty_duration);
4777 
4778       pad->last_dts = GST_BUFFER_PTS (buf);
4779       empty_duration_scaled = gst_util_uint64_scale_round (pad->last_dts,
4780           atom_trak_get_timescale (pad->trak), GST_SECOND)
4781           - (last_dts + scaled_duration);
4782       empty_size = gst_buffer_get_size (empty_buf);
4783 
4784       gst_qt_mux_register_buffer_in_chunk (qtmux, pad, empty_size,
4785           empty_duration);
4786 
4787       ret =
4788           gst_qt_mux_register_and_push_sample (qtmux, pad, empty_buf, FALSE, 1,
4789           last_dts + scaled_duration, empty_duration_scaled,
4790           empty_size, chunk_offset, sync, TRUE, 0);
4791     } else if (pad->fourcc != FOURCC_c608 && pad->fourcc != FOURCC_c708) {
4792       /* This assert is kept here to make sure implementors of new
4793        * sparse input format decide whether there needs to be special
4794        * gap handling or not */
4795       g_assert_not_reached ();
4796       GST_WARNING_OBJECT (qtmux,
4797           "no empty buffer creation function found for pad %s",
4798           GST_PAD_NAME (pad->collect.pad));
4799     }
4800   }
4801 
4802 exit:
4803 
4804   return ret;
4805 
4806   /* ERRORS */
4807 bail:
4808   {
4809     gst_buffer_unref (last_buf);
4810     return GST_FLOW_ERROR;
4811   }
4812 fragmented_sample:
4813   {
4814     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4815         ("Audio buffer contains fragmented sample."));
4816     goto bail;
4817   }
4818 raw_audio_timestamp_drift:
4819   {
4820     /* TODO: Could in theory be implemented with edit lists */
4821     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL),
4822         ("Audio stream timestamps are drifting (got %" GST_TIME_FORMAT
4823             ", expected %" GST_TIME_FORMAT "). This is not supported yet!",
4824             GST_TIME_ARGS (GST_BUFFER_DTS_OR_PTS (last_buf)),
4825             GST_TIME_ARGS (gst_util_uint64_scale (pad->sample_offset,
4826                     GST_SECOND,
4827                     atom_trak_get_timescale (pad->trak)) + pad->first_ts)));
4828     goto bail;
4829   }
4830 no_pts:
4831   {
4832     GST_ELEMENT_ERROR (qtmux, STREAM, MUX, (NULL), ("Buffer has no PTS."));
4833     goto bail;
4834   }
4835 not_negotiated:
4836   {
4837     GST_ELEMENT_ERROR (qtmux, CORE, NEGOTIATION, (NULL),
4838         ("format wasn't negotiated before buffer flow on pad %s",
4839             GST_PAD_NAME (pad->collect.pad)));
4840     if (buf)
4841       gst_buffer_unref (buf);
4842     return GST_FLOW_NOT_NEGOTIATED;
4843   }
4844 }
4845 
4846 /*
4847  * DTS running time can be negative. There is no way to represent that in
4848  * MP4 however, thus we need to offset DTS so that it starts from 0.
4849  */
4850 static void
gst_qt_pad_adjust_buffer_dts(GstQTMux * qtmux,GstQTPad * pad,GstCollectData * cdata,GstBuffer ** buf)4851 gst_qt_pad_adjust_buffer_dts (GstQTMux * qtmux, GstQTPad * pad,
4852     GstCollectData * cdata, GstBuffer ** buf)
4853 {
4854   GstClockTime pts;
4855   gint64 dts;
4856 
4857   pts = GST_BUFFER_PTS (*buf);
4858   dts = GST_COLLECT_PADS_DTS (cdata);
4859 
4860   GST_LOG_OBJECT (qtmux, "selected pad %s with PTS %" GST_TIME_FORMAT
4861       " and DTS %" GST_STIME_FORMAT, GST_PAD_NAME (cdata->pad),
4862       GST_TIME_ARGS (pts), GST_STIME_ARGS (dts));
4863 
4864   if (!GST_CLOCK_TIME_IS_VALID (pad->dts_adjustment)) {
4865     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0)
4866       pad->dts_adjustment = -dts;
4867     else
4868       pad->dts_adjustment = 0;
4869   }
4870 
4871   if (pad->dts_adjustment > 0) {
4872     *buf = gst_buffer_make_writable (*buf);
4873 
4874     dts += pad->dts_adjustment;
4875 
4876     if (GST_CLOCK_TIME_IS_VALID (pts))
4877       pts += pad->dts_adjustment;
4878 
4879     if (GST_CLOCK_STIME_IS_VALID (dts) && dts < 0) {
4880       GST_WARNING_OBJECT (pad, "Decreasing DTS.");
4881       dts = 0;
4882     }
4883 
4884     if (pts < dts) {
4885       GST_WARNING_OBJECT (pad, "DTS is bigger then PTS");
4886       pts = dts;
4887     }
4888 
4889     GST_BUFFER_PTS (*buf) = pts;
4890     GST_BUFFER_DTS (*buf) = dts;
4891 
4892     GST_LOG_OBJECT (qtmux, "time adjusted to PTS %" GST_TIME_FORMAT
4893         " and DTS %" GST_TIME_FORMAT, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts));
4894   }
4895 }
4896 
4897 static GstQTPad *
find_best_pad(GstQTMux * qtmux,GstCollectPads * pads)4898 find_best_pad (GstQTMux * qtmux, GstCollectPads * pads)
4899 {
4900   GSList *walk;
4901   GstQTPad *best_pad = NULL;
4902 
4903   if (qtmux->mux_mode == GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL) {
4904     guint64 smallest_offset = G_MAXUINT64;
4905     guint64 chunk_offset = 0;
4906 
4907     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4908       GstCollectData *cdata = (GstCollectData *) walk->data;
4909       GstQTPad *qtpad = (GstQTPad *) cdata;
4910       const TrakBufferEntryInfo *sample_entry;
4911       guint64 block_idx, current_block_idx;
4912       guint64 chunk_offset_offset = 0;
4913       GstBuffer *tmp_buf =
4914           gst_collect_pads_peek (pads, (GstCollectData *) qtpad);
4915 
4916       /* Check for EOS pads and just skip them */
4917       if (!tmp_buf && !qtpad->last_buf && (!qtpad->raw_audio_adapter
4918               || gst_adapter_available (qtpad->raw_audio_adapter) == 0))
4919         continue;
4920       if (tmp_buf)
4921         gst_buffer_unref (tmp_buf);
4922 
4923       /* Find the exact offset where the next sample of this track is supposed
4924        * to be written at */
4925       block_idx = current_block_idx = prefill_get_block_index (qtmux, qtpad);
4926       sample_entry =
4927           &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx);
4928       while (block_idx > 0) {
4929         const TrakBufferEntryInfo *tmp =
4930             &g_array_index (qtpad->samples, TrakBufferEntryInfo, block_idx - 1);
4931 
4932         if (tmp->chunk_offset != sample_entry->chunk_offset)
4933           break;
4934         chunk_offset_offset += tmp->size * tmp->nsamples;
4935         block_idx--;
4936       }
4937 
4938       /* Except for the previously selected pad being EOS we always have
4939        *  qtmux->current_chunk_offset + qtmux->current_chunk_size
4940        *    ==
4941        *  sample_entry->chunk_offset + chunk_offset_offset
4942        * for the best pad. Instead of checking that, we just return the
4943        * pad that has the smallest offset for the next to-be-written sample.
4944        */
4945       if (sample_entry->chunk_offset + chunk_offset_offset < smallest_offset) {
4946         smallest_offset = sample_entry->chunk_offset + chunk_offset_offset;
4947         best_pad = qtpad;
4948         chunk_offset = sample_entry->chunk_offset;
4949       }
4950     }
4951 
4952     if (chunk_offset != qtmux->current_chunk_offset) {
4953       qtmux->current_pad = NULL;
4954     }
4955 
4956     return best_pad;
4957   }
4958 
4959   if (qtmux->current_pad && (qtmux->interleave_bytes != 0
4960           || qtmux->interleave_time != 0) && (qtmux->interleave_bytes == 0
4961           || qtmux->current_chunk_size <= qtmux->interleave_bytes)
4962       && (qtmux->interleave_time == 0
4963           || qtmux->current_chunk_duration <= qtmux->interleave_time)
4964       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED
4965       && qtmux->mux_mode != GST_QT_MUX_MODE_FRAGMENTED_STREAMABLE) {
4966     GstBuffer *tmp_buf =
4967         gst_collect_pads_peek (pads, (GstCollectData *) qtmux->current_pad);
4968 
4969     if (tmp_buf || qtmux->current_pad->last_buf) {
4970       best_pad = qtmux->current_pad;
4971       if (tmp_buf)
4972         gst_buffer_unref (tmp_buf);
4973       GST_DEBUG_OBJECT (qtmux, "Reusing pad %s:%s",
4974           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
4975     }
4976   } else if (qtmux->collect->data->next) {
4977     /* Only switch pads if we have more than one, otherwise
4978      * we can just put everything into a single chunk and save
4979      * a few bytes of offsets
4980      */
4981     if (qtmux->current_pad)
4982       GST_DEBUG_OBJECT (qtmux, "Switching from pad %s:%s",
4983           GST_DEBUG_PAD_NAME (qtmux->current_pad->collect.pad));
4984     best_pad = qtmux->current_pad = NULL;
4985   }
4986 
4987   if (!best_pad) {
4988     GstClockTime best_time = GST_CLOCK_TIME_NONE;
4989 
4990     for (walk = qtmux->collect->data; walk; walk = g_slist_next (walk)) {
4991       GstCollectData *cdata = (GstCollectData *) walk->data;
4992       GstQTPad *qtpad = (GstQTPad *) cdata;
4993       GstBuffer *tmp_buf;
4994       GstClockTime timestamp;
4995 
4996       tmp_buf = gst_collect_pads_peek (pads, cdata);
4997       if (!tmp_buf) {
4998         /* This one is newly EOS now, finish it for real */
4999         if (qtpad->last_buf) {
5000           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5001         } else {
5002           continue;
5003         }
5004       } else {
5005         if (qtpad->last_buf)
5006           timestamp = GST_BUFFER_DTS_OR_PTS (qtpad->last_buf);
5007         else
5008           timestamp = GST_BUFFER_DTS_OR_PTS (tmp_buf);
5009       }
5010 
5011       if (best_pad == NULL ||
5012           !GST_CLOCK_TIME_IS_VALID (best_time) || timestamp < best_time) {
5013         best_pad = qtpad;
5014         best_time = timestamp;
5015       }
5016 
5017       if (tmp_buf)
5018         gst_buffer_unref (tmp_buf);
5019     }
5020 
5021     if (best_pad) {
5022       GST_DEBUG_OBJECT (qtmux, "Choosing pad %s:%s",
5023           GST_DEBUG_PAD_NAME (best_pad->collect.pad));
5024     } else {
5025       GST_DEBUG_OBJECT (qtmux, "No best pad: EOS");
5026     }
5027   }
5028 
5029   return best_pad;
5030 }
5031 
5032 static GstFlowReturn
gst_qt_mux_collected(GstCollectPads * pads,gpointer user_data)5033 gst_qt_mux_collected (GstCollectPads * pads, gpointer user_data)
5034 {
5035   GstFlowReturn ret = GST_FLOW_OK;
5036   GstQTMux *qtmux = GST_QT_MUX_CAST (user_data);
5037   GstQTPad *best_pad = NULL;
5038 
5039   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_STARTED)) {
5040     if ((ret = gst_qt_mux_start_file (qtmux)) != GST_FLOW_OK)
5041       return ret;
5042 
5043     qtmux->state = GST_QT_MUX_STATE_DATA;
5044   }
5045 
5046   if (G_UNLIKELY (qtmux->state == GST_QT_MUX_STATE_EOS))
5047     return GST_FLOW_EOS;
5048 
5049   best_pad = find_best_pad (qtmux, pads);
5050 
5051   /* clipping already converted to running time */
5052   if (best_pad != NULL) {
5053     GstBuffer *buf = NULL;
5054 
5055     if (qtmux->mux_mode != GST_QT_MUX_MODE_ROBUST_RECORDING_PREFILL ||
5056         best_pad->raw_audio_adapter == NULL ||
5057         best_pad->raw_audio_adapter_pts == GST_CLOCK_TIME_NONE)
5058       buf = gst_collect_pads_pop (pads, (GstCollectData *) best_pad);
5059 
5060     g_assert (buf || best_pad->last_buf || (best_pad->raw_audio_adapter
5061             && gst_adapter_available (best_pad->raw_audio_adapter) > 0));
5062 
5063     if (buf)
5064       gst_qt_pad_adjust_buffer_dts (qtmux, best_pad,
5065           (GstCollectData *) best_pad, &buf);
5066 
5067     ret = gst_qt_mux_add_buffer (qtmux, best_pad, buf);
5068   } else {
5069     qtmux->state = GST_QT_MUX_STATE_EOS;
5070     ret = gst_qt_mux_stop_file (qtmux);
5071     if (ret == GST_FLOW_OK) {
5072       GST_DEBUG_OBJECT (qtmux, "Pushing eos");
5073       gst_pad_push_event (qtmux->srcpad, gst_event_new_eos ());
5074       ret = GST_FLOW_EOS;
5075     } else {
5076       GST_WARNING_OBJECT (qtmux, "Failed to stop file: %s",
5077           gst_flow_get_name (ret));
5078     }
5079   }
5080 
5081   return ret;
5082 }
5083 
5084 static gboolean
check_field(GQuark field_id,const GValue * value,gpointer user_data)5085 check_field (GQuark field_id, const GValue * value, gpointer user_data)
5086 {
5087   GstStructure *structure = (GstStructure *) user_data;
5088   const GValue *other = gst_structure_id_get_value (structure, field_id);
5089   if (other == NULL)
5090     return FALSE;
5091   return gst_value_compare (value, other) == GST_VALUE_EQUAL;
5092 }
5093 
5094 static gboolean
gst_qtmux_caps_is_subset_full(GstQTMux * qtmux,GstCaps * subset,GstCaps * superset)5095 gst_qtmux_caps_is_subset_full (GstQTMux * qtmux, GstCaps * subset,
5096     GstCaps * superset)
5097 {
5098   GstStructure *sub_s = gst_caps_get_structure (subset, 0);
5099   GstStructure *sup_s = gst_caps_get_structure (superset, 0);
5100 
5101   return gst_structure_foreach (sub_s, check_field, sup_s);
5102 }
5103 
5104 /* will unref @qtmux */
5105 static gboolean
gst_qt_mux_can_renegotiate(GstQTMux * qtmux,GstPad * pad,GstCaps * caps)5106 gst_qt_mux_can_renegotiate (GstQTMux * qtmux, GstPad * pad, GstCaps * caps)
5107 {
5108   GstCaps *current_caps;
5109 
5110   /* does not go well to renegotiate stream mid-way, unless
5111    * the old caps are a subset of the new one (this means upstream
5112    * added more info to the caps, as both should be 'fixed' caps) */
5113   current_caps = gst_pad_get_current_caps (pad);
5114   g_assert (caps != NULL);
5115 
5116   if (!gst_qtmux_caps_is_subset_full (qtmux, current_caps, caps)) {
5117     gst_caps_unref (current_caps);
5118     GST_WARNING_OBJECT (qtmux,
5119         "pad %s refused renegotiation to %" GST_PTR_FORMAT,
5120         GST_PAD_NAME (pad), caps);
5121     gst_object_unref (qtmux);
5122     return FALSE;
5123   }
5124 
5125   GST_DEBUG_OBJECT (qtmux,
5126       "pad %s accepted renegotiation to %" GST_PTR_FORMAT " from %"
5127       GST_PTR_FORMAT, GST_PAD_NAME (pad), caps, current_caps);
5128   gst_object_unref (qtmux);
5129   gst_caps_unref (current_caps);
5130 
5131   return TRUE;
5132 }
5133 
5134 static gboolean
gst_qt_mux_audio_sink_set_caps(GstQTPad * qtpad,GstCaps * caps)5135 gst_qt_mux_audio_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5136 {
5137   GstPad *pad = qtpad->collect.pad;
5138   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5139   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5140   GstStructure *structure;
5141   const gchar *mimetype;
5142   gint rate, channels;
5143   const GValue *value = NULL;
5144   const GstBuffer *codec_data = NULL;
5145   GstQTMuxFormat format;
5146   AudioSampleEntry entry = { 0, };
5147   AtomInfo *ext_atom = NULL;
5148   gint constant_size = 0;
5149   const gchar *stream_format;
5150   guint32 timescale;
5151 
5152   if (qtpad->fourcc)
5153     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5154 
5155   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5156       GST_DEBUG_PAD_NAME (pad), caps);
5157 
5158   qtpad->prepare_buf_func = NULL;
5159 
5160   format = qtmux_klass->format;
5161   structure = gst_caps_get_structure (caps, 0);
5162   mimetype = gst_structure_get_name (structure);
5163 
5164   /* common info */
5165   if (!gst_structure_get_int (structure, "channels", &channels) ||
5166       !gst_structure_get_int (structure, "rate", &rate)) {
5167     goto refuse_caps;
5168   }
5169 
5170   /* optional */
5171   value = gst_structure_get_value (structure, "codec_data");
5172   if (value != NULL)
5173     codec_data = gst_value_get_buffer (value);
5174 
5175   qtpad->is_out_of_order = FALSE;
5176 
5177   /* set common properties */
5178   entry.sample_rate = rate;
5179   entry.channels = channels;
5180   /* default */
5181   entry.sample_size = 16;
5182   /* this is the typical compressed case */
5183   if (format == GST_QT_MUX_FORMAT_QT) {
5184     entry.version = 1;
5185     entry.compression_id = -2;
5186   }
5187 
5188   /* now map onto a fourcc, and some extra properties */
5189   if (strcmp (mimetype, "audio/mpeg") == 0) {
5190     gint mpegversion = 0, mpegaudioversion = 0;
5191     gint layer = -1;
5192 
5193     gst_structure_get_int (structure, "mpegversion", &mpegversion);
5194     switch (mpegversion) {
5195       case 1:
5196         gst_structure_get_int (structure, "layer", &layer);
5197         gst_structure_get_int (structure, "mpegaudioversion",
5198             &mpegaudioversion);
5199 
5200         /* mp1/2/3 */
5201         /* note: QuickTime player does not like mp3 either way in iso/mp4 */
5202         if (format == GST_QT_MUX_FORMAT_QT)
5203           entry.fourcc = FOURCC__mp3;
5204         else {
5205           entry.fourcc = FOURCC_mp4a;
5206           ext_atom =
5207               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG1_P3,
5208               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5209               qtpad->max_bitrate);
5210         }
5211         if (layer == 1) {
5212           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5213               || format == GST_QT_MUX_FORMAT_QT);
5214           entry.samples_per_packet = 384;
5215         } else if (layer == 2) {
5216           g_warn_if_fail (format == GST_QT_MUX_FORMAT_MP4
5217               || format == GST_QT_MUX_FORMAT_QT);
5218           entry.samples_per_packet = 1152;
5219         } else {
5220           g_warn_if_fail (layer == 3);
5221           entry.samples_per_packet = (mpegaudioversion <= 1) ? 1152 : 576;
5222         }
5223         entry.bytes_per_sample = 2;
5224         break;
5225       case 4:
5226 
5227         /* check stream-format */
5228         stream_format = gst_structure_get_string (structure, "stream-format");
5229         if (stream_format) {
5230           if (strcmp (stream_format, "raw") != 0) {
5231             GST_WARNING_OBJECT (qtmux, "Unsupported AAC stream-format %s, "
5232                 "please use 'raw'", stream_format);
5233             goto refuse_caps;
5234           }
5235         } else {
5236           GST_WARNING_OBJECT (qtmux, "No stream-format present in caps, "
5237               "assuming 'raw'");
5238         }
5239 
5240         if (!codec_data || gst_buffer_get_size ((GstBuffer *) codec_data) < 2) {
5241           GST_WARNING_OBJECT (qtmux, "no (valid) codec_data for AAC audio");
5242           goto refuse_caps;
5243         } else {
5244           guint8 profile;
5245 
5246           gst_buffer_extract ((GstBuffer *) codec_data, 0, &profile, 1);
5247           /* warn if not Low Complexity profile */
5248           profile >>= 3;
5249           if (profile != 2)
5250             GST_WARNING_OBJECT (qtmux,
5251                 "non-LC AAC may not run well on (Apple) QuickTime/iTunes");
5252         }
5253 
5254         /* AAC */
5255         entry.fourcc = FOURCC_mp4a;
5256 
5257         if (format == GST_QT_MUX_FORMAT_QT)
5258           ext_atom = build_mov_aac_extension (qtpad->trak, codec_data,
5259               qtpad->avg_bitrate, qtpad->max_bitrate);
5260         else
5261           ext_atom =
5262               build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5263               ESDS_STREAM_TYPE_AUDIO, codec_data, qtpad->avg_bitrate,
5264               qtpad->max_bitrate);
5265         break;
5266       default:
5267         break;
5268     }
5269   } else if (strcmp (mimetype, "audio/AMR") == 0) {
5270     entry.fourcc = FOURCC_samr;
5271     entry.sample_size = 16;
5272     entry.samples_per_packet = 160;
5273     entry.bytes_per_sample = 2;
5274     ext_atom = build_amr_extension ();
5275   } else if (strcmp (mimetype, "audio/AMR-WB") == 0) {
5276     entry.fourcc = FOURCC_sawb;
5277     entry.sample_size = 16;
5278     entry.samples_per_packet = 320;
5279     entry.bytes_per_sample = 2;
5280     ext_atom = build_amr_extension ();
5281   } else if (strcmp (mimetype, "audio/x-raw") == 0) {
5282     GstAudioInfo info;
5283 
5284     gst_audio_info_init (&info);
5285     if (!gst_audio_info_from_caps (&info, caps))
5286       goto refuse_caps;
5287 
5288     /* spec has no place for a distinction in these */
5289     if (info.finfo->width != info.finfo->depth) {
5290       GST_DEBUG_OBJECT (qtmux, "width must be same as depth!");
5291       goto refuse_caps;
5292     }
5293 
5294     if ((info.finfo->flags & GST_AUDIO_FORMAT_FLAG_SIGNED)) {
5295       if (info.finfo->endianness == G_LITTLE_ENDIAN)
5296         entry.fourcc = FOURCC_sowt;
5297       else if (info.finfo->endianness == G_BIG_ENDIAN)
5298         entry.fourcc = FOURCC_twos;
5299       else
5300         entry.fourcc = FOURCC_sowt;
5301       /* maximum backward compatibility; only new version for > 16 bit */
5302       if (info.finfo->depth <= 16)
5303         entry.version = 0;
5304       /* not compressed in any case */
5305       entry.compression_id = 0;
5306       /* QT spec says: max at 16 bit even if sample size were actually larger,
5307        * however, most players (e.g. QuickTime!) seem to disagree, so ... */
5308       entry.sample_size = info.finfo->depth;
5309       entry.bytes_per_sample = info.finfo->depth / 8;
5310       entry.samples_per_packet = 1;
5311       entry.bytes_per_packet = info.finfo->depth / 8;
5312       entry.bytes_per_frame = entry.bytes_per_packet * info.channels;
5313     } else {
5314       if (info.finfo->width == 8 && info.finfo->depth == 8) {
5315         /* fall back to old 8-bit version */
5316         entry.fourcc = FOURCC_raw_;
5317         entry.version = 0;
5318         entry.compression_id = 0;
5319         entry.sample_size = 8;
5320       } else {
5321         GST_DEBUG_OBJECT (qtmux, "non 8-bit PCM must be signed");
5322         goto refuse_caps;
5323       }
5324     }
5325     constant_size = (info.finfo->depth / 8) * info.channels;
5326   } else if (strcmp (mimetype, "audio/x-alaw") == 0) {
5327     entry.fourcc = FOURCC_alaw;
5328     entry.samples_per_packet = 1023;
5329     entry.bytes_per_sample = 2;
5330   } else if (strcmp (mimetype, "audio/x-mulaw") == 0) {
5331     entry.fourcc = FOURCC_ulaw;
5332     entry.samples_per_packet = 1023;
5333     entry.bytes_per_sample = 2;
5334   } else if (strcmp (mimetype, "audio/x-adpcm") == 0) {
5335     gint blocksize;
5336     if (!gst_structure_get_int (structure, "block_align", &blocksize)) {
5337       GST_DEBUG_OBJECT (qtmux, "broken caps, block_align missing");
5338       goto refuse_caps;
5339     }
5340     /* Currently only supports WAV-style IMA ADPCM, for which the codec id is
5341        0x11 */
5342     entry.fourcc = MS_WAVE_FOURCC (0x11);
5343     /* 4 byte header per channel (including one sample). 2 samples per byte
5344        remaining. Simplifying gives the following (samples per block per
5345        channel) */
5346     entry.samples_per_packet = 2 * blocksize / channels - 7;
5347     entry.bytes_per_sample = 2;
5348 
5349     entry.bytes_per_frame = blocksize;
5350     entry.bytes_per_packet = blocksize / channels;
5351     /* ADPCM has constant size packets */
5352     constant_size = 1;
5353     /* TODO: I don't really understand why this helps, but it does! Constant
5354      * size and compression_id of -2 seem to be incompatible, and other files
5355      * in the wild use this too. */
5356     entry.compression_id = -1;
5357 
5358     ext_atom = build_ima_adpcm_extension (channels, rate, blocksize);
5359   } else if (strcmp (mimetype, "audio/x-alac") == 0) {
5360     GstBuffer *codec_config;
5361     gint len;
5362     GstMapInfo map;
5363 
5364     entry.fourcc = FOURCC_alac;
5365     gst_buffer_map ((GstBuffer *) codec_data, &map, GST_MAP_READ);
5366     /* let's check if codec data already comes with 'alac' atom prefix */
5367     if (!codec_data || (len = map.size) < 28) {
5368       GST_DEBUG_OBJECT (qtmux, "broken caps, codec data missing");
5369       gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5370       goto refuse_caps;
5371     }
5372     if (GST_READ_UINT32_LE (map.data + 4) == FOURCC_alac) {
5373       len -= 8;
5374       codec_config =
5375           gst_buffer_copy_region ((GstBuffer *) codec_data,
5376           GST_BUFFER_COPY_MEMORY, 8, len);
5377     } else {
5378       codec_config = gst_buffer_ref ((GstBuffer *) codec_data);
5379     }
5380     gst_buffer_unmap ((GstBuffer *) codec_data, &map);
5381     if (len != 28) {
5382       /* does not look good, but perhaps some trailing unneeded stuff */
5383       GST_WARNING_OBJECT (qtmux, "unexpected codec-data size, possibly broken");
5384     }
5385     if (format == GST_QT_MUX_FORMAT_QT)
5386       ext_atom = build_mov_alac_extension (codec_config);
5387     else
5388       ext_atom = build_codec_data_extension (FOURCC_alac, codec_config);
5389     /* set some more info */
5390     gst_buffer_map (codec_config, &map, GST_MAP_READ);
5391     entry.bytes_per_sample = 2;
5392     entry.samples_per_packet = GST_READ_UINT32_BE (map.data + 4);
5393     gst_buffer_unmap (codec_config, &map);
5394     gst_buffer_unref (codec_config);
5395   } else if (strcmp (mimetype, "audio/x-ac3") == 0) {
5396     entry.fourcc = FOURCC_ac_3;
5397 
5398     /* Fixed values according to TS 102 366 but it also mentions that
5399      * they should be ignored */
5400     entry.channels = 2;
5401     entry.sample_size = 16;
5402 
5403     /* AC-3 needs an extension atom but its data can only be obtained from
5404      * the stream itself. Abuse the prepare_buf_func so we parse a frame
5405      * and get the needed data */
5406     qtpad->prepare_buf_func = gst_qt_mux_prepare_parse_ac3_frame;
5407   } else if (strcmp (mimetype, "audio/x-opus") == 0) {
5408     /* Based on the specification defined in:
5409      * https://www.opus-codec.org/docs/opus_in_isobmff.html */
5410     guint8 channels, mapping_family, stream_count, coupled_count;
5411     guint16 pre_skip;
5412     gint16 output_gain;
5413     guint32 rate;
5414     guint8 channel_mapping[256];
5415     const GValue *streamheader;
5416     const GValue *first_element;
5417     GstBuffer *header;
5418 
5419     entry.fourcc = FOURCC_opus;
5420     entry.sample_size = 16;
5421 
5422     streamheader = gst_structure_get_value (structure, "streamheader");
5423     if (streamheader && GST_VALUE_HOLDS_ARRAY (streamheader) &&
5424         gst_value_array_get_size (streamheader) != 0) {
5425       first_element = gst_value_array_get_value (streamheader, 0);
5426       header = gst_value_get_buffer (first_element);
5427       if (!gst_codec_utils_opus_parse_header (header, &rate, &channels,
5428               &mapping_family, &stream_count, &coupled_count, channel_mapping,
5429               &pre_skip, &output_gain)) {
5430         GST_ERROR_OBJECT (qtmux, "Incomplete OpusHead");
5431         goto refuse_caps;
5432       }
5433     } else {
5434       GST_WARNING_OBJECT (qtmux,
5435           "no streamheader field in caps %" GST_PTR_FORMAT, caps);
5436 
5437       if (!gst_codec_utils_opus_parse_caps (caps, &rate, &channels,
5438               &mapping_family, &stream_count, &coupled_count,
5439               channel_mapping)) {
5440         GST_ERROR_OBJECT (qtmux, "Incomplete Opus caps");
5441         goto refuse_caps;
5442       }
5443       pre_skip = 0;
5444       output_gain = 0;
5445     }
5446 
5447     entry.channels = channels;
5448     ext_atom = build_opus_extension (rate, channels, mapping_family,
5449         stream_count, coupled_count, channel_mapping, pre_skip, output_gain);
5450   }
5451 
5452   if (!entry.fourcc)
5453     goto refuse_caps;
5454 
5455   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5456   if (!timescale && qtmux->trak_timescale)
5457     timescale = qtmux->trak_timescale;
5458   else if (!timescale)
5459     timescale = entry.sample_rate;
5460 
5461   /* ok, set the pad info accordingly */
5462   qtpad->fourcc = entry.fourcc;
5463   qtpad->sample_size = constant_size;
5464   qtpad->trak_ste =
5465       (SampleTableEntry *) atom_trak_set_audio_type (qtpad->trak,
5466       qtmux->context, &entry, timescale, ext_atom, constant_size);
5467 
5468   gst_object_unref (qtmux);
5469   return TRUE;
5470 
5471   /* ERRORS */
5472 refuse_caps:
5473   {
5474     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
5475         GST_PAD_NAME (pad), caps);
5476     gst_object_unref (qtmux);
5477     return FALSE;
5478   }
5479 }
5480 
5481 static gboolean
gst_qt_mux_video_sink_set_caps(GstQTPad * qtpad,GstCaps * caps)5482 gst_qt_mux_video_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
5483 {
5484   GstPad *pad = qtpad->collect.pad;
5485   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
5486   GstQTMuxClass *qtmux_klass = (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
5487   GstStructure *structure;
5488   const gchar *mimetype;
5489   gint width, height, depth = -1;
5490   gint framerate_num, framerate_den;
5491   guint32 rate;
5492   const GValue *value = NULL;
5493   const GstBuffer *codec_data = NULL;
5494   VisualSampleEntry entry = { 0, };
5495   GstQTMuxFormat format;
5496   AtomInfo *ext_atom = NULL;
5497   GList *ext_atom_list = NULL;
5498   gboolean sync = FALSE;
5499   int par_num, par_den;
5500   const gchar *multiview_mode;
5501 
5502   if (qtpad->fourcc)
5503     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
5504 
5505   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
5506       GST_DEBUG_PAD_NAME (pad), caps);
5507 
5508   qtpad->prepare_buf_func = NULL;
5509 
5510   format = qtmux_klass->format;
5511   structure = gst_caps_get_structure (caps, 0);
5512   mimetype = gst_structure_get_name (structure);
5513 
5514   /* required parts */
5515   if (!gst_structure_get_int (structure, "width", &width) ||
5516       !gst_structure_get_int (structure, "height", &height))
5517     goto refuse_caps;
5518 
5519   /* optional */
5520   depth = -1;
5521   /* works as a default timebase */
5522   framerate_num = 10000;
5523   framerate_den = 1;
5524   gst_structure_get_fraction (structure, "framerate", &framerate_num,
5525       &framerate_den);
5526   gst_structure_get_int (structure, "depth", &depth);
5527   value = gst_structure_get_value (structure, "codec_data");
5528   if (value != NULL)
5529     codec_data = gst_value_get_buffer (value);
5530 
5531   par_num = 1;
5532   par_den = 1;
5533   gst_structure_get_fraction (structure, "pixel-aspect-ratio", &par_num,
5534       &par_den);
5535 
5536   qtpad->is_out_of_order = FALSE;
5537 
5538   /* bring frame numerator into a range that ensures both reasonable resolution
5539    * as well as a fair duration */
5540   qtpad->expected_sample_duration_n = framerate_num;
5541   qtpad->expected_sample_duration_d = framerate_den;
5542 
5543   rate = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
5544   if (!rate && qtmux->trak_timescale)
5545     rate = qtmux->trak_timescale;
5546   else if (!rate)
5547     rate = atom_framerate_to_timescale (framerate_num, framerate_den);
5548 
5549   GST_DEBUG_OBJECT (qtmux, "Rate of video track selected: %" G_GUINT32_FORMAT,
5550       rate);
5551 
5552   multiview_mode = gst_structure_get_string (structure, "multiview-mode");
5553   if (multiview_mode && !qtpad->trak->mdia.minf.stbl.svmi) {
5554     GstVideoMultiviewMode mode;
5555     GstVideoMultiviewFlags flags = 0;
5556 
5557     mode = gst_video_multiview_mode_from_caps_string (multiview_mode);
5558     gst_structure_get_flagset (structure, "multiview-flags", &flags, NULL);
5559     switch (mode) {
5560       case GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE:
5561         qtpad->trak->mdia.minf.stbl.svmi =
5562             atom_svmi_new (0,
5563             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5564         break;
5565       case GST_VIDEO_MULTIVIEW_MODE_ROW_INTERLEAVED:
5566         qtpad->trak->mdia.minf.stbl.svmi =
5567             atom_svmi_new (1,
5568             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5569         break;
5570       case GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME:
5571         qtpad->trak->mdia.minf.stbl.svmi =
5572             atom_svmi_new (2,
5573             flags & GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST);
5574         break;
5575       default:
5576         GST_DEBUG_OBJECT (qtmux, "Unsupported multiview-mode %s",
5577             multiview_mode);
5578         break;
5579     }
5580   }
5581 
5582   /* set common properties */
5583   entry.width = width;
5584   entry.height = height;
5585   entry.par_n = par_num;
5586   entry.par_d = par_den;
5587   /* should be OK according to qt and iso spec, override if really needed */
5588   entry.color_table_id = -1;
5589   entry.frame_count = 1;
5590   entry.depth = 24;
5591 
5592   /* sync entries by default */
5593   sync = TRUE;
5594 
5595   /* now map onto a fourcc, and some extra properties */
5596   if (strcmp (mimetype, "video/x-raw") == 0) {
5597     const gchar *format;
5598     GstVideoFormat fmt;
5599     const GstVideoFormatInfo *vinfo;
5600 
5601     format = gst_structure_get_string (structure, "format");
5602     fmt = gst_video_format_from_string (format);
5603     vinfo = gst_video_format_get_info (fmt);
5604 
5605     switch (fmt) {
5606       case GST_VIDEO_FORMAT_UYVY:
5607         if (depth == -1)
5608           depth = 24;
5609         entry.fourcc = FOURCC_2vuy;
5610         entry.depth = depth;
5611         sync = FALSE;
5612         break;
5613       case GST_VIDEO_FORMAT_v210:
5614         if (depth == -1)
5615           depth = 24;
5616         entry.fourcc = FOURCC_v210;
5617         entry.depth = depth;
5618         sync = FALSE;
5619         break;
5620       default:
5621         if (GST_VIDEO_FORMAT_INFO_FLAGS (vinfo) & GST_VIDEO_FORMAT_FLAG_RGB) {
5622           entry.fourcc = FOURCC_raw_;
5623           entry.depth = GST_VIDEO_FORMAT_INFO_PSTRIDE (vinfo, 0) * 8;
5624           sync = FALSE;
5625         }
5626         break;
5627     }
5628   } else if (strcmp (mimetype, "video/x-h263") == 0) {
5629     ext_atom = NULL;
5630     if (format == GST_QT_MUX_FORMAT_QT)
5631       entry.fourcc = FOURCC_h263;
5632     else
5633       entry.fourcc = FOURCC_s263;
5634     ext_atom = build_h263_extension ();
5635     if (ext_atom != NULL)
5636       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5637   } else if (strcmp (mimetype, "video/x-divx") == 0 ||
5638       strcmp (mimetype, "video/mpeg") == 0) {
5639     gint version = 0;
5640 
5641     if (strcmp (mimetype, "video/x-divx") == 0) {
5642       gst_structure_get_int (structure, "divxversion", &version);
5643       version = version == 5 ? 1 : 0;
5644     } else {
5645       gst_structure_get_int (structure, "mpegversion", &version);
5646       version = version == 4 ? 1 : 0;
5647     }
5648     if (version) {
5649       entry.fourcc = FOURCC_mp4v;
5650       ext_atom =
5651           build_esds_extension (qtpad->trak, ESDS_OBJECT_TYPE_MPEG4_P2,
5652           ESDS_STREAM_TYPE_VISUAL, codec_data, qtpad->avg_bitrate,
5653           qtpad->max_bitrate);
5654       if (ext_atom != NULL)
5655         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5656       if (!codec_data)
5657         GST_WARNING_OBJECT (qtmux, "no codec_data for MPEG4 video; "
5658             "output might not play in Apple QuickTime (try global-headers?)");
5659     }
5660   } else if (strcmp (mimetype, "video/x-h264") == 0) {
5661     if (!codec_data) {
5662       GST_WARNING_OBJECT (qtmux, "no codec_data in h264 caps");
5663       goto refuse_caps;
5664     }
5665 
5666     entry.fourcc = FOURCC_avc1;
5667 
5668     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5669     if (ext_atom != NULL)
5670       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5671     ext_atom = build_codec_data_extension (FOURCC_avcC, codec_data);
5672     if (ext_atom != NULL)
5673       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5674   } else if (strcmp (mimetype, "video/x-h265") == 0) {
5675     const gchar *format;
5676 
5677     if (!codec_data) {
5678       GST_WARNING_OBJECT (qtmux, "no codec_data in h265 caps");
5679       goto refuse_caps;
5680     }
5681 
5682     format = gst_structure_get_string (structure, "stream-format");
5683     if (strcmp (format, "hvc1") == 0)
5684       entry.fourcc = FOURCC_hvc1;
5685     else if (strcmp (format, "hev1") == 0)
5686       entry.fourcc = FOURCC_hev1;
5687 
5688     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5689     if (ext_atom != NULL)
5690       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5691 
5692     ext_atom = build_codec_data_extension (FOURCC_hvcC, codec_data);
5693     if (ext_atom != NULL)
5694       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5695 
5696   } else if (strcmp (mimetype, "video/x-svq") == 0) {
5697     gint version = 0;
5698     const GstBuffer *seqh = NULL;
5699     const GValue *seqh_value;
5700     gdouble gamma = 0;
5701 
5702     gst_structure_get_int (structure, "svqversion", &version);
5703     if (version == 3) {
5704       entry.fourcc = FOURCC_SVQ3;
5705       entry.version = 3;
5706       entry.depth = 32;
5707 
5708       seqh_value = gst_structure_get_value (structure, "seqh");
5709       if (seqh_value) {
5710         seqh = gst_value_get_buffer (seqh_value);
5711         ext_atom = build_SMI_atom (seqh);
5712         if (ext_atom)
5713           ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5714       }
5715 
5716       /* we need to add the gamma anyway because quicktime might crash
5717        * when it doesn't find it */
5718       if (!gst_structure_get_double (structure, "applied-gamma", &gamma)) {
5719         /* it seems that using 0 here makes it ignored */
5720         gamma = 0.0;
5721       }
5722       ext_atom = build_gama_atom (gamma);
5723       if (ext_atom)
5724         ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5725     } else {
5726       GST_WARNING_OBJECT (qtmux, "SVQ version %d not supported. Please file "
5727           "a bug at http://bugzilla.gnome.org", version);
5728     }
5729   } else if (strcmp (mimetype, "video/x-dv") == 0) {
5730     gint version = 0;
5731     gboolean pal = TRUE;
5732 
5733     sync = FALSE;
5734     if (framerate_num != 25 || framerate_den != 1)
5735       pal = FALSE;
5736     gst_structure_get_int (structure, "dvversion", &version);
5737     /* fall back to typical one */
5738     if (!version)
5739       version = 25;
5740     switch (version) {
5741       case 25:
5742         if (pal)
5743           entry.fourcc = FOURCC_dvcp;
5744         else
5745           entry.fourcc = FOURCC_dvc_;
5746         break;
5747       case 50:
5748         if (pal)
5749           entry.fourcc = FOURCC_dv5p;
5750         else
5751           entry.fourcc = FOURCC_dv5n;
5752         break;
5753       default:
5754         GST_WARNING_OBJECT (qtmux, "unrecognized dv version");
5755         break;
5756     }
5757   } else if (strcmp (mimetype, "image/jpeg") == 0) {
5758     entry.fourcc = FOURCC_jpeg;
5759     sync = FALSE;
5760   } else if (strcmp (mimetype, "image/png") == 0) {
5761     entry.fourcc = FOURCC_png;
5762     sync = FALSE;
5763   } else if (strcmp (mimetype, "image/x-j2c") == 0 ||
5764       strcmp (mimetype, "image/x-jpc") == 0) {
5765     const gchar *colorspace;
5766     const GValue *cmap_array;
5767     const GValue *cdef_array;
5768     gint ncomp = 0;
5769 
5770     if (strcmp (mimetype, "image/x-jpc") == 0) {
5771       qtpad->prepare_buf_func = gst_qt_mux_prepare_jpc_buffer;
5772     }
5773 
5774     gst_structure_get_int (structure, "num-components", &ncomp);
5775     cmap_array = gst_structure_get_value (structure, "component-map");
5776     cdef_array = gst_structure_get_value (structure, "channel-definitions");
5777 
5778     ext_atom = NULL;
5779     entry.fourcc = FOURCC_mjp2;
5780     sync = FALSE;
5781 
5782     colorspace = gst_structure_get_string (structure, "colorspace");
5783     if (colorspace &&
5784         (ext_atom =
5785             build_jp2h_extension (width, height, colorspace, ncomp, cmap_array,
5786                 cdef_array)) != NULL) {
5787       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5788 
5789       ext_atom = build_jp2x_extension (codec_data);
5790       if (ext_atom)
5791         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5792     } else {
5793       GST_DEBUG_OBJECT (qtmux, "missing or invalid fourcc in jp2 caps");
5794       goto refuse_caps;
5795     }
5796   } else if (strcmp (mimetype, "video/x-vp8") == 0) {
5797     entry.fourcc = FOURCC_vp08;
5798   } else if (strcmp (mimetype, "video/x-vp9") == 0) {
5799     entry.fourcc = FOURCC_vp09;
5800   } else if (strcmp (mimetype, "video/x-dirac") == 0) {
5801     entry.fourcc = FOURCC_drac;
5802   } else if (strcmp (mimetype, "video/x-qt-part") == 0) {
5803     guint32 fourcc = 0;
5804 
5805     gst_structure_get_uint (structure, "format", &fourcc);
5806     entry.fourcc = fourcc;
5807   } else if (strcmp (mimetype, "video/x-mp4-part") == 0) {
5808     guint32 fourcc = 0;
5809 
5810     gst_structure_get_uint (structure, "format", &fourcc);
5811     entry.fourcc = fourcc;
5812   } else if (strcmp (mimetype, "video/x-prores") == 0) {
5813     const gchar *variant;
5814 
5815     variant = gst_structure_get_string (structure, "variant");
5816     if (!variant || !g_strcmp0 (variant, "standard"))
5817       entry.fourcc = FOURCC_apcn;
5818     else if (!g_strcmp0 (variant, "lt"))
5819       entry.fourcc = FOURCC_apcs;
5820     else if (!g_strcmp0 (variant, "hq"))
5821       entry.fourcc = FOURCC_apch;
5822     else if (!g_strcmp0 (variant, "proxy"))
5823       entry.fourcc = FOURCC_apco;
5824     else if (!g_strcmp0 (variant, "4444"))
5825       entry.fourcc = FOURCC_ap4h;
5826     else if (!g_strcmp0 (variant, "4444xq"))
5827       entry.fourcc = FOURCC_ap4x;
5828 
5829     sync = FALSE;
5830 
5831     if (!qtmux->interleave_time_set)
5832       qtmux->interleave_time = 500 * GST_MSECOND;
5833     if (!qtmux->interleave_bytes_set)
5834       qtmux->interleave_bytes = width > 720 ? 4 * 1024 * 1024 : 2 * 1024 * 1024;
5835   } else if (strcmp (mimetype, "video/x-cineform") == 0) {
5836     entry.fourcc = FOURCC_cfhd;
5837     sync = FALSE;
5838   } else if (strcmp (mimetype, "video/x-av1") == 0) {
5839     gint presentation_delay;
5840     guint8 presentation_delay_byte = 0;
5841     GstBuffer *av1_codec_data;
5842 
5843     if (gst_structure_get_int (structure, "presentation-delay",
5844             &presentation_delay)) {
5845       presentation_delay_byte = 1 << 5;
5846       presentation_delay_byte |= MAX (0xF, presentation_delay & 0xF);
5847     }
5848 
5849 
5850     av1_codec_data = gst_buffer_new_allocate (NULL, 5, NULL);
5851     /* Fill version and 3 bytes of flags to 0 */
5852     gst_buffer_memset (av1_codec_data, 0, 0, 4);
5853     gst_buffer_fill (av1_codec_data, 4, &presentation_delay_byte, 1);
5854     if (codec_data)
5855       av1_codec_data = gst_buffer_append (av1_codec_data,
5856           gst_buffer_ref ((GstBuffer *) codec_data));
5857 
5858     entry.fourcc = FOURCC_av01;
5859 
5860     ext_atom = build_btrt_extension (0, qtpad->avg_bitrate, qtpad->max_bitrate);
5861     if (ext_atom != NULL)
5862       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5863     ext_atom = build_codec_data_extension (FOURCC_av1C, av1_codec_data);
5864     if (ext_atom != NULL)
5865       ext_atom_list = g_list_prepend (ext_atom_list, ext_atom);
5866     gst_buffer_unref (av1_codec_data);
5867   }
5868 
5869   if (!entry.fourcc)
5870     goto refuse_caps;
5871 
5872   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT ||
5873       qtmux_klass->format == GST_QT_MUX_FORMAT_MP4) {
5874     const gchar *s;
5875     GstVideoColorimetry colorimetry;
5876 
5877     s = gst_structure_get_string (structure, "colorimetry");
5878     if (s && gst_video_colorimetry_from_string (&colorimetry, s)) {
5879       ext_atom =
5880           build_colr_extension (&colorimetry,
5881           qtmux_klass->format == GST_QT_MUX_FORMAT_MP4);
5882       if (ext_atom)
5883         ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5884     }
5885   }
5886 
5887   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT
5888       || strcmp (mimetype, "image/x-j2c") == 0
5889       || strcmp (mimetype, "image/x-jpc") == 0) {
5890     const gchar *s;
5891     GstVideoInterlaceMode interlace_mode;
5892     GstVideoFieldOrder field_order;
5893     gint fields = -1;
5894 
5895     if (strcmp (mimetype, "image/x-j2c") == 0 ||
5896         strcmp (mimetype, "image/x-jpc") == 0) {
5897 
5898       fields = 1;
5899       gst_structure_get_int (structure, "fields", &fields);
5900     }
5901 
5902     s = gst_structure_get_string (structure, "interlace-mode");
5903     if (s)
5904       interlace_mode = gst_video_interlace_mode_from_string (s);
5905     else
5906       interlace_mode =
5907           (fields <=
5908           1) ? GST_VIDEO_INTERLACE_MODE_PROGRESSIVE :
5909           GST_VIDEO_INTERLACE_MODE_MIXED;
5910 
5911     field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
5912     if (interlace_mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
5913       s = gst_structure_get_string (structure, "field-order");
5914       if (s)
5915         field_order = gst_video_field_order_from_string (s);
5916     }
5917 
5918     ext_atom = build_fiel_extension (interlace_mode, field_order);
5919     if (ext_atom)
5920       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5921   }
5922 
5923 
5924   if (qtmux_klass->format == GST_QT_MUX_FORMAT_QT &&
5925       width > 640 && width <= 1052 && height >= 480 && height <= 576) {
5926     /* The 'clap' extension is also defined for MP4 but inventing values in
5927      * general seems a bit tricky for this one. We only write it for
5928      * SD resolution in MOV, where it is a requirement.
5929      * The same goes for the 'tapt' extension, just that it is not defined for
5930      * MP4 and only for MOV
5931      */
5932     gint dar_num, dar_den;
5933     gint clef_width, clef_height, prof_width;
5934     gint clap_width_n, clap_width_d, clap_height;
5935     gint cdiv;
5936     double approx_dar;
5937 
5938     /* First, guess display aspect ratio based on pixel aspect ratio,
5939      * width and height. We assume that display aspect ratio is either
5940      * 4:3 or 16:9
5941      */
5942     approx_dar = (gdouble) (width * par_num) / (height * par_den);
5943     if (approx_dar > 11.0 / 9 && approx_dar < 14.0 / 9) {
5944       dar_num = 4;
5945       dar_den = 3;
5946     } else if (approx_dar > 15.0 / 9 && approx_dar < 18.0 / 9) {
5947       dar_num = 16;
5948       dar_den = 9;
5949     } else {
5950       dar_num = width * par_num;
5951       dar_den = height * par_den;
5952       cdiv = gst_util_greatest_common_divisor (dar_num, dar_den);
5953       dar_num /= cdiv;
5954       dar_den /= cdiv;
5955     }
5956 
5957     /* Then, calculate clean-aperture values (clap and clef)
5958      * using the guessed DAR.
5959      */
5960     clef_height = clap_height = (height == 486 ? 480 : height);
5961     clef_width = gst_util_uint64_scale (clef_height,
5962         dar_num * G_GUINT64_CONSTANT (65536), dar_den);
5963     prof_width = gst_util_uint64_scale (width,
5964         par_num * G_GUINT64_CONSTANT (65536), par_den);
5965     clap_width_n = clap_height * dar_num * par_den;
5966     clap_width_d = dar_den * par_num;
5967     cdiv = gst_util_greatest_common_divisor (clap_width_n, clap_width_d);
5968     clap_width_n /= cdiv;
5969     clap_width_d /= cdiv;
5970 
5971     ext_atom = build_tapt_extension (clef_width, clef_height << 16, prof_width,
5972         height << 16, width << 16, height << 16);
5973     qtpad->trak->tapt = ext_atom;
5974 
5975     ext_atom = build_clap_extension (clap_width_n, clap_width_d,
5976         clap_height, 1, 0, 1, 0, 1);
5977     if (ext_atom)
5978       ext_atom_list = g_list_append (ext_atom_list, ext_atom);
5979   }
5980 
5981   /* ok, set the pad info accordingly */
5982   qtpad->fourcc = entry.fourcc;
5983   qtpad->sync = sync;
5984   qtpad->trak_ste =
5985       (SampleTableEntry *) atom_trak_set_video_type (qtpad->trak,
5986       qtmux->context, &entry, rate, ext_atom_list);
5987   if (strcmp (mimetype, "video/x-prores") == 0) {
5988     SampleTableEntryMP4V *mp4v = (SampleTableEntryMP4V *) qtpad->trak_ste;
5989     const gchar *compressor = NULL;
5990     mp4v->spatial_quality = 0x3FF;
5991     mp4v->temporal_quality = 0;
5992     mp4v->vendor = FOURCC_appl;
5993     mp4v->horizontal_resolution = 72 << 16;
5994     mp4v->vertical_resolution = 72 << 16;
5995     mp4v->depth = (entry.fourcc == FOURCC_ap4h
5996         || entry.fourcc == FOURCC_ap4x) ? 32 : 24;
5997 
5998     /* Set compressor name, required by some software */
5999     switch (entry.fourcc) {
6000       case FOURCC_apcn:
6001         compressor = "Apple ProRes 422";
6002         break;
6003       case FOURCC_apcs:
6004         compressor = "Apple ProRes 422 LT";
6005         break;
6006       case FOURCC_apch:
6007         compressor = "Apple ProRes 422 HQ";
6008         break;
6009       case FOURCC_apco:
6010         compressor = "Apple ProRes 422 Proxy";
6011         break;
6012       case FOURCC_ap4h:
6013         compressor = "Apple ProRes 4444";
6014         break;
6015       case FOURCC_ap4x:
6016         compressor = "Apple ProRes 4444 XQ";
6017         break;
6018     }
6019     if (compressor) {
6020       strcpy ((gchar *) mp4v->compressor + 1, compressor);
6021       mp4v->compressor[0] = strlen (compressor);
6022     }
6023   }
6024 
6025   gst_object_unref (qtmux);
6026   return TRUE;
6027 
6028   /* ERRORS */
6029 refuse_caps:
6030   {
6031     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6032         GST_PAD_NAME (pad), caps);
6033     gst_object_unref (qtmux);
6034     return FALSE;
6035   }
6036 }
6037 
6038 static gboolean
gst_qt_mux_subtitle_sink_set_caps(GstQTPad * qtpad,GstCaps * caps)6039 gst_qt_mux_subtitle_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6040 {
6041   GstPad *pad = qtpad->collect.pad;
6042   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6043   GstStructure *structure;
6044   SubtitleSampleEntry entry = { 0, };
6045 
6046   if (qtpad->fourcc)
6047     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6048 
6049   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6050       GST_DEBUG_PAD_NAME (pad), caps);
6051 
6052   /* subtitles default */
6053   subtitle_sample_entry_init (&entry);
6054   qtpad->is_out_of_order = FALSE;
6055   qtpad->sync = FALSE;
6056   qtpad->sparse = TRUE;
6057   qtpad->prepare_buf_func = NULL;
6058 
6059   structure = gst_caps_get_structure (caps, 0);
6060 
6061   if (gst_structure_has_name (structure, "text/x-raw")) {
6062     const gchar *format = gst_structure_get_string (structure, "format");
6063     if (format && strcmp (format, "utf8") == 0) {
6064       entry.fourcc = FOURCC_tx3g;
6065       qtpad->prepare_buf_func = gst_qt_mux_prepare_tx3g_buffer;
6066       qtpad->create_empty_buffer = gst_qt_mux_create_empty_tx3g_buffer;
6067     }
6068   }
6069 
6070   if (!entry.fourcc)
6071     goto refuse_caps;
6072 
6073   qtpad->fourcc = entry.fourcc;
6074   qtpad->trak_ste =
6075       (SampleTableEntry *) atom_trak_set_subtitle_type (qtpad->trak,
6076       qtmux->context, &entry);
6077 
6078   gst_object_unref (qtmux);
6079   return TRUE;
6080 
6081   /* ERRORS */
6082 refuse_caps:
6083   {
6084     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6085         GST_PAD_NAME (pad), caps);
6086     gst_object_unref (qtmux);
6087     return FALSE;
6088   }
6089 }
6090 
6091 static gboolean
gst_qt_mux_caption_sink_set_caps(GstQTPad * qtpad,GstCaps * caps)6092 gst_qt_mux_caption_sink_set_caps (GstQTPad * qtpad, GstCaps * caps)
6093 {
6094   GstPad *pad = qtpad->collect.pad;
6095   GstQTMux *qtmux = GST_QT_MUX_CAST (gst_pad_get_parent (pad));
6096   GstStructure *structure;
6097   guint32 fourcc_entry;
6098   guint32 timescale;
6099 
6100   if (qtpad->fourcc)
6101     return gst_qt_mux_can_renegotiate (qtmux, pad, caps);
6102 
6103   GST_DEBUG_OBJECT (qtmux, "%s:%s, caps=%" GST_PTR_FORMAT,
6104       GST_DEBUG_PAD_NAME (pad), caps);
6105 
6106   /* captions default */
6107   qtpad->is_out_of_order = FALSE;
6108   qtpad->sync = FALSE;
6109   qtpad->sparse = TRUE;
6110   /* Closed caption data are within atoms */
6111   qtpad->prepare_buf_func = gst_qt_mux_prepare_caption_buffer;
6112 
6113   structure = gst_caps_get_structure (caps, 0);
6114 
6115   /* We know we only handle 608,format=s334-1a and 708,format=cdp */
6116   if (gst_structure_has_name (structure, "closedcaption/x-cea-608")) {
6117     fourcc_entry = FOURCC_c608;
6118   } else if (gst_structure_has_name (structure, "closedcaption/x-cea-708")) {
6119     fourcc_entry = FOURCC_c708;
6120   } else
6121     goto refuse_caps;
6122 
6123   /* We set the real timescale later to the one from the video track when
6124    * writing the headers */
6125   timescale = gst_qt_mux_pad_get_timescale (GST_QT_MUX_PAD_CAST (pad));
6126   if (!timescale && qtmux->trak_timescale)
6127     timescale = qtmux->trak_timescale;
6128   else if (!timescale)
6129     timescale = 30000;
6130 
6131   qtpad->fourcc = fourcc_entry;
6132   qtpad->trak_ste =
6133       (SampleTableEntry *) atom_trak_set_caption_type (qtpad->trak,
6134       qtmux->context, timescale, fourcc_entry);
6135 
6136   /* Initialize caption track language code to 0 unless something else is
6137    * specified. Without this, Final Cut considers it "non-standard"
6138    */
6139   qtpad->trak->mdia.mdhd.language_code = 0;
6140 
6141   gst_object_unref (qtmux);
6142   return TRUE;
6143 
6144   /* ERRORS */
6145 refuse_caps:
6146   {
6147     GST_WARNING_OBJECT (qtmux, "pad %s refused caps %" GST_PTR_FORMAT,
6148         GST_PAD_NAME (pad), caps);
6149     gst_object_unref (qtmux);
6150     return FALSE;
6151   }
6152 }
6153 
6154 static gboolean
gst_qt_mux_sink_event(GstCollectPads * pads,GstCollectData * data,GstEvent * event,gpointer user_data)6155 gst_qt_mux_sink_event (GstCollectPads * pads, GstCollectData * data,
6156     GstEvent * event, gpointer user_data)
6157 {
6158   GstQTMux *qtmux;
6159   guint32 avg_bitrate = 0, max_bitrate = 0;
6160   GstPad *pad = data->pad;
6161   gboolean ret = TRUE;
6162 
6163   qtmux = GST_QT_MUX_CAST (user_data);
6164   switch (GST_EVENT_TYPE (event)) {
6165     case GST_EVENT_CAPS:
6166     {
6167       GstCaps *caps;
6168       GstQTPad *collect_pad;
6169 
6170       gst_event_parse_caps (event, &caps);
6171 
6172       /* find stream data */
6173       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6174       g_assert (collect_pad);
6175       g_assert (collect_pad->set_caps);
6176 
6177       ret = collect_pad->set_caps (collect_pad, caps);
6178       gst_event_unref (event);
6179       event = NULL;
6180       break;
6181     }
6182     case GST_EVENT_TAG:{
6183       GstTagList *list;
6184       GstTagSetter *setter = GST_TAG_SETTER (qtmux);
6185       GstTagMergeMode mode;
6186       gchar *code;
6187       GstQTPad *collect_pad;
6188 
6189       GST_OBJECT_LOCK (qtmux);
6190       mode = gst_tag_setter_get_tag_merge_mode (setter);
6191       collect_pad = (GstQTPad *) gst_pad_get_element_private (pad);
6192 
6193       gst_event_parse_tag (event, &list);
6194       GST_DEBUG_OBJECT (qtmux, "received tag event on pad %s:%s : %"
6195           GST_PTR_FORMAT, GST_DEBUG_PAD_NAME (pad), list);
6196 
6197       if (gst_tag_list_get_scope (list) == GST_TAG_SCOPE_GLOBAL) {
6198         gst_tag_setter_merge_tags (setter, list, mode);
6199         qtmux->tags_changed = TRUE;
6200       } else {
6201         if (!collect_pad->tags)
6202           collect_pad->tags = gst_tag_list_new_empty ();
6203         gst_tag_list_insert (collect_pad->tags, list, mode);
6204         collect_pad->tags_changed = TRUE;
6205       }
6206       GST_OBJECT_UNLOCK (qtmux);
6207 
6208       if (gst_tag_list_get_uint (list, GST_TAG_BITRATE, &avg_bitrate) |
6209           gst_tag_list_get_uint (list, GST_TAG_MAXIMUM_BITRATE, &max_bitrate)) {
6210         GstQTPad *qtpad = gst_pad_get_element_private (pad);
6211         g_assert (qtpad);
6212 
6213         if (avg_bitrate > 0 && avg_bitrate < G_MAXUINT32)
6214           qtpad->avg_bitrate = avg_bitrate;
6215         if (max_bitrate > 0 && max_bitrate < G_MAXUINT32)
6216           qtpad->max_bitrate = max_bitrate;
6217       }
6218 
6219       if (gst_tag_list_get_string (list, GST_TAG_LANGUAGE_CODE, &code)) {
6220         const char *iso_code = gst_tag_get_language_code_iso_639_2T (code);
6221         if (iso_code) {
6222           GstQTPad *qtpad = gst_pad_get_element_private (pad);
6223           g_assert (qtpad);
6224           if (qtpad->trak) {
6225             /* https://developer.apple.com/library/mac/#documentation/QuickTime/QTFF/QTFFChap4/qtff4.html */
6226             qtpad->trak->mdia.mdhd.language_code = language_code (iso_code);
6227           }
6228         }
6229         g_free (code);
6230       }
6231 
6232       gst_event_unref (event);
6233       event = NULL;
6234       ret = TRUE;
6235       break;
6236     }
6237     default:
6238       break;
6239   }
6240 
6241   if (event != NULL)
6242     return gst_collect_pads_event_default (pads, data, event, FALSE);
6243 
6244   return ret;
6245 }
6246 
6247 static void
gst_qt_mux_release_pad(GstElement * element,GstPad * pad)6248 gst_qt_mux_release_pad (GstElement * element, GstPad * pad)
6249 {
6250   GstQTMux *mux = GST_QT_MUX_CAST (element);
6251   GSList *walk;
6252 
6253   GST_DEBUG_OBJECT (element, "Releasing %s:%s", GST_DEBUG_PAD_NAME (pad));
6254 
6255   for (walk = mux->sinkpads; walk; walk = g_slist_next (walk)) {
6256     GstQTPad *qtpad = (GstQTPad *) walk->data;
6257     GST_DEBUG ("Checking %s:%s", GST_DEBUG_PAD_NAME (qtpad->collect.pad));
6258     if (qtpad->collect.pad == pad) {
6259       /* this is it, remove */
6260       mux->sinkpads = g_slist_delete_link (mux->sinkpads, walk);
6261       gst_element_remove_pad (element, pad);
6262       break;
6263     }
6264   }
6265 
6266   if (mux->current_pad && mux->current_pad->collect.pad == pad) {
6267     mux->current_pad = NULL;
6268     mux->current_chunk_size = 0;
6269     mux->current_chunk_duration = 0;
6270   }
6271 
6272   gst_collect_pads_remove_pad (mux->collect, pad);
6273 
6274   if (mux->sinkpads == NULL) {
6275     /* No more outstanding request pads, reset our counters */
6276     mux->video_pads = 0;
6277     mux->audio_pads = 0;
6278     mux->subtitle_pads = 0;
6279   }
6280 }
6281 
6282 static GstPad *
gst_qt_mux_request_new_pad(GstElement * element,GstPadTemplate * templ,const gchar * req_name,const GstCaps * caps)6283 gst_qt_mux_request_new_pad (GstElement * element,
6284     GstPadTemplate * templ, const gchar * req_name, const GstCaps * caps)
6285 {
6286   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
6287   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6288   GstQTPad *collect_pad;
6289   GstPad *newpad;
6290   GstQTPadSetCapsFunc setcaps_func;
6291   gchar *name;
6292   gint pad_id;
6293   gboolean lock = TRUE;
6294 
6295   if (templ->direction != GST_PAD_SINK)
6296     goto wrong_direction;
6297 
6298   if (qtmux->state > GST_QT_MUX_STATE_STARTED)
6299     goto too_late;
6300 
6301   if (templ == gst_element_class_get_pad_template (klass, "audio_%u")) {
6302     setcaps_func = gst_qt_mux_audio_sink_set_caps;
6303     if (req_name != NULL && sscanf (req_name, "audio_%u", &pad_id) == 1) {
6304       name = g_strdup (req_name);
6305     } else {
6306       name = g_strdup_printf ("audio_%u", qtmux->audio_pads++);
6307     }
6308   } else if (templ == gst_element_class_get_pad_template (klass, "video_%u")) {
6309     setcaps_func = gst_qt_mux_video_sink_set_caps;
6310     if (req_name != NULL && sscanf (req_name, "video_%u", &pad_id) == 1) {
6311       name = g_strdup (req_name);
6312     } else {
6313       name = g_strdup_printf ("video_%u", qtmux->video_pads++);
6314     }
6315   } else if (templ == gst_element_class_get_pad_template (klass, "subtitle_%u")) {
6316     setcaps_func = gst_qt_mux_subtitle_sink_set_caps;
6317     if (req_name != NULL && sscanf (req_name, "subtitle_%u", &pad_id) == 1) {
6318       name = g_strdup (req_name);
6319     } else {
6320       name = g_strdup_printf ("subtitle_%u", qtmux->subtitle_pads++);
6321     }
6322     lock = FALSE;
6323   } else if (templ == gst_element_class_get_pad_template (klass, "caption_%u")) {
6324     setcaps_func = gst_qt_mux_caption_sink_set_caps;
6325     if (req_name != NULL && sscanf (req_name, "caption_%u", &pad_id) == 1) {
6326       name = g_strdup (req_name);
6327     } else {
6328       name = g_strdup_printf ("caption_%u", qtmux->caption_pads++);
6329     }
6330     lock = FALSE;
6331   } else
6332     goto wrong_template;
6333 
6334   GST_DEBUG_OBJECT (qtmux, "Requested pad: %s", name);
6335 
6336   /* create pad and add to collections */
6337   newpad =
6338       g_object_new (GST_TYPE_QT_MUX_PAD, "name", name, "direction",
6339       templ->direction, "template", templ, NULL);
6340   g_free (name);
6341   collect_pad = (GstQTPad *)
6342       gst_collect_pads_add_pad (qtmux->collect, newpad, sizeof (GstQTPad),
6343       (GstCollectDataDestroyNotify) (gst_qt_mux_pad_reset), lock);
6344   /* set up pad */
6345   gst_qt_mux_pad_reset (collect_pad);
6346   collect_pad->trak = atom_trak_new (qtmux->context);
6347   atom_moov_add_trak (qtmux->moov, collect_pad->trak);
6348 
6349   qtmux->sinkpads = g_slist_append (qtmux->sinkpads, collect_pad);
6350 
6351   /* set up pad functions */
6352   collect_pad->set_caps = setcaps_func;
6353 
6354   gst_pad_set_active (newpad, TRUE);
6355   gst_element_add_pad (element, newpad);
6356 
6357   return newpad;
6358 
6359   /* ERRORS */
6360 wrong_direction:
6361   {
6362     GST_WARNING_OBJECT (qtmux, "Request pad that is not a SINK pad.");
6363     return NULL;
6364   }
6365 too_late:
6366   {
6367     GST_WARNING_OBJECT (qtmux, "Not providing request pad after stream start.");
6368     return NULL;
6369   }
6370 wrong_template:
6371   {
6372     GST_WARNING_OBJECT (qtmux, "This is not our template!");
6373     return NULL;
6374   }
6375 }
6376 
6377 static void
gst_qt_mux_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)6378 gst_qt_mux_get_property (GObject * object,
6379     guint prop_id, GValue * value, GParamSpec * pspec)
6380 {
6381   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6382 
6383   GST_OBJECT_LOCK (qtmux);
6384   switch (prop_id) {
6385     case PROP_MOVIE_TIMESCALE:
6386       g_value_set_uint (value, qtmux->timescale);
6387       break;
6388     case PROP_TRAK_TIMESCALE:
6389       g_value_set_uint (value, qtmux->trak_timescale);
6390       break;
6391     case PROP_DO_CTTS:
6392       g_value_set_boolean (value, qtmux->guess_pts);
6393       break;
6394 #ifndef GST_REMOVE_DEPRECATED
6395     case PROP_DTS_METHOD:
6396       g_value_set_enum (value, qtmux->dts_method);
6397       break;
6398 #endif
6399     case PROP_FAST_START:
6400       g_value_set_boolean (value, qtmux->fast_start);
6401       break;
6402     case PROP_FAST_START_TEMP_FILE:
6403       g_value_set_string (value, qtmux->fast_start_file_path);
6404       break;
6405     case PROP_MOOV_RECOV_FILE:
6406       g_value_set_string (value, qtmux->moov_recov_file_path);
6407       break;
6408     case PROP_FRAGMENT_DURATION:
6409       g_value_set_uint (value, qtmux->fragment_duration);
6410       break;
6411     case PROP_STREAMABLE:
6412       g_value_set_boolean (value, qtmux->streamable);
6413       break;
6414     case PROP_RESERVED_MAX_DURATION:
6415       g_value_set_uint64 (value, qtmux->reserved_max_duration);
6416       break;
6417     case PROP_RESERVED_DURATION_REMAINING:
6418       if (qtmux->reserved_duration_remaining == GST_CLOCK_TIME_NONE)
6419         g_value_set_uint64 (value, qtmux->reserved_max_duration);
6420       else {
6421         GstClockTime remaining = qtmux->reserved_duration_remaining;
6422 
6423         /* Report the remaining space as the calculated remaining, minus
6424          * however much we've muxed since the last update */
6425         if (remaining > qtmux->muxed_since_last_update)
6426           remaining -= qtmux->muxed_since_last_update;
6427         else
6428           remaining = 0;
6429         GST_LOG_OBJECT (qtmux, "reserved duration remaining - reporting %"
6430             G_GUINT64_FORMAT "(%" G_GUINT64_FORMAT " - %" G_GUINT64_FORMAT,
6431             remaining, qtmux->reserved_duration_remaining,
6432             qtmux->muxed_since_last_update);
6433         g_value_set_uint64 (value, remaining);
6434       }
6435       break;
6436     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6437       g_value_set_uint64 (value, qtmux->reserved_moov_update_period);
6438       break;
6439     case PROP_RESERVED_BYTES_PER_SEC:
6440       g_value_set_uint (value, qtmux->reserved_bytes_per_sec_per_trak);
6441       break;
6442     case PROP_RESERVED_PREFILL:
6443       g_value_set_boolean (value, qtmux->reserved_prefill);
6444       break;
6445     case PROP_INTERLEAVE_BYTES:
6446       g_value_set_uint64 (value, qtmux->interleave_bytes);
6447       break;
6448     case PROP_INTERLEAVE_TIME:
6449       g_value_set_uint64 (value, qtmux->interleave_time);
6450       break;
6451     case PROP_MAX_RAW_AUDIO_DRIFT:
6452       g_value_set_uint64 (value, qtmux->max_raw_audio_drift);
6453       break;
6454     case PROP_START_GAP_THRESHOLD:
6455       g_value_set_uint64 (value, qtmux->start_gap_threshold);
6456       break;
6457     default:
6458       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6459       break;
6460   }
6461   GST_OBJECT_UNLOCK (qtmux);
6462 }
6463 
6464 static void
gst_qt_mux_generate_fast_start_file_path(GstQTMux * qtmux)6465 gst_qt_mux_generate_fast_start_file_path (GstQTMux * qtmux)
6466 {
6467   gchar *tmp;
6468 
6469   g_free (qtmux->fast_start_file_path);
6470   qtmux->fast_start_file_path = NULL;
6471 
6472   tmp = g_strdup_printf ("%s%d", "qtmux", g_random_int ());
6473   qtmux->fast_start_file_path = g_build_filename (g_get_tmp_dir (), tmp, NULL);
6474   g_free (tmp);
6475 }
6476 
6477 static void
gst_qt_mux_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)6478 gst_qt_mux_set_property (GObject * object,
6479     guint prop_id, const GValue * value, GParamSpec * pspec)
6480 {
6481   GstQTMux *qtmux = GST_QT_MUX_CAST (object);
6482 
6483   GST_OBJECT_LOCK (qtmux);
6484   switch (prop_id) {
6485     case PROP_MOVIE_TIMESCALE:
6486       qtmux->timescale = g_value_get_uint (value);
6487       break;
6488     case PROP_TRAK_TIMESCALE:
6489       qtmux->trak_timescale = g_value_get_uint (value);
6490       break;
6491     case PROP_DO_CTTS:
6492       qtmux->guess_pts = g_value_get_boolean (value);
6493       break;
6494 #ifndef GST_REMOVE_DEPRECATED
6495     case PROP_DTS_METHOD:
6496       qtmux->dts_method = g_value_get_enum (value);
6497       break;
6498 #endif
6499     case PROP_FAST_START:
6500       qtmux->fast_start = g_value_get_boolean (value);
6501       break;
6502     case PROP_FAST_START_TEMP_FILE:
6503       g_free (qtmux->fast_start_file_path);
6504       qtmux->fast_start_file_path = g_value_dup_string (value);
6505       /* NULL means to generate a random one */
6506       if (!qtmux->fast_start_file_path) {
6507         gst_qt_mux_generate_fast_start_file_path (qtmux);
6508       }
6509       break;
6510     case PROP_MOOV_RECOV_FILE:
6511       g_free (qtmux->moov_recov_file_path);
6512       qtmux->moov_recov_file_path = g_value_dup_string (value);
6513       break;
6514     case PROP_FRAGMENT_DURATION:
6515       qtmux->fragment_duration = g_value_get_uint (value);
6516       break;
6517     case PROP_STREAMABLE:{
6518       GstQTMuxClass *qtmux_klass =
6519           (GstQTMuxClass *) (G_OBJECT_GET_CLASS (qtmux));
6520       if (qtmux_klass->format == GST_QT_MUX_FORMAT_ISML) {
6521         qtmux->streamable = g_value_get_boolean (value);
6522       }
6523       break;
6524     }
6525     case PROP_RESERVED_MAX_DURATION:
6526       qtmux->reserved_max_duration = g_value_get_uint64 (value);
6527       break;
6528     case PROP_RESERVED_MOOV_UPDATE_PERIOD:
6529       qtmux->reserved_moov_update_period = g_value_get_uint64 (value);
6530       break;
6531     case PROP_RESERVED_BYTES_PER_SEC:
6532       qtmux->reserved_bytes_per_sec_per_trak = g_value_get_uint (value);
6533       break;
6534     case PROP_RESERVED_PREFILL:
6535       qtmux->reserved_prefill = g_value_get_boolean (value);
6536       break;
6537     case PROP_INTERLEAVE_BYTES:
6538       qtmux->interleave_bytes = g_value_get_uint64 (value);
6539       qtmux->interleave_bytes_set = TRUE;
6540       break;
6541     case PROP_INTERLEAVE_TIME:
6542       qtmux->interleave_time = g_value_get_uint64 (value);
6543       qtmux->interleave_time_set = TRUE;
6544       break;
6545     case PROP_MAX_RAW_AUDIO_DRIFT:
6546       qtmux->max_raw_audio_drift = g_value_get_uint64 (value);
6547       break;
6548     case PROP_START_GAP_THRESHOLD:
6549       qtmux->start_gap_threshold = g_value_get_uint64 (value);
6550       break;
6551     default:
6552       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6553       break;
6554   }
6555   GST_OBJECT_UNLOCK (qtmux);
6556 }
6557 
6558 static GstStateChangeReturn
gst_qt_mux_change_state(GstElement * element,GstStateChange transition)6559 gst_qt_mux_change_state (GstElement * element, GstStateChange transition)
6560 {
6561   GstStateChangeReturn ret;
6562   GstQTMux *qtmux = GST_QT_MUX_CAST (element);
6563 
6564   switch (transition) {
6565     case GST_STATE_CHANGE_NULL_TO_READY:
6566       break;
6567     case GST_STATE_CHANGE_READY_TO_PAUSED:
6568       gst_collect_pads_start (qtmux->collect);
6569       qtmux->state = GST_QT_MUX_STATE_STARTED;
6570       break;
6571     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
6572       break;
6573     case GST_STATE_CHANGE_PAUSED_TO_READY:
6574       gst_collect_pads_stop (qtmux->collect);
6575       break;
6576     default:
6577       break;
6578   }
6579 
6580   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6581 
6582   switch (transition) {
6583     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
6584       break;
6585     case GST_STATE_CHANGE_PAUSED_TO_READY:
6586       gst_qt_mux_reset (qtmux, TRUE);
6587       break;
6588     case GST_STATE_CHANGE_READY_TO_NULL:
6589       break;
6590     default:
6591       break;
6592   }
6593 
6594   return ret;
6595 }
6596 
6597 gboolean
gst_qt_mux_register(GstPlugin * plugin)6598 gst_qt_mux_register (GstPlugin * plugin)
6599 {
6600   GTypeInfo typeinfo = {
6601     sizeof (GstQTMuxClass),
6602     (GBaseInitFunc) gst_qt_mux_base_init,
6603     NULL,
6604     (GClassInitFunc) gst_qt_mux_class_init,
6605     NULL,
6606     NULL,
6607     sizeof (GstQTMux),
6608     0,
6609     (GInstanceInitFunc) gst_qt_mux_init,
6610   };
6611   static const GInterfaceInfo tag_setter_info = {
6612     NULL, NULL, NULL
6613   };
6614   static const GInterfaceInfo tag_xmp_writer_info = {
6615     NULL, NULL, NULL
6616   };
6617   static const GInterfaceInfo preset_info = {
6618     NULL, NULL, NULL
6619   };
6620   GType type;
6621   GstQTMuxFormat format;
6622   GstQTMuxClassParams *params;
6623   guint i = 0;
6624 
6625   GST_DEBUG_CATEGORY_INIT (gst_qt_mux_debug, "qtmux", 0, "QT Muxer");
6626 
6627   GST_LOG ("Registering muxers");
6628 
6629   while (TRUE) {
6630     GstQTMuxFormatProp *prop;
6631     GstCaps *subtitle_caps, *caption_caps;
6632 
6633     prop = &gst_qt_mux_format_list[i];
6634     format = prop->format;
6635     if (format == GST_QT_MUX_FORMAT_NONE)
6636       break;
6637 
6638     /* create a cache for these properties */
6639     params = g_new0 (GstQTMuxClassParams, 1);
6640     params->prop = prop;
6641     params->src_caps = gst_static_caps_get (&prop->src_caps);
6642     params->video_sink_caps = gst_static_caps_get (&prop->video_sink_caps);
6643     params->audio_sink_caps = gst_static_caps_get (&prop->audio_sink_caps);
6644     subtitle_caps = gst_static_caps_get (&prop->subtitle_sink_caps);
6645     if (!gst_caps_is_equal (subtitle_caps, GST_CAPS_NONE)) {
6646       params->subtitle_sink_caps = subtitle_caps;
6647     } else {
6648       gst_caps_unref (subtitle_caps);
6649     }
6650     caption_caps = gst_static_caps_get (&prop->caption_sink_caps);
6651     if (!gst_caps_is_equal (caption_caps, GST_CAPS_NONE)) {
6652       params->caption_sink_caps = caption_caps;
6653     } else {
6654       gst_caps_unref (caption_caps);
6655     }
6656 
6657     /* create the type now */
6658     type = g_type_register_static (GST_TYPE_ELEMENT, prop->type_name, &typeinfo,
6659         0);
6660     g_type_set_qdata (type, GST_QT_MUX_PARAMS_QDATA, (gpointer) params);
6661     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, &tag_setter_info);
6662     g_type_add_interface_static (type, GST_TYPE_TAG_XMP_WRITER,
6663         &tag_xmp_writer_info);
6664     g_type_add_interface_static (type, GST_TYPE_PRESET, &preset_info);
6665 
6666     if (!gst_element_register (plugin, prop->name, prop->rank, type))
6667       return FALSE;
6668 
6669     i++;
6670   }
6671 
6672   GST_LOG ("Finished registering muxers");
6673 
6674   /* FIXME: ideally classification tag should be added and
6675      registered in gstreamer core gsttaglist
6676    */
6677 
6678   GST_LOG ("Registering tags");
6679 
6680   gst_tag_register (GST_TAG_3GP_CLASSIFICATION, GST_TAG_FLAG_META,
6681       G_TYPE_STRING, GST_TAG_3GP_CLASSIFICATION, "content classification",
6682       gst_tag_merge_use_first);
6683 
6684   GST_LOG ("Finished registering tags");
6685 
6686   return TRUE;
6687 }
6688